├── Documentation
├── Images
│ └── Heap Performance.png
├── Announcement-benchmarks
│ ├── Results
│ │ ├── 03 OrderedSet lookups.png
│ │ ├── 04 OrderedSet insertions.png
│ │ ├── 05 OrderedDictionary lookups.png
│ │ ├── 01 Deque - random access lookups.png
│ │ ├── 06 OrderedDictionary insertions.png
│ │ └── 02 Deque - prepending individual integers.png
│ ├── generate-results.sh
│ ├── Results.md
│ └── README.md
└── Reviews
│ └── 2022-10-31.ShareableHashedCollections
│ ├── ShareableSet-insert.png
│ ├── ShareableSet-model-diffing.png
│ └── ShareableSet-sequential iteration.png
├── .swiftci
├── nightly_6_0_macos
├── nightly_main_macos
├── 5_10_ubuntu2204
├── 5_7_ubuntu2204
├── 5_8_ubuntu2204
├── 5_9_ubuntu2204
├── nightly_6_0_ubuntu2204
├── nightly_main_ubuntu2204
└── nightly_main_windows
├── Sources
├── HeapModule
│ ├── HeapModule.docc
│ │ ├── Extensions
│ │ │ └── Heap.md
│ │ └── HeapModule.md
│ ├── CMakeLists.txt
│ ├── Heap+ExpressibleByArrayLiteral.swift
│ └── Heap+Descriptions.swift
├── DequeModule
│ ├── DequeModule.docc
│ │ ├── Extensions
│ │ │ └── Deque.md
│ │ └── DequeModule.md
│ ├── Deque+CustomReflectable.swift
│ ├── Deque+Hashable.swift
│ ├── Deque+Descriptions.swift
│ ├── Deque+Equatable.swift
│ ├── Deque+ExpressibleByArrayLiteral.swift
│ ├── CMakeLists.txt
│ └── _DequeBufferHeader.swift
├── Collections
│ ├── Collections.docc
│ │ └── Extensions
│ │ │ ├── Heap.md
│ │ │ ├── Deque.md
│ │ │ ├── OrderedDictionary.Values.md
│ │ │ ├── OrderedDictionary.Elements.md
│ │ │ └── OrderedSet.UnorderedView.md
│ ├── CMakeLists.txt
│ └── Collections.swift
├── ContainersPreview
│ ├── ContainersPreview.docc
│ │ └── ContainersPreview.md
│ ├── CMakeLists.txt
│ └── Ref.swift
├── BitCollections
│ ├── BitCollections.docc
│ │ └── BitCollections.md
│ ├── BitSet
│ │ ├── BitSet+SetAlgebra conformance.swift
│ │ ├── BitSet+CustomReflectable.swift
│ │ ├── BitSet+CustomDebugStringConvertible.swift
│ │ ├── BitSet+CustomStringConvertible.swift
│ │ ├── BitSet+Hashable.swift
│ │ ├── BitSet+Equatable.swift
│ │ ├── BitSet+ExpressibleByArrayLiteral.swift
│ │ ├── BitSet+Random.swift
│ │ ├── BitSet+Codable.swift
│ │ ├── BitSet+Invariants.swift
│ │ └── BitSet+Sorted Collection APIs.swift
│ ├── Shared
│ │ ├── Slice+Utilities.swift
│ │ ├── Range+Utilities.swift
│ │ └── UInt+Tricks.swift
│ └── BitArray
│ │ ├── BitArray+Testing.swift
│ │ ├── BitArray+ExpressibleByArrayLiteral.swift
│ │ ├── BitArray+CustomReflectable.swift
│ │ ├── BitArray+ExpressibleByStringLiteral.swift
│ │ ├── BitArray+Hashable.swift
│ │ ├── BitArray+Equatable.swift
│ │ ├── BitArray+Invariants.swift
│ │ └── BitArray+RandomBits.swift
├── OrderedCollections
│ ├── OrderedCollections.docc
│ │ ├── OrderedCollections.md
│ │ └── Extensions
│ │ │ ├── OrderedDictionary.Values.md
│ │ │ ├── OrderedDictionary.Elements.md
│ │ │ └── OrderedSet.UnorderedView.md
│ ├── OrderedSet
│ │ ├── OrderedSet+Sendable.swift
│ │ ├── OrderedSet+CustomReflectable.swift
│ │ ├── OrderedSet+Hashable.swift
│ │ ├── OrderedSet+Descriptions.swift
│ │ ├── OrderedSet+Equatable.swift
│ │ ├── OrderedSet+ExpressibleByArrayLiteral.swift
│ │ └── OrderedSet+UnstableInternals.swift
│ ├── OrderedDictionary
│ │ ├── OrderedDictionary+Sendable.swift
│ │ ├── OrderedDictionary+CustomReflectable.swift
│ │ ├── OrderedDictionary+Hashable.swift
│ │ ├── OrderedDictionary+Equatable.swift
│ │ ├── OrderedDictionary+Descriptions.swift
│ │ ├── OrderedDictionary+Invariants.swift
│ │ └── OrderedDictionary+ExpressibleByDictionaryLiteral.swift
│ ├── Utilities
│ │ └── _UnsafeBitset.swift
│ └── HashTable
│ │ └── _HashTable+Bucket.swift
├── HashTreeCollections
│ ├── HashTreeCollections.docc
│ │ └── HashTreeCollections.md
│ ├── TreeSet
│ │ ├── TreeSet+Sendable.swift
│ │ ├── TreeSet+CustomReflectable.swift
│ │ ├── TreeSet+Hashable.swift
│ │ ├── TreeSet+Descriptions.swift
│ │ ├── TreeSet+Equatable.swift
│ │ ├── TreeSet+Debugging.swift
│ │ └── TreeSet+ExpressibleByArrayLiteral.swift
│ ├── TreeDictionary
│ │ ├── TreeDictionary+Sendable.swift
│ │ ├── TreeDictionary+CustomReflectable.swift
│ │ ├── TreeDictionary+Equatable.swift
│ │ ├── TreeDictionary+Descriptions.swift
│ │ ├── TreeDictionary+Hashable.swift
│ │ ├── TreeDictionary+Debugging.swift
│ │ └── TreeDictionary+ExpressibleByDictionaryLiteral.swift
│ └── HashNode
│ │ └── _HashNode+Structural compactMapValues.swift
├── SortedCollections
│ ├── SortedSet
│ │ ├── SortedSet+Sendable.swift
│ │ ├── SortedSet+CustomReflectable.swift
│ │ ├── SortedSet+Hashable.swift
│ │ ├── SortedSet.swift
│ │ ├── SortedSet+Equatable.swift
│ │ ├── SortedSet+CustomStringConvertible.swift
│ │ └── SortedSet+ExpressibleByArrayLiteral.swift
│ ├── SortedDictionary
│ │ ├── SortedDictionary+Sendable.swift
│ │ ├── SortedDictionary+CustomReflectable.swift
│ │ ├── SortedDictionary+Hashable.swift
│ │ ├── SortedDictionary+Equatable.swift
│ │ ├── SortedDictionary+ExpressibleByDictionaryLiteral.swift
│ │ └── SortedDictionary+CustomStringConvertible.swift
│ └── BTree
│ │ ├── _Node+CustomDebugString.swift
│ │ ├── _BTree+CustomReflectable.swift
│ │ └── _BTree+CustomDebugStringConvertible.swift
├── RopeModule
│ ├── Utilities
│ │ └── Optional Utilities.swift
│ ├── BigString
│ │ ├── Basics
│ │ │ ├── BigString+Debugging.swift
│ │ │ ├── BigString.swift
│ │ │ └── BigString+Invariants.swift
│ │ ├── Conformances
│ │ │ ├── BigString+CustomStringConvertible.swift
│ │ │ ├── BigString+LosslessStringConvertible.swift
│ │ │ ├── BigString+ExpressibleByStringLiteral.swift
│ │ │ ├── BigString+CustomDebugStringConvertible.swift
│ │ │ ├── BigString+TextOutputStream.swift
│ │ │ └── BigString+Comparable.swift
│ │ ├── Operations
│ │ │ ├── Range+BigString.swift
│ │ │ └── BigString+Split.swift
│ │ └── Chunk
│ │ │ └── BigString+Chunk+UTF8.swift
│ └── Rope
│ │ ├── Basics
│ │ ├── _RopeVersion.swift
│ │ ├── RopeMetric.swift
│ │ └── Rope+_UnmanagedLeaf.swift
│ │ └── Conformances
│ │ └── Rope+Sequence.swift
├── InternalCollectionsUtilities
│ ├── UnsafeRawBufferPointer+Extras.swift
│ ├── UnsafeMutableRawBufferPointer+Extras.swift
│ ├── IntegerTricks
│ │ ├── FixedWidthInteger+roundUpToPowerOfTwo.swift
│ │ ├── UInt+first and last set bit.swift
│ │ └── UInt+reversed.swift
│ ├── RandomAccessCollection+Offsets.swift
│ ├── Debugging.swift
│ ├── _SortedCollection.swift
│ └── CMakeLists.txt
├── TrailingElementsModule
│ ├── CMakeLists.txt
│ └── TrailingElements.swift
└── BasicContainers
│ └── CMakeLists.txt
├── .gitignore
├── Xcode
├── Collections.xcodeproj
│ └── project.xcworkspace
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata
│ │ └── IDEWorkspaceChecks.plist
├── Collections.xctestplan
├── README.md
├── CollectionsTests.xcconfig
└── Collections.xcconfig
├── .spi.yml
├── CODE_OF_CONDUCT.md
├── .github
├── ISSUE_TEMPLATE
│ ├── config.yml
│ ├── FEATURE_REQUEST.md
│ └── BUG_REPORT.md
└── PULL_REQUEST_TEMPLATE.md
├── Tests
├── README.md
├── RopeModuleTests
│ └── Availability.swift
├── _CollectionsTestSupport
│ ├── Utilities
│ │ ├── ClassBox.swift
│ │ ├── AllOnesRandomNumberGenerator.swift
│ │ ├── Integer Square Root.swift
│ │ ├── HashableBox.swift
│ │ ├── StringConvertibleValue.swift
│ │ ├── SortedCollectionAPIChecker.swift
│ │ └── LifetimeTrackedStruct.swift
│ ├── MinimalTypes
│ │ └── ResettableValue.swift
│ └── AssertionContexts
│ │ └── CollectionTestCase.swift
├── ContainersTests
│ ├── RefTests.swift
│ ├── MutTests.swift
│ └── BoxTests.swift
├── CollectionsTestSupportTests
│ ├── UtilitiesTests.swift
│ ├── IndexRangeCollectionTests.swift
│ └── MinimalTypeConformances.swift
├── SortedCollectionsTests
│ ├── BTree
│ │ └── BTree.Builder Tests.swift
│ └── SortedDictionary
│ │ └── SortedDictionary Utils.swift
├── HeapTests
│ └── HeapNodeTests.swift
├── OrderedCollectionsTests
│ └── OrderedDictionary
│ │ └── OrderedDictionary Utils.swift
└── HashTreeCollectionsTests
│ └── TreeDictionary.Values Tests.swift
├── Utils
├── swift-collections.xcworkspace
│ ├── xcshareddata
│ │ ├── IDEWorkspaceChecks.plist
│ │ ├── swiftpm
│ │ │ └── Package.resolved
│ │ └── IDETemplateMacros.plist
│ └── contents.xcworkspacedata
├── README.md
├── shuffle-sources.sh
└── run-benchmarks.sh
├── Benchmarks
├── Sources
│ ├── CppBenchmarks
│ │ ├── include
│ │ │ ├── module.modulemap
│ │ │ ├── Hashing.h
│ │ │ ├── Utils.h
│ │ │ └── MapBenchmarks.h
│ │ └── src
│ │ │ ├── Utils.cpp
│ │ │ ├── CustomHash.h
│ │ │ ├── Hashing.cpp
│ │ │ └── PriorityQueueBenchmarks.cpp
│ ├── Benchmarks
│ │ ├── Foundation
│ │ │ └── FoundationBenchmarks.swift
│ │ └── Cpp
│ │ │ ├── CppBenchmarks.swift
│ │ │ └── CppMapBenchmarks.swift
│ └── benchmark-tool
│ │ └── main.swift
└── Package.resolved
├── cmake
└── modules
│ ├── SwiftCollectionsConfig.cmake.in
│ └── CMakeLists.txt
├── CONTRIBUTING.md
├── CODEOWNERS
└── .editorconfig
/Documentation/Images/Heap Performance.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apple/swift-collections/HEAD/Documentation/Images/Heap Performance.png
--------------------------------------------------------------------------------
/.swiftci/nightly_6_0_macos:
--------------------------------------------------------------------------------
1 | macOSSwiftPackageJob {
2 | swift_version = "6.0"
3 | repo = "swift-collections"
4 | branch = "main"
5 | }
6 |
--------------------------------------------------------------------------------
/.swiftci/nightly_main_macos:
--------------------------------------------------------------------------------
1 | macOSSwiftPackageJob {
2 | swift_version = "main"
3 | repo = "swift-collections"
4 | branch = "main"
5 | }
6 |
--------------------------------------------------------------------------------
/.swiftci/5_10_ubuntu2204:
--------------------------------------------------------------------------------
1 | LinuxSwiftPackageJob {
2 | swift_version_tag = "5.10-jammy"
3 | repo = "swift-collections"
4 | branch = "main"
5 | }
6 |
--------------------------------------------------------------------------------
/.swiftci/5_7_ubuntu2204:
--------------------------------------------------------------------------------
1 | LinuxSwiftPackageJob {
2 | swift_version_tag = "5.7-jammy"
3 | repo = "swift-collections"
4 | branch = "main"
5 | }
6 |
--------------------------------------------------------------------------------
/.swiftci/5_8_ubuntu2204:
--------------------------------------------------------------------------------
1 | LinuxSwiftPackageJob {
2 | swift_version_tag = "5.8-jammy"
3 | repo = "swift-collections"
4 | branch = "main"
5 | }
6 |
--------------------------------------------------------------------------------
/.swiftci/5_9_ubuntu2204:
--------------------------------------------------------------------------------
1 | LinuxSwiftPackageJob {
2 | swift_version_tag = "5.9-jammy"
3 | repo = "swift-collections"
4 | branch = "main"
5 | }
6 |
--------------------------------------------------------------------------------
/Sources/HeapModule/HeapModule.docc/Extensions/Heap.md:
--------------------------------------------------------------------------------
1 | # ``HeapModule/Heap``
2 |
3 |
4 |
5 |
6 |
7 | ## Topics
8 |
--------------------------------------------------------------------------------
/Sources/DequeModule/DequeModule.docc/Extensions/Deque.md:
--------------------------------------------------------------------------------
1 | # ``DequeModule/Deque``
2 |
3 |
4 |
5 |
6 |
7 | ## Topics
8 |
--------------------------------------------------------------------------------
/.swiftci/nightly_6_0_ubuntu2204:
--------------------------------------------------------------------------------
1 | LinuxSwiftPackageJob {
2 | nightly_docker_tag = "nightly-6.0-jammy"
3 | repo = "swift-collections"
4 | branch = "main"
5 | }
6 |
--------------------------------------------------------------------------------
/.swiftci/nightly_main_ubuntu2204:
--------------------------------------------------------------------------------
1 | LinuxSwiftPackageJob {
2 | nightly_docker_tag = "nightly-jammy"
3 | repo = "swift-collections"
4 | branch = "main"
5 | }
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | /.swiftpm
3 | /.build
4 | /Packages
5 | /*.xcodeproj
6 | xcuserdata/
7 | .*.sw?
8 | /Benchmarks/.swiftpm
9 | /Benchmarks/.build
10 | .docc-build
11 | __pycache__
12 |
--------------------------------------------------------------------------------
/Documentation/Announcement-benchmarks/Results/03 OrderedSet lookups.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apple/swift-collections/HEAD/Documentation/Announcement-benchmarks/Results/03 OrderedSet lookups.png
--------------------------------------------------------------------------------
/Documentation/Announcement-benchmarks/Results/04 OrderedSet insertions.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apple/swift-collections/HEAD/Documentation/Announcement-benchmarks/Results/04 OrderedSet insertions.png
--------------------------------------------------------------------------------
/Documentation/Announcement-benchmarks/Results/05 OrderedDictionary lookups.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apple/swift-collections/HEAD/Documentation/Announcement-benchmarks/Results/05 OrderedDictionary lookups.png
--------------------------------------------------------------------------------
/Documentation/Announcement-benchmarks/Results/01 Deque - random access lookups.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apple/swift-collections/HEAD/Documentation/Announcement-benchmarks/Results/01 Deque - random access lookups.png
--------------------------------------------------------------------------------
/Documentation/Announcement-benchmarks/Results/06 OrderedDictionary insertions.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apple/swift-collections/HEAD/Documentation/Announcement-benchmarks/Results/06 OrderedDictionary insertions.png
--------------------------------------------------------------------------------
/Documentation/Reviews/2022-10-31.ShareableHashedCollections/ShareableSet-insert.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apple/swift-collections/HEAD/Documentation/Reviews/2022-10-31.ShareableHashedCollections/ShareableSet-insert.png
--------------------------------------------------------------------------------
/Sources/DequeModule/DequeModule.docc/DequeModule.md:
--------------------------------------------------------------------------------
1 | # ``DequeModule``
2 |
3 | Summary
4 |
5 | ## Overview
6 |
7 | Text
8 |
9 |
--------------------------------------------------------------------------------
/Xcode/Collections.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.spi.yml:
--------------------------------------------------------------------------------
1 | version: 1
2 | builder:
3 | configs:
4 | - documentation_targets: [Collections, BasicContainers, BitCollections, ContainersPreview, DequeModule, HashTreeCollections, HeapModule, OrderedCollections, TrailingElementsModule]
5 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Code of Conduct
2 |
3 | The code of conduct for this project can be found at https://swift.org/code-of-conduct.
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Documentation/Announcement-benchmarks/Results/02 Deque - prepending individual integers.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apple/swift-collections/HEAD/Documentation/Announcement-benchmarks/Results/02 Deque - prepending individual integers.png
--------------------------------------------------------------------------------
/Documentation/Reviews/2022-10-31.ShareableHashedCollections/ShareableSet-model-diffing.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apple/swift-collections/HEAD/Documentation/Reviews/2022-10-31.ShareableHashedCollections/ShareableSet-model-diffing.png
--------------------------------------------------------------------------------
/Sources/Collections/Collections.docc/Extensions/Heap.md:
--------------------------------------------------------------------------------
1 | # ``Collections/Heap``
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | ## Topics
11 |
--------------------------------------------------------------------------------
/Sources/Collections/Collections.docc/Extensions/Deque.md:
--------------------------------------------------------------------------------
1 | # ``Collections/Deque``
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | ## Topics
11 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: false
2 | contact_links:
3 | - name: ❓ Discussion Forum
4 | url: https://forums.swift.org/c/related-projects/collections/
5 | about: Questions about using Swift Collections? Ask here!
6 |
--------------------------------------------------------------------------------
/Documentation/Reviews/2022-10-31.ShareableHashedCollections/ShareableSet-sequential iteration.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apple/swift-collections/HEAD/Documentation/Reviews/2022-10-31.ShareableHashedCollections/ShareableSet-sequential iteration.png
--------------------------------------------------------------------------------
/.swiftci/nightly_main_windows:
--------------------------------------------------------------------------------
1 | WindowsSwiftPackageWithDockerImageJob {
2 | docker_image = "swiftlang/swift:nightly-windowsservercore-1809"
3 | repo = "swift-collections"
4 | branch = "main"
5 | sub_dir = "swift-collections"
6 | label = "windows-server-2019"
7 | }
8 |
--------------------------------------------------------------------------------
/Sources/HeapModule/HeapModule.docc/HeapModule.md:
--------------------------------------------------------------------------------
1 | # ``HeapModule``
2 |
3 | Summary
4 |
5 | ## Overview
6 |
7 | Text
8 |
9 | ## Topics
10 |
11 | ### Structures
12 |
13 | - ``Heap``
14 |
--------------------------------------------------------------------------------
/Tests/README.md:
--------------------------------------------------------------------------------
1 | # Unit tests
2 |
3 | Beware! The contents of this directory are not source stable. They are provided as is, with no compatibility promises across package releases. Future versions of this package can arbitrarily change these files or remove them, without any advance notice. (This can include patch releases.)
4 |
--------------------------------------------------------------------------------
/Utils/swift-collections.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Xcode/Collections.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/CppBenchmarks/include/module.modulemap:
--------------------------------------------------------------------------------
1 | module CppBenchmarks {
2 | header "Utils.h"
3 | header "Hashing.h"
4 | header "VectorBenchmarks.h"
5 | header "DequeBenchmarks.h"
6 | header "UnorderedSetBenchmarks.h"
7 | header "UnorderedMapBenchmarks.h"
8 | header "MapBenchmarks.h"
9 | header "PriorityQueueBenchmarks.h"
10 | header "VectorBoolBenchmarks.h"
11 | export *
12 | }
13 |
--------------------------------------------------------------------------------
/Sources/ContainersPreview/ContainersPreview.docc/ContainersPreview.md:
--------------------------------------------------------------------------------
1 | # ``ContainersPreview``
2 |
3 | ## Overview
4 |
5 | This module provides previews of new standard constructs intended to aide using Swift's ownership facilities.
6 |
7 | This currently consists of a ``Box`` type that provides a noncopyable, heap-allocated box wrapping an arbitrary Swift value.
8 |
9 | ## Topics
10 |
11 | ### Structures
12 |
13 | - ``Box``
14 |
--------------------------------------------------------------------------------
/Utils/swift-collections.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
9 |
10 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/cmake/modules/SwiftCollectionsConfig.cmake.in:
--------------------------------------------------------------------------------
1 | #[[
2 | This source file is part of the Swift Collections Open Source Project
3 |
4 | Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
5 | Licensed under Apache License v2.0 with Runtime Library Exception
6 |
7 | See https://swift.org/LICENSE.txt for license information
8 | #]]
9 |
10 | if(NOT TARGET SwiftCollections)
11 | include(@SWIFT_COLLECTIONS_EXPORTS_FILE@)
12 | endif()
13 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | By submitting a pull request, you represent that you have the right to license
2 | your contribution to Apple and the community, and agree by submitting the patch
3 | that your contributions are licensed under the [Swift
4 | license](https://swift.org/LICENSE.txt).
5 |
6 | ---
7 |
8 | Before submitting the pull request, please make sure you have tested your
9 | changes and that they follow the Swift project [guidelines for contributing
10 | code](https://swift.org/contributing/#contributing-code).
11 |
12 |
--------------------------------------------------------------------------------
/CODEOWNERS:
--------------------------------------------------------------------------------
1 | # Lines starting with '#' are comments.
2 | # Each line is a case-sensitive file pattern followed by one or more owners.
3 | # Order is important. The last matching pattern has the most precedence.
4 | # More information: https://docs.github.com/en/articles/about-code-owners
5 | #
6 | # Please mirror the repository's file hierarchy in case-sensitive lexicographic
7 | # order.
8 |
9 | # Default owners
10 | * @lorentey
11 |
12 | # Swift CI configuration files
13 | .swiftci/ @shahmishal
14 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitCollections.docc/BitCollections.md:
--------------------------------------------------------------------------------
1 | # ``BitCollections``
2 |
3 | **Swift Collections** is an open-source package of data structure implementations for the Swift programming language.
4 |
5 | ## Overview
6 |
7 |
8 |
9 | #### Additional Resources
10 |
11 | - [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/)
12 | - [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72)
13 |
14 |
15 | ## Topics
16 |
17 | ### Structures
18 |
19 | - ``BitSet``
20 | - ``BitArray``
21 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitSet/BitSet+SetAlgebra conformance.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension BitSet: SetAlgebra {}
13 |
--------------------------------------------------------------------------------
/Xcode/Collections.xctestplan:
--------------------------------------------------------------------------------
1 | {
2 | "configurations" : [
3 | {
4 | "id" : "18C3508F-98DB-45BE-9CFC-5159D79BA600",
5 | "name" : "Test Scheme Action",
6 | "options" : {
7 |
8 | }
9 | }
10 | ],
11 | "defaultOptions" : {
12 |
13 | },
14 | "testTargets" : [
15 | {
16 | "parallelizable" : true,
17 | "target" : {
18 | "containerPath" : "container:Collections.xcodeproj",
19 | "identifier" : "7DE91B2D29CA6721004483EB",
20 | "name" : "CollectionsTests"
21 | }
22 | }
23 | ],
24 | "version" : 1
25 | }
26 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedCollections.docc/OrderedCollections.md:
--------------------------------------------------------------------------------
1 | # ``OrderedCollections``
2 |
3 | **Swift Collections** is an open-source package of data structure implementations for the Swift programming language.
4 |
5 | ## Overview
6 |
7 |
8 |
9 | #### Additional Resources
10 |
11 | - [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/)
12 | - [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72)
13 |
14 |
15 | ## Topics
16 |
17 | ### Structures
18 |
19 | - ``OrderedSet``
20 | - ``OrderedDictionary``
21 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/HashTreeCollections.docc/HashTreeCollections.md:
--------------------------------------------------------------------------------
1 | # ``HashTreeCollections``
2 |
3 | **Swift Collections** is an open-source package of data structure implementations for the Swift programming language.
4 |
5 | ## Overview
6 |
7 |
8 |
9 | #### Additional Resources
10 |
11 | - [`Swift Collections` on GitHub](https://github.com/apple/swift-collections/)
12 | - [`Swift Collections` on the Swift Forums](https://forums.swift.org/c/related-projects/collections/72)
13 |
14 |
15 | ## Topics
16 |
17 | ### Persistent Collections
18 |
19 | - ``TreeSet``
20 | - ``TreeDictionary``
21 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeSet/TreeSet+Sendable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension TreeSet: @unchecked Sendable where Element: Sendable {}
13 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.Values.md:
--------------------------------------------------------------------------------
1 | # ``OrderedCollections/OrderedDictionary/Values-swift.struct``
2 |
3 | ## Topics
4 |
5 | ### Inspecting a Values Collection
6 |
7 | - ``isEmpty``
8 | - ``count``
9 |
10 | ### Accessing Elements
11 |
12 | - ``subscript(_:)-25vfz``
13 | - ``elements``
14 | - ``withUnsafeBufferPointer(_:)``
15 | - ``withUnsafeMutableBufferPointer(_:)``
16 |
17 | ### Reordering Elements
18 |
19 | - ``swapAt(_:_:)-77eiy``
20 | - ``partition(by:)-9x0i5``
21 | - ``sort()``
22 | - ``sort(by:)``
23 | - ``shuffle()``
24 | - ``shuffle(using:)``
25 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedSet/OrderedSet+Sendable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension OrderedSet: @unchecked Sendable where Element: Sendable {}
13 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: 💡 Feature Request
3 | about: A suggestion for a new feature
4 | labels: enhancement
5 | ---
6 |
7 |
13 |
14 | Replace this paragraph with a description of your proposed feature.
15 | Please be sure to describe some concrete use cases for the new feature -- be as specific as possible.
16 | Provide links to existing issues or external references/discussions, if appropriate.
17 |
--------------------------------------------------------------------------------
/Xcode/README.md:
--------------------------------------------------------------------------------
1 | # Xcode build files
2 |
3 | The project file here is used to build a variant of this package with Xcode. The project file is a regular Xcode project that builds the code base using the COLLECTIONS_SINGLE_MODULE configuration, producing a single framework bundle. Builds settings are entirely configured via the provided xcconfig files.
4 |
5 | Beware! The contents of this directory are not source stable. They are provided as is, with no compatibility promises across package releases. Future versions of this package can arbitrarily change these files or remove them, without any advance notice. (This can include patch releases.)
6 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sendable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension TreeDictionary: @unchecked Sendable
13 | where Key: Sendable, Value: Sendable {}
14 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Sendable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension OrderedDictionary: @unchecked Sendable
13 | where Key: Sendable, Value: Sendable {}
14 |
--------------------------------------------------------------------------------
/Sources/Collections/Collections.docc/Extensions/OrderedDictionary.Values.md:
--------------------------------------------------------------------------------
1 | # ``Collections/OrderedDictionary/Values-swift.struct``
2 |
3 |
4 |
5 |
6 | ## Topics
7 |
8 | ### Inspecting a Values Collection
9 |
10 | - ``isEmpty``
11 | - ``count``
12 |
13 | ### Accessing Elements
14 |
15 | - ``subscript(_:)-25vfz``
16 | - ``elements``
17 | - ``withUnsafeBufferPointer(_:)``
18 | - ``withUnsafeMutableBufferPointer(_:)``
19 |
20 | ### Reordering Elements
21 |
22 | - ``swapAt(_:_:)-77eiy``
23 | - ``partition(by:)-9x0i5``
24 | - ``sort()``
25 | - ``sort(by:)``
26 | - ``shuffle()``
27 | - ``shuffle(using:)``
28 |
--------------------------------------------------------------------------------
/Sources/BitCollections/Shared/Slice+Utilities.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension Slice {
13 | internal var _bounds: Range {
14 | Range(uncheckedBounds: (startIndex, endIndex))
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedSet/SortedSet+Sendable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | extension SortedSet: @unchecked Sendable where Element: Sendable {}
15 |
16 | #endif
17 |
--------------------------------------------------------------------------------
/Tests/RopeModuleTests/Availability.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | var isRunningOnSwiftStdlib5_8: Bool {
13 | if #available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *) {
14 | return true
15 | }
16 | return false
17 | }
18 |
--------------------------------------------------------------------------------
/Sources/RopeModule/Utilities/Optional Utilities.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension Optional {
13 | @inlinable
14 | internal mutating func _take() -> Self {
15 | let r = self
16 | self = nil
17 | return r
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedDictionary/SortedDictionary+Sendable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | extension SortedDictionary: @unchecked Sendable
15 | where Key: Sendable, Value: Sendable {}
16 |
17 | #endif
18 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/Utilities/_UnsafeBitset.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 |
15 | @usableFromInline
16 | internal typealias _UnsafeBitSet = InternalCollectionsUtilities._UnsafeBitSet
17 | #endif
18 |
--------------------------------------------------------------------------------
/Tests/_CollectionsTestSupport/Utilities/ClassBox.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift.org open source project
4 | //
5 | // Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10 | //
11 | //===----------------------------------------------------------------------===//
12 |
13 | public final class ClassBox {
14 | public init(_ value: T) { self.value = value }
15 | public var value: T
16 | }
17 |
--------------------------------------------------------------------------------
/Utils/swift-collections.xcworkspace/xcshareddata/swiftpm/Package.resolved:
--------------------------------------------------------------------------------
1 | {
2 | "pins" : [
3 | {
4 | "identity" : "swift-argument-parser",
5 | "kind" : "remoteSourceControl",
6 | "location" : "https://github.com/apple/swift-argument-parser",
7 | "state" : {
8 | "revision" : "41982a3656a71c768319979febd796c6fd111d5c",
9 | "version" : "1.5.0"
10 | }
11 | },
12 | {
13 | "identity" : "swift-system",
14 | "kind" : "remoteSourceControl",
15 | "location" : "https://github.com/apple/swift-system",
16 | "state" : {
17 | "revision" : "a34201439c74b53f0fd71ef11741af7e7caf01e1",
18 | "version" : "1.4.2"
19 | }
20 | }
21 | ],
22 | "version" : 2
23 | }
24 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | insert_final_newline = true
6 | end_of_line = lf
7 | trim_trailing_whitespace = true
8 |
9 | [*.{swift,swift.gyb,cpp,h,yml}]
10 | indent_style = space
11 | tab_width = 4
12 | indent_size = 2
13 |
14 | [*.{sh,py}]
15 | indent_style = space
16 | indent_size = 4
17 |
18 | [.swiftci/*}]
19 | indent_style = space
20 | indent_size = 4
21 |
22 | [CMakeLists.txt]
23 | indent_style = space
24 | indent_size = 2
25 |
26 | [*.cmake{,.in}]
27 | indent_style = space
28 | indent_size = 2
29 |
30 | [*.{md,txt}]
31 | indent_style = space
32 | indent_size = 2
33 |
34 | [*.xcconfig]
35 | indent_style = space
36 | indent_size = 2
37 |
38 | [*.pbxproj]
39 | indent_style = tab
40 | tab_width = 4
41 | indent_size = 4
42 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/Benchmarks/Foundation/FoundationBenchmarks.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | import CollectionsBenchmark
13 |
14 | extension Benchmark {
15 | public mutating func addFoundationBenchmarks() {
16 | _addCFBinaryHeapBenchmarks()
17 | _addCFBitVectorBenchmarks()
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitArray/BitArray+Testing.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension BitArray {
17 | @_spi(Testing)
18 | public var _capacity: Int {
19 | _storage.capacity * _Word.capacity
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Sources/DequeModule/Deque+CustomReflectable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !$Embedded
13 | extension Deque: CustomReflectable {
14 | /// The custom mirror for this instance.
15 | public var customMirror: Mirror {
16 | Mirror(self, unlabeledChildren: self, displayStyle: .collection)
17 | }
18 | }
19 | #endif
20 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitArray/BitArray+ExpressibleByArrayLiteral.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension BitArray: ExpressibleByArrayLiteral {
13 | /// Creates an instance initialized with the given elements.
14 | @inlinable
15 | public init(arrayLiteral elements: Bool...) {
16 | self.init(elements)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitSet/BitSet+CustomReflectable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !$Embedded
13 | extension BitSet: CustomReflectable {
14 | /// The custom mirror for this instance.
15 | public var customMirror: Mirror {
16 | Mirror(self, unlabeledChildren: self, displayStyle: .set)
17 | }
18 | }
19 | #endif
20 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitSet/BitSet+CustomDebugStringConvertible.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !$Embedded
13 | extension BitSet: CustomDebugStringConvertible {
14 | /// A textual representation of this instance, suitable for debugging.
15 | public var debugDescription: String {
16 | description
17 | }
18 | }
19 | #endif
20 |
--------------------------------------------------------------------------------
/Sources/Collections/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #[[
2 | This source file is part of the Swift Collections Open Source Project
3 |
4 | Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
5 | Licensed under Apache License v2.0 with Runtime Library Exception
6 |
7 | See https://swift.org/LICENSE.txt for license information
8 | #]]
9 |
10 | add_library(Collections
11 | "Collections.swift")
12 | target_link_libraries(Collections PRIVATE
13 | BitCollections
14 | DequeModule
15 | HeapModule
16 | OrderedCollections
17 | HashTreeCollections
18 | )
19 | set_target_properties(Collections PROPERTIES
20 | INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
21 |
22 | _install_target(Collections)
23 | set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS Collections)
24 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeSet/TreeSet+CustomReflectable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !$Embedded
13 | extension TreeSet: CustomReflectable {
14 | /// The custom mirror for this instance.
15 | public var customMirror: Mirror {
16 | Mirror(self, unlabeledChildren: self, displayStyle: .set)
17 | }
18 | }
19 | #endif
20 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitArray/BitArray+CustomReflectable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !$Embedded
13 | extension BitArray: CustomReflectable {
14 | /// The custom mirror for this instance.
15 | public var customMirror: Mirror {
16 | Mirror(self, unlabeledChildren: self, displayStyle: .collection)
17 | }
18 | }
19 | #endif
20 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedSet/OrderedSet+CustomReflectable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !$Embedded
13 | extension OrderedSet: CustomReflectable {
14 | /// The custom mirror for this instance.
15 | public var customMirror: Mirror {
16 | Mirror(self, unlabeledChildren: _elements, displayStyle: .set)
17 | }
18 | }
19 | #endif
20 |
--------------------------------------------------------------------------------
/cmake/modules/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #[[
2 | This source file is part of the Swift Collections Open Source Project
3 |
4 | Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
5 | Licensed under Apache License v2.0 with Runtime Library Exception
6 |
7 | See https://swift.org/LICENSE.txt for license information
8 | #]]
9 |
10 | set(SWIFT_COLLECTIONS_EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/SwiftCollectionsExports.cmake)
11 |
12 | configure_file(SwiftCollectionsConfig.cmake.in
13 | ${CMAKE_CURRENT_BINARY_DIR}/SwiftCollectionsConfig.cmake)
14 |
15 | get_property(SWIFT_COLLECTIONS_EXPORTS GLOBAL PROPERTY SWIFT_COLLECTIONS_EXPORTS)
16 | export(TARGETS ${SWIFT_COLLECTIONS_EXPORTS}
17 | NAMESPACE SwiftCollections::
18 | FILE ${SWIFT_COLLECTIONS_EXPORTS_FILE}
19 | EXPORT_LINK_INTERFACE_LIBRARIES)
20 |
--------------------------------------------------------------------------------
/Utils/swift-collections.xcworkspace/xcshareddata/IDETemplateMacros.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | FILEHEADER
6 | ===----------------------------------------------------------------------===//
7 | //
8 | // This source file is part of the Swift Collections open source project
9 | //
10 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
11 | // Licensed under Apache License v2.0 with Runtime Library Exception
12 | //
13 | // See https://swift.org/LICENSE.txt for license information
14 | //
15 | //===----------------------------------------------------------------------===//
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Basics/BigString+Debugging.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | @available(SwiftStdlib 6.2, *)
15 | extension BigString {
16 | public func _dump(heightLimit: Int = .max) {
17 | _rope._dump(heightLimit: heightLimit)
18 | }
19 | }
20 |
21 | #endif // compiler(>=6.2) && !$Embedded
22 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+CustomReflectable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !$Embedded
13 | extension TreeDictionary: CustomReflectable {
14 | /// The custom mirror for this instance.
15 | public var customMirror: Mirror {
16 | Mirror(self, unlabeledChildren: self, displayStyle: .dictionary)
17 | }
18 | }
19 | #endif
20 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Conformances/BigString+CustomStringConvertible.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | @available(SwiftStdlib 6.2, *)
15 | extension BigString: CustomStringConvertible {
16 | public var description: String {
17 | String(self)
18 | }
19 | }
20 |
21 | #endif // compiler(>=6.2) && !$Embedded
22 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Operations/Range+BigString.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | @available(SwiftStdlib 6.2, *)
15 | extension Range {
16 | internal var _isEmptyUTF8: Bool {
17 | lowerBound.utf8Offset == upperBound.utf8Offset
18 | }
19 | }
20 |
21 | #endif // compiler(>=6.2) && !$Embedded
22 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Conformances/BigString+LosslessStringConvertible.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | @available(SwiftStdlib 6.2, *)
15 | extension BigString: LosslessStringConvertible {
16 | // init?(_: String) is implemented by RangeReplaceableCollection.init(_:)
17 | }
18 |
19 | #endif // compiler(>=6.2) && !$Embedded
20 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+CustomReflectable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !$Embedded
13 | extension OrderedDictionary: CustomReflectable {
14 | /// The custom mirror for this instance.
15 | public var customMirror: Mirror {
16 | Mirror(self, unlabeledChildren: self.elements, displayStyle: .dictionary)
17 | }
18 | }
19 | #endif
20 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Conformances/BigString+ExpressibleByStringLiteral.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | @available(SwiftStdlib 6.2, *)
15 | extension BigString: ExpressibleByStringLiteral {
16 | public init(stringLiteral value: String) {
17 | self.init(value)
18 | }
19 | }
20 |
21 | #endif // compiler(>=6.2) && !$Embedded
22 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/BTree/_Node+CustomDebugString.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | extension _Node: CustomDebugStringConvertible {
15 | /// A textual representation of this instance, suitable for debugging.
16 | public var debugDescription: String {
17 | self.read { $0.debugDescription }
18 | }
19 | }
20 |
21 | #endif
22 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Conformances/BigString+CustomDebugStringConvertible.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | @available(SwiftStdlib 6.2, *)
15 | extension BigString: CustomDebugStringConvertible {
16 | public var debugDescription: String {
17 | description.debugDescription
18 | }
19 | }
20 |
21 | #endif // compiler(>=6.2) && !$Embedded
22 |
--------------------------------------------------------------------------------
/Tests/_CollectionsTestSupport/Utilities/AllOnesRandomNumberGenerator.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | /// A terrible random number generator that always returns values with all
13 | /// bits set to true.
14 | public struct AllOnesRandomNumberGenerator: RandomNumberGenerator {
15 |
16 | public init() {}
17 |
18 | public mutating func next() -> UInt64 {
19 | UInt64.max
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Documentation/Announcement-benchmarks/generate-results.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | #===----------------------------------------------------------------------===//
3 | #
4 | # This source file is part of the Swift Collections open source project
5 | #
6 | # Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
7 | # Licensed under Apache License v2.0 with Runtime Library Exception
8 | #
9 | # See https://swift.org/LICENSE.txt for license information
10 | #
11 | #===----------------------------------------------------------------------===//
12 |
13 | set -eux
14 |
15 | ../../Utils/run-benchmarks.sh library run results.json --library Library.json --max-size 16M --cycles 20 --mode replace-all
16 | ../../Utils/run-benchmarks.sh library render results.json --library Library.json --max-time 10us --min-time 1ns --theme-file Theme.json --percentile 90 --output .
17 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitSet/BitSet+CustomStringConvertible.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | #if !$Embedded
17 | extension BitSet: CustomStringConvertible {
18 | // A textual representation of this instance.
19 | public var description: String {
20 | _arrayDescription(for: self)
21 | }
22 | }
23 | #endif
24 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedSet/SortedSet+CustomReflectable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | #if !$Embedded
15 | extension SortedSet: CustomReflectable {
16 | /// The custom mirror for this instance.
17 | public var customMirror: Mirror {
18 | Mirror(self, unlabeledChildren: self, displayStyle: .set)
19 | }
20 | }
21 | #endif
22 |
23 | #endif
24 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.Elements.md:
--------------------------------------------------------------------------------
1 | # ``OrderedCollections/OrderedDictionary/Elements-swift.struct``
2 |
3 | ## Topics
4 |
5 | ### Inspecting an Elements View
6 |
7 | - ``isEmpty``
8 | - ``count``
9 |
10 | ### Accessing Elements
11 |
12 | - ``subscript(_:)-4xwc2``
13 | - ``keys``
14 | - ``values``
15 | - ``index(forKey:)``
16 |
17 | ### Removing Elements
18 |
19 | - ``remove(at:)``
20 | - ``removeSubrange(_:)-5x7oo``
21 | - ``removeSubrange(_:)-7wdak``
22 | - ``removeAll(keepingCapacity:)``
23 | - ``removeAll(where:)``
24 | - ``removeFirst()``
25 | - ``removeFirst(_:)``
26 | - ``removeLast()``
27 | - ``removeLast(_:)``
28 |
29 | ### Reordering Elements
30 |
31 | - ``swapAt(_:_:)``
32 | - ``reverse()``
33 | - ``sort()``
34 | - ``sort(by:)``
35 | - ``partition(by:)``
36 | - ``shuffle()``
37 | - ``shuffle(using:)``
38 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/BTree/_BTree+CustomReflectable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | #if !$Embedded
15 | extension _BTree: CustomReflectable {
16 | /// The custom mirror for this instance.
17 | @inlinable
18 | internal var customMirror: Mirror {
19 | Mirror(self, unlabeledChildren: self, displayStyle: .dictionary)
20 | }
21 | }
22 | #endif
23 |
24 | #endif
25 |
--------------------------------------------------------------------------------
/Sources/Collections/Collections.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | @_exported import BitCollections
14 | @_exported import DequeModule
15 | @_exported import HashTreeCollections
16 | @_exported import HeapModule
17 | @_exported import OrderedCollections
18 | // Note: _RopeModule is very intentionally not reexported, as its contents
19 | // aren't part of this package's stable API surface (yet).
20 | #endif
21 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomReflectable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | #if !$Embedded
15 | extension SortedDictionary: CustomReflectable {
16 | /// The custom mirror for this instance.
17 | public var customMirror: Mirror {
18 | Mirror(self, unlabeledChildren: self, displayStyle: .dictionary)
19 | }
20 | }
21 | #endif
22 |
23 | #endif
24 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitArray/BitArray+ExpressibleByStringLiteral.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !$Embedded
13 | extension BitArray: ExpressibleByStringLiteral {
14 | /// Creates an instance initialized with the given elements.
15 | @inlinable
16 | public init(stringLiteral value: String) {
17 | guard let bits = Self(value) else {
18 | fatalError("Invalid bit array literal")
19 | }
20 | self = bits
21 | }
22 | }
23 | #endif
24 |
--------------------------------------------------------------------------------
/Sources/InternalCollectionsUtilities/UnsafeRawBufferPointer+Extras.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension UnsafeRawBufferPointer {
13 | /// Returns a Boolean value indicating whether two `UnsafeRawBufferPointer`
14 | /// instances refer to the same region in memory.
15 | @inlinable @inline(__always)
16 | package func _isIdentical(to other: Self) -> Bool {
17 | (self.baseAddress == other.baseAddress) && (self.count == other.count)
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Tests/ContainersTests/RefTests.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_CONTAINERS_PREVIEW
13 | import XCTest
14 | import ContainersPreview
15 | import Synchronization
16 |
17 | final class RefTests: XCTestCase {
18 | @available(SwiftStdlib 5.0, *)
19 | func test_basic() {
20 | let x: Atomic? = Atomic(0)
21 |
22 | if let y = x.borrow() {
23 | XCTAssertEqual(y[].load(ordering: .relaxed), 0)
24 | }
25 | }
26 | }
27 | #endif
28 |
--------------------------------------------------------------------------------
/Sources/Collections/Collections.docc/Extensions/OrderedDictionary.Elements.md:
--------------------------------------------------------------------------------
1 | # ``Collections/OrderedDictionary/Elements-swift.struct``
2 |
3 |
4 |
5 |
6 | ## Topics
7 |
8 | ### Inspecting an Elements View
9 |
10 | - ``isEmpty``
11 | - ``count``
12 |
13 | ### Accessing Elements
14 |
15 | - ``subscript(_:)-4xwc2``
16 | - ``keys``
17 | - ``values``
18 | - ``index(forKey:)``
19 |
20 | ### Removing Elements
21 |
22 | - ``remove(at:)``
23 | - ``removeSubrange(_:)-5x7oo``
24 | - ``removeSubrange(_:)-7wdak``
25 | - ``removeAll(keepingCapacity:)``
26 | - ``removeAll(where:)``
27 | - ``removeFirst()``
28 | - ``removeFirst(_:)``
29 | - ``removeLast()``
30 | - ``removeLast(_:)``
31 |
32 | ### Reordering Elements
33 |
34 | - ``swapAt(_:_:)``
35 | - ``reverse()``
36 | - ``sort()``
37 | - ``sort(by:)``
38 | - ``partition(by:)``
39 | - ``shuffle()``
40 | - ``shuffle(using:)``
41 |
--------------------------------------------------------------------------------
/Sources/DequeModule/Deque+Hashable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension Deque: Hashable where Element: Hashable {
13 | /// Hashes the essential components of this value by feeding them into the
14 | /// given hasher.
15 | ///
16 | /// Complexity: O(`count`)
17 | @inlinable
18 | public func hash(into hasher: inout Hasher) {
19 | hasher.combine(count) // discriminator
20 | for element in self {
21 | hasher.combine(element)
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedSet/OrderedSet+Hashable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension OrderedSet: Hashable {
13 | /// Hashes the essential components of this value by feeding them into the
14 | /// given hasher.
15 | ///
16 | /// Complexity: O(`count`)
17 | @inlinable
18 | public func hash(into hasher: inout Hasher) {
19 | hasher.combine(count) // Discriminator
20 | for item in _elements {
21 | hasher.combine(item)
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Basics/BigString.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | /// The core of a B-tree based String implementation.
15 | @available(SwiftStdlib 6.2, *)
16 | public struct BigString: Sendable {
17 | typealias _Rope = Rope<_Chunk>
18 |
19 | nonisolated(unsafe)
20 | var _rope: _Rope
21 |
22 | internal init(_rope: _Rope) {
23 | self._rope = _rope
24 | }
25 | }
26 |
27 | #endif // compiler(>=6.2) && !$Embedded
28 |
--------------------------------------------------------------------------------
/Sources/InternalCollectionsUtilities/UnsafeMutableRawBufferPointer+Extras.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension UnsafeMutableRawBufferPointer {
13 | /// Returns a Boolean value indicating whether two
14 | /// `UnsafeMutableRawBufferPointer` instances refer to the same region in
15 | /// memory.
16 | @inlinable @inline(__always)
17 | package func _isIdentical(to other: Self) -> Bool {
18 | (self.baseAddress == other.baseAddress) && (self.count == other.count)
19 | }
20 | }
21 |
22 |
--------------------------------------------------------------------------------
/Sources/InternalCollectionsUtilities/IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension FixedWidthInteger {
13 | /// Round up `self` to the nearest power of two, assuming it's representable.
14 | /// Returns 0 if `self` isn't positive.
15 | @inlinable
16 | package func _roundUpToPowerOfTwo() -> Self {
17 | guard self > 0 else { return 0 }
18 | let l = Self.bitWidth - (self &- 1).leadingZeroBitCount
19 | return 1 << l
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Sources/TrailingElementsModule/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #[[
2 | This source file is part of the Swift Collections Open Source Project
3 |
4 | Copyright (c) 2025 Apple Inc. and the Swift project authors
5 | Licensed under Apache License v2.0 with Runtime Library Exception
6 |
7 | See https://swift.org/LICENSE.txt for license information
8 | #]]
9 |
10 | if(COLLECTIONS_SINGLE_MODULE)
11 | set(module_name ${COLLECTIONS_MODULE_NAME})
12 | else()
13 | set(module_name TrailingElementsModule)
14 | add_library(TrailingElementsModule)
15 | set_target_properties(TrailingElementsModule PROPERTIES
16 | INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
17 |
18 | _install_target(TrailingElementsModule)
19 | set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS TrailingElementsModule)
20 | endif()
21 |
22 | target_sources(${module_name} PRIVATE
23 | "TrailingArray.swift"
24 | "TrailingElements.swift"
25 | "TrailingPadding.swift")
26 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitSet/BitSet+Hashable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension BitSet: Hashable {
17 | /// Hashes the essential components of this value by feeding them into the
18 | /// given hasher.
19 | ///
20 | /// Complexity: O(*max*) where *max* is the largest value stored in this set.
21 | public func hash(into hasher: inout Hasher) {
22 | hasher.combine(_storage)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/CppBenchmarks/src/Utils.cpp:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #include "Utils.h"
13 |
14 | void
15 | black_hole(intptr_t value)
16 | {
17 | // Do nothing.
18 | }
19 |
20 | void
21 | black_hole(void *value)
22 | {
23 | // Do nothing.
24 | }
25 |
26 | intptr_t
27 | identity(intptr_t value)
28 | {
29 | return value;
30 | }
31 |
32 | void *
33 | _identity(void *value)
34 | {
35 | return value;
36 | }
37 |
38 | const void *
39 | _identity(const void *value)
40 | {
41 | return value;
42 | }
43 |
--------------------------------------------------------------------------------
/Tests/_CollectionsTestSupport/Utilities/Integer Square Root.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension FixedWidthInteger {
13 | internal func _squareRoot() -> Self {
14 | // Newton's method
15 | precondition(self >= 0)
16 | guard self != 0 else { return 0 }
17 | var x: Self = 1 &<< ((self.bitWidth + 1) / 2)
18 | var y: Self = 0
19 | while true {
20 | y = (self / x + x) &>> 1
21 | if x == y || x == y - 1 { break }
22 | x = y
23 | }
24 | return x
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/CppBenchmarks/src/CustomHash.h:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #ifndef CUSTOMHASH_H
13 | #define CUSTOMHASH_H
14 |
15 | #include
16 | #include
17 |
18 | #include "Hashing.h"
19 |
20 | extern cpp_hash_fn custom_hash_fn;
21 |
22 | struct custom_intptr_hash: public std::function
23 | {
24 | std::size_t
25 | operator()(intptr_t value) const
26 | {
27 | return static_cast(custom_hash_fn(value));
28 | }
29 | };
30 |
31 | #endif /* CUSTOMHASH_H */
32 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Chunk/BigString+Chunk+UTF8.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | @available(SwiftStdlib 6.2, *)
15 | extension BigString._Chunk {
16 | func utf8Distance(from i: Index, to j: Index) -> Int {
17 | j.utf8Offset - i.utf8Offset
18 | }
19 |
20 | subscript(utf8 i: Index) -> UInt8 {
21 | precondition((startIndex ..< endIndex).contains(i), "Index out of bounds")
22 | return span[i.utf8Offset]
23 | }
24 | }
25 |
26 | #endif // compiler(>=6.2) && !$Embedded
27 |
--------------------------------------------------------------------------------
/Tests/_CollectionsTestSupport/Utilities/HashableBox.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift.org open source project
4 | //
5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10 | //
11 | //===----------------------------------------------------------------------===//
12 |
13 | public final class HashableBox: Hashable {
14 | public init(_ value: T) { self.value = value }
15 | public var value: T
16 |
17 | public static func ==(left: HashableBox, right: HashableBox) -> Bool {
18 | left.value == right.value
19 | }
20 |
21 | public func hash(into hasher: inout Hasher) {
22 | hasher.combine(value)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Utils/README.md:
--------------------------------------------------------------------------------
1 | # Maintenance Scripts
2 |
3 | This directory contains scripts that are used to maintain this package.
4 |
5 | Beware! The contents of this directory are not source stable. They are provided as is, with no compatibility promises across package releases. Future versions of this package can arbitrarily change these files or remove them, without any advance notice. (This can include patch releases.)
6 |
7 | - `generate-docs.sh`: A shell scripts that automates the generation of API documentation.
8 |
9 | - `run-full-tests.sh`: A shell script that exercises many common configurations of this package in a semi-automated way. This is used before tagging a release to avoid accidentally shipping a package version that breaks some setups.
10 |
11 | - `shuffle-sources.sh`: A legacy utility that randomly reorders Swift source files in a given directory. This is used to avoid reoccurrances of issue #7. (This is hopefully only relevant with compilers that the package no longer supports.)
12 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Hashable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension OrderedDictionary: Hashable where Value: Hashable {
13 | /// Hashes the essential components of this value by feeding them into the
14 | /// given hasher.
15 | ///
16 | /// Complexity: O(`count`)
17 | @inlinable
18 | public func hash(into hasher: inout Hasher) {
19 | hasher.combine(count) // Discriminator
20 | for (key, value) in self {
21 | hasher.combine(key)
22 | hasher.combine(value)
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeSet/TreeSet+Hashable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension TreeSet: Hashable {
13 | /// Hashes the essential components of this value by feeding them into the
14 | /// given hasher.
15 | ///
16 | /// Complexity: O(`count`)
17 | @inlinable
18 | public func hash(into hasher: inout Hasher) {
19 | let copy = hasher
20 | let seed = copy.finalize()
21 |
22 | var hash = 0
23 | for member in self {
24 | hash ^= member._rawHashValue(seed: seed)
25 | }
26 | hasher.combine(hash)
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Sources/TrailingElementsModule/TrailingElements.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | /// Describes a type that has some number of elements following it directly
13 | /// in memory. Such types are generally used with the `TrailingArray`
14 | /// type, which manages storage for the header and its trailing elements.
15 | public protocol TrailingElements: ~Copyable {
16 | /// The element type of the data that follows the header in memory.
17 | associatedtype Element
18 |
19 | /// The number of elements following the header.
20 | var trailingCount: Int { get }
21 | }
22 |
--------------------------------------------------------------------------------
/Sources/InternalCollectionsUtilities/IntegerTricks/UInt+first and last set bit.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension UInt {
13 | @inlinable @inline(__always)
14 | package var _firstSetBit: UInt? {
15 | guard self != 0 else { return nil }
16 | let v = UInt.bitWidth &- 1 &- self.leadingZeroBitCount
17 | return UInt(truncatingIfNeeded: v)
18 | }
19 |
20 | @inlinable @inline(__always)
21 | package var _lastSetBit: UInt? {
22 | guard self != 0 else { return nil }
23 | return UInt(truncatingIfNeeded: self.trailingZeroBitCount)
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Sources/InternalCollectionsUtilities/IntegerTricks/UInt+reversed.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension UInt {
13 | @inlinable
14 | package var _reversed: UInt {
15 | // https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
16 | var shift: UInt = UInt(UInt.bitWidth)
17 | var mask: UInt = ~0;
18 | var result = self
19 | while true {
20 | shift &>>= 1
21 | guard shift > 0 else { break }
22 | mask ^= mask &<< shift
23 | result = ((result &>> shift) & mask) | ((result &<< shift) & ~mask)
24 | }
25 | return result
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Tests/ContainersTests/MutTests.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | import XCTest
13 | #if COLLECTIONS_SINGLE_MODULE
14 | import Collections
15 | #else
16 | import _CollectionsTestSupport
17 | import ContainersPreview
18 | #endif
19 |
20 | #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
21 | final class MutTests: XCTestCase {
22 | func test_basic() {
23 | var x = 0
24 | var y = Mut(&x)
25 |
26 | var v = y[]
27 | XCTAssertEqual(v, 0)
28 |
29 | y[] += 10
30 |
31 | v = y[]
32 | XCTAssertEqual(v, 10)
33 | XCTAssertEqual(x, 10)
34 | }
35 | }
36 | #endif
37 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/CppBenchmarks/include/Hashing.h:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #ifndef CPPBENCHMARKS_HASHING_H
13 | #define CPPBENCHMARKS_HASHING_H
14 |
15 | #include
16 | #include
17 |
18 | #ifdef __cplusplus
19 | extern "C" {
20 | #endif
21 |
22 | typedef size_t (*cpp_hash_fn)(intptr_t);
23 | extern void cpp_set_hash_fn(cpp_hash_fn fn);
24 |
25 | // Benchmarks
26 | void cpp_hash(const intptr_t *start, size_t count);
27 | void cpp_custom_hash(const intptr_t *start, size_t count);
28 |
29 | #ifdef __cplusplus
30 | }
31 | #endif
32 |
33 | #endif /* CPPBENCHMARKS_HASHING_H */
34 |
--------------------------------------------------------------------------------
/Sources/DequeModule/Deque+Descriptions.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | #if !$Embedded
17 | extension Deque: CustomStringConvertible {
18 | /// A textual representation of this instance.
19 | public var description: String {
20 | _arrayDescription(for: self)
21 | }
22 | }
23 |
24 | extension Deque: CustomDebugStringConvertible {
25 | /// A textual representation of this instance, suitable for debugging.
26 | public var debugDescription: String {
27 | description
28 | }
29 | }
30 | #endif
31 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitArray/BitArray+Hashable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension BitArray: Hashable {
17 | /// Hashes the essential components of this value by feeding them into the
18 | /// given hasher.
19 | ///
20 | /// - Parameter hasher: The hasher to use when combining the components
21 | /// of this instance.
22 | public func hash(into hasher: inout Hasher) {
23 | hasher.combine(_count)
24 | for word in _storage {
25 | hasher.combine(word)
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Sources/InternalCollectionsUtilities/RandomAccessCollection+Offsets.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension RandomAccessCollection {
13 | @_alwaysEmitIntoClient @inline(__always)
14 | package func _index(at offset: Int) -> Index {
15 | index(startIndex, offsetBy: offset)
16 | }
17 |
18 | @_alwaysEmitIntoClient @inline(__always)
19 | package func _offset(of index: Index) -> Int {
20 | distance(from: startIndex, to: index)
21 | }
22 |
23 | @_alwaysEmitIntoClient @inline(__always)
24 | package subscript(_offset offset: Int) -> Element {
25 | self[_index(at: offset)]
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Equatable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension OrderedDictionary: Equatable where Value: Equatable {
13 | /// Returns a Boolean value indicating whether two values are equal.
14 | ///
15 | /// Two ordered dictionaries are considered equal if they contain the same
16 | /// key-value pairs, in the same order.
17 | ///
18 | /// - Complexity: O(`min(left.count, right.count)`)
19 | @inlinable
20 | public static func ==(left: Self, right: Self) -> Bool {
21 | left._keys == right._keys && left._values == right._values
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Sources/InternalCollectionsUtilities/Debugging.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | /// True if consistency checking is enabled in the implementation of the
13 | /// Swift Collections package, false otherwise.
14 | ///
15 | /// Documented performance promises are null and void when this property
16 | /// returns true -- for example, operations that are documented to take
17 | /// O(1) time might take O(*n*) time, or worse.
18 | @inlinable @inline(__always)
19 | package var _isCollectionsInternalCheckingEnabled: Bool {
20 | #if COLLECTIONS_INTERNAL_CHECKS
21 | return true
22 | #else
23 | return false
24 | #endif
25 | }
26 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeSet/TreeSet+Descriptions.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | #if !$Embedded
17 | extension TreeSet: CustomStringConvertible {
18 | /// A textual representation of this instance.
19 | public var description: String {
20 | _arrayDescription(for: self)
21 | }
22 | }
23 |
24 | extension TreeSet: CustomDebugStringConvertible {
25 | /// A textual representation of this instance, suitable for debugging.
26 | public var debugDescription: String {
27 | description
28 | }
29 | }
30 | #endif
31 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Equatable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2019 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension TreeDictionary: Equatable where Value: Equatable {
13 | /// Returns a Boolean value indicating whether two values are equal.
14 | ///
15 | /// Two persistent dictionaries are considered equal if they contain the same
16 | /// key-value pairs, but not necessarily in the same order.
17 | ///
18 | /// - Complexity: O(`min(left.count, right.count)`)
19 | @inlinable
20 | public static func == (left: Self, right: Self) -> Bool {
21 | left._root.isEqualSet(to: right._root, by: { $0 == $1 })
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedSet/OrderedSet+Descriptions.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | #if !$Embedded
17 | extension OrderedSet: CustomStringConvertible {
18 | /// A textual representation of this instance.
19 | public var description: String {
20 | _arrayDescription(for: self)
21 | }
22 | }
23 |
24 | extension OrderedSet: CustomDebugStringConvertible {
25 | /// A textual representation of this instance, suitable for debugging.
26 | public var debugDescription: String {
27 | description
28 | }
29 | }
30 | #endif
31 |
--------------------------------------------------------------------------------
/Sources/HeapModule/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #[[
2 | This source file is part of the Swift Collections Open Source Project
3 |
4 | Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
5 | Licensed under Apache License v2.0 with Runtime Library Exception
6 |
7 | See https://swift.org/LICENSE.txt for license information
8 | #]]
9 |
10 | if(COLLECTIONS_SINGLE_MODULE)
11 | set(module_name ${COLLECTIONS_MODULE_NAME})
12 | else()
13 | set(module_name HeapModule)
14 | add_library(HeapModule
15 | ${COLLECTIONS_HEAP_SOURCES})
16 | target_link_libraries(HeapModule PRIVATE
17 | InternalCollectionsUtilities)
18 | set_target_properties(HeapModule PROPERTIES
19 | INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
20 |
21 | _install_target(HeapModule)
22 | set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS HeapModule)
23 | endif()
24 |
25 | target_sources(${module_name} PRIVATE
26 | "_HeapNode.swift"
27 | "Heap.swift"
28 | "Heap+Descriptions.swift"
29 | "Heap+ExpressibleByArrayLiteral.swift"
30 | "Heap+Invariants.swift"
31 | "Heap+UnsafeHandle.swift")
32 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Descriptions.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | #if !$Embedded
17 | extension TreeDictionary: CustomStringConvertible {
18 | // A textual representation of this instance.
19 | public var description: String {
20 | _dictionaryDescription(for: self)
21 | }
22 | }
23 |
24 | extension TreeDictionary: CustomDebugStringConvertible {
25 | /// A textual representation of this instance, suitable for debugging.
26 | public var debugDescription: String {
27 | description
28 | }
29 | }
30 | #endif
31 |
--------------------------------------------------------------------------------
/Utils/shuffle-sources.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | #
3 | # Randomly reorder Swift source files in the specified directory, then
4 | # try rebuilding the package, in a loop.
5 | #
6 | # This script is useful to help reproducing nondeterministic issues
7 | # with the Swift compiler's MergeModules phase, as in
8 | # https://github.com/apple/swift-collections/issues/7
9 | #
10 |
11 | set -eu
12 |
13 |
14 | function shuffle() {
15 | input="$1"
16 |
17 | tmp="$(dirname "$input")/tmp"
18 | mkdir "$tmp"
19 | local i=0
20 | ls "$input"/*.swift | sort -R | while read file; do
21 | mv "$file" "$tmp/$i.swift"
22 | i=$(($i + 1))
23 | done
24 |
25 | mv "$tmp"/*.swift "$input"
26 | rmdir "$tmp"
27 | }
28 |
29 | if [[ -z "${1+set}" || ! -d "$1" ]]; then
30 | echo "Usage: $0 ..." >&2
31 | exit 1
32 | fi
33 |
34 | dir="$1"
35 | shift
36 |
37 | cd "$(dirname "$0")/.."
38 |
39 | i=0
40 | while true; do
41 | echo
42 | echo "$i"
43 |
44 | rm -rf .build
45 | shuffle "$dir"
46 | xcrun swift build "$@"
47 | i="$(($i + 1))"
48 | done
49 |
--------------------------------------------------------------------------------
/Benchmarks/Package.resolved:
--------------------------------------------------------------------------------
1 | {
2 | "originHash" : "77540dbea8c5b0878a1a745326146f44af61e58620d5484d3d37c7454bf8b088",
3 | "pins" : [
4 | {
5 | "identity" : "swift-argument-parser",
6 | "kind" : "remoteSourceControl",
7 | "location" : "https://github.com/apple/swift-argument-parser",
8 | "state" : {
9 | "revision" : "41982a3656a71c768319979febd796c6fd111d5c",
10 | "version" : "1.5.0"
11 | }
12 | },
13 | {
14 | "identity" : "swift-collections-benchmark",
15 | "kind" : "remoteSourceControl",
16 | "location" : "https://github.com/apple/swift-collections-benchmark",
17 | "state" : {
18 | "revision" : "69cd5b456633671456884217688afe53f87efd13",
19 | "version" : "0.0.4"
20 | }
21 | },
22 | {
23 | "identity" : "swift-system",
24 | "kind" : "remoteSourceControl",
25 | "location" : "https://github.com/apple/swift-system",
26 | "state" : {
27 | "revision" : "a34201439c74b53f0fd71ef11741af7e7caf01e1",
28 | "version" : "1.4.2"
29 | }
30 | }
31 | ],
32 | "version" : 3
33 | }
34 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/CppBenchmarks/src/Hashing.cpp:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #import "Hashing.h"
13 | #import "CustomHash.h"
14 | #import "Utils.h"
15 |
16 | cpp_hash_fn custom_hash_fn;
17 |
18 | void
19 | cpp_set_hash_fn(cpp_hash_fn fn)
20 | {
21 | custom_hash_fn = fn;
22 | }
23 |
24 | void
25 | cpp_hash(const intptr_t *start, size_t count)
26 | {
27 | for (auto p = start; p < start + count; ++p) {
28 | black_hole(std::hash{}(*p));
29 | }
30 | }
31 |
32 | void
33 | cpp_custom_hash(const intptr_t *start, size_t count)
34 | {
35 | for (auto p = start; p < start + count; ++p) {
36 | black_hole(custom_intptr_hash{}(*p));
37 | }
38 | }
39 |
40 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedSet/SortedSet+Hashable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | extension SortedSet: Hashable where Element: Hashable {
15 | /// Hashes the essential components of this value by feeding them
16 | /// into the given hasher.
17 | /// - Parameter hasher: The hasher to use when combining
18 | /// the components of this instance.
19 | /// - Complexity: O(`self.count`)
20 | @inlinable
21 | public func hash(into hasher: inout Hasher) {
22 | hasher.combine(self.count)
23 | for element in self {
24 | hasher.combine(element)
25 | }
26 | }
27 | }
28 |
29 | #endif
30 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Descriptions.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | #if !$Embedded
17 | extension OrderedDictionary: CustomStringConvertible {
18 | /// A textual representation of this instance.
19 | public var description: String {
20 | _dictionaryDescription(for: self.elements)
21 | }
22 | }
23 |
24 | extension OrderedDictionary: CustomDebugStringConvertible {
25 | /// A textual representation of this instance, suitable for debugging.
26 | public var debugDescription: String {
27 | description
28 | }
29 | }
30 | #endif
31 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Hashable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2019 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension TreeDictionary: Hashable where Value: Hashable {
13 | /// Hashes the essential components of this value by feeding them into the
14 | /// given hasher.
15 | ///
16 | /// Complexity: O(`count`)
17 | @inlinable
18 | public func hash(into hasher: inout Hasher) {
19 | var commutativeHash = 0
20 | for (key, value) in self {
21 | var elementHasher = hasher
22 | elementHasher.combine(key)
23 | elementHasher.combine(value)
24 | commutativeHash ^= elementHasher.finalize()
25 | }
26 | hasher.combine(commutativeHash)
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Tests/CollectionsTestSupportTests/UtilitiesTests.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | import XCTest
13 |
14 | #if !COLLECTIONS_SINGLE_MODULE && DEBUG
15 | @testable import _CollectionsTestSupport
16 | #endif
17 |
18 | #if COLLECTIONS_SINGLE_MODULE || DEBUG
19 | final class UtilitiesTests: CollectionTestCase {
20 | func testIntegerSquareRoot() {
21 | withSome("i", in: 0 ..< Int.max, maxSamples: 100_000) { i in
22 | let s = i._squareRoot()
23 | expectLessThanOrEqual(s * s, i)
24 | let next = (s + 1).multipliedReportingOverflow(by: s + 1)
25 | if !next.overflow {
26 | expectGreaterThan(next.partialValue, i)
27 | }
28 | }
29 | }
30 | }
31 | #endif
32 |
--------------------------------------------------------------------------------
/Tests/CollectionsTestSupportTests/IndexRangeCollectionTests.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | import XCTest
13 | #if !COLLECTIONS_SINGLE_MODULE
14 | import _CollectionsTestSupport
15 | #endif
16 |
17 | final class IndexRangeCollectionTests: CollectionTestCase {
18 | func testCollection() {
19 | withEvery("b", in: [0, 1]) { b in
20 | withEvery("c", in: 0 ..< 3) { c in
21 | let expected = (b ... b + c).flatMap { end in
22 | (b ... end).lazy.map { start in start ..< end }
23 | }
24 | let actual = IndexRangeCollection(bounds: b ..< b + c)
25 | checkBidirectionalCollection(actual, expectedContents: expected)
26 | }
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitSet/BitSet+Equatable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension BitSet: Equatable {
13 | /// Returns a Boolean value indicating whether two values are equal. Two
14 | /// bit sets are considered equal if they contain the same elements.
15 | ///
16 | /// - Note: This simply forwards to the ``isEqualSet(to:)-4xfa9`` method.
17 | /// That method has additional overloads that can be used to compare
18 | /// bit sets with additional types.
19 | ///
20 | /// - Complexity: O(*max*), where *max* is value of the largest member of
21 | /// either set.
22 | public static func ==(left: Self, right: Self) -> Bool {
23 | left.isEqualSet(to: right)
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/BTree/_BTree+CustomDebugStringConvertible.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | extension _BTree: CustomDebugStringConvertible {
15 | #if DEBUG
16 | /// A textual representation of this instance, suitable for debugging.
17 | public var debugDescription: String {
18 | return "BTree<\(Key.self), \(Value.self)>\n" +
19 | self.root.read { String(reflecting: $0) }
20 | }
21 | #else
22 | /// A textual representation of this instance, suitable for debugging.
23 | public var debugDescription: String {
24 | return "BTree<\(Key.self), \(Value.self)>(\(self.root))"
25 | }
26 | #endif // DEBUG
27 | }
28 |
29 | #endif
30 |
--------------------------------------------------------------------------------
/Sources/ContainersPreview/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #[[
2 | This source file is part of the Swift Collections Open Source Project
3 |
4 | Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors
5 | Licensed under Apache License v2.0 with Runtime Library Exception
6 |
7 | See https://swift.org/LICENSE.txt for license information
8 | #]]
9 |
10 | if(COLLECTIONS_SINGLE_MODULE)
11 | set(module_name ${COLLECTIONS_MODULE_NAME})
12 | else()
13 | set(module_name ContainersPreview)
14 | add_library(ContainersPreview
15 | ${COLLECTIONS_CONTAINERS_SOURCES})
16 | target_link_libraries(ContainersPreview PRIVATE
17 | InternalCollectionsUtilities)
18 | set_target_properties(ContainersPreview PROPERTIES
19 | INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
20 |
21 | _install_target(ContainersPreview)
22 | set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS ContainersPreview)
23 | endif()
24 |
25 | target_sources(${module_name} PRIVATE
26 | "BorrowIteratorProtocol.swift"
27 | "Box.swift"
28 | "Container.swift"
29 | "Container+Utilities.swift"
30 | "InputSpan.swift"
31 | "Mut.swift"
32 | "Ref.swift"
33 | "Shared.swift"
34 | )
35 |
--------------------------------------------------------------------------------
/Documentation/Announcement-benchmarks/Results.md:
--------------------------------------------------------------------------------
1 | # Benchmark results
2 |
3 | Click to expand individual items below.
4 |
5 | All results
6 |
7 |
8 | 01: Deque - random access lookups
9 |
10 |
11 |
12 | 02: Deque - prepending individual integers
13 |
14 |
15 |
16 | 03: OrderedSet lookups
17 |
18 |
19 |
20 | 04: OrderedSet insertions
21 |
22 |
23 |
24 | 05: OrderedDictionary lookups
25 |
26 |
27 |
28 | 06: OrderedDictionary insertions
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedDictionary/SortedDictionary+Hashable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | extension SortedDictionary: Hashable where Key: Hashable, Value: Hashable {
15 | /// Hashes the essential components of this value by feeding them
16 | /// into the given hasher.
17 | /// - Parameter hasher: The hasher to use when combining
18 | /// the components of this instance.
19 | /// - Complexity: O(`self.count`)
20 | @inlinable
21 | public func hash(into hasher: inout Hasher) {
22 | hasher.combine(self.count)
23 | for (key, value) in self {
24 | hasher.combine(key)
25 | hasher.combine(value)
26 | }
27 | }
28 | }
29 |
30 | #endif
31 |
--------------------------------------------------------------------------------
/Xcode/CollectionsTests.xcconfig:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | PRODUCT_NAME = CollectionsTests
13 | PRODUCT_BUNDLE_IDENTIFIER = org.swift.CollectionsTests
14 |
15 | SUPPORTED_PLATFORMS = macosx iphoneos iphonesimulator watchos watchsimulator appletvos appletvsimulator
16 | ARCHS = $(ARCHS_STANDARD)
17 |
18 | MACOSX_DEPLOYMENT_TARGET = 12.0
19 | IPHONEOS_DEPLOYMENT_TARGET = 15.0
20 | WATCHOS_DEPLOYMENT_TARGET = 8.0
21 | TVOS_DEPLOYMENT_TARGET = 15.0
22 |
23 | CURRENT_PROJECT_VERSION = 1
24 | MARKETING_VERSION = 1.0
25 |
26 | GENERATE_INFOPLIST_FILE = YES
27 |
28 | CODE_SIGN_STYLE = Automatic
29 | CODE_SIGN_IDENTITY = -
30 |
31 | ENABLE_TESTABILITY = NO
32 |
33 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) COLLECTIONS_RANDOMIZED_TESTING
34 |
--------------------------------------------------------------------------------
/Sources/HeapModule/Heap+ExpressibleByArrayLiteral.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension Heap: ExpressibleByArrayLiteral {
13 | /// Creates a new heap from the contents of an array literal.
14 | ///
15 | /// **Do not call this initializer directly.** It is used by the compiler when
16 | /// you use an array literal. Instead, create a new heap using an array
17 | /// literal as its value by enclosing a comma-separated list of values in
18 | /// square brackets. You can use an array literal anywhere a heap is expected
19 | /// by the type context.
20 | ///
21 | /// - Parameter elements: A variadic list of elements of the new heap.
22 | public init(arrayLiteral elements: Element...) {
23 | self.init(elements)
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Tests/SortedCollectionsTests/BTree/BTree.Builder Tests.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | #if DEBUG
15 | import _CollectionsTestSupport
16 | @_spi(Testing) @testable import SortedCollections
17 |
18 | final class BTreeBuilderTests: CollectionTestCase {
19 | func test_append() {
20 | withEvery("size", in: 0..<1000) { size in
21 | var builder = _BTree.Builder(capacity: 4)
22 |
23 | for i in 0.. Bool {
26 | guard left._count == right._count else { return false }
27 | return left._storage == right._storage
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Conformances/BigString+TextOutputStream.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | @available(SwiftStdlib 6.2, *)
15 | extension BigString: TextOutputStream {
16 | public mutating func write(_ string: String) {
17 | append(contentsOf: string)
18 | }
19 | }
20 |
21 | @available(SwiftStdlib 6.2, *)
22 | extension BigString: TextOutputStreamable {
23 | public func write(to target: inout some TextOutputStream) {
24 | for chunk in _rope {
25 | let str = String(unsafeUninitializedCapacity: chunk.utf8Count) {
26 | $0.initialize(fromContentsOf: chunk._bytes)
27 | }
28 |
29 | str.write(to: &target)
30 | }
31 | }
32 | }
33 |
34 | #endif // compiler(>=6.2) && !$Embedded
35 |
--------------------------------------------------------------------------------
/Sources/DequeModule/Deque+Equatable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension Deque: Equatable where Element: Equatable {
13 | /// Returns a Boolean value indicating whether two values are equal. Two
14 | /// deques are considered equal if they contain the same elements in the same
15 | /// order.
16 | ///
17 | /// - Complexity: O(`min(left.count, right.count)`)
18 | @inlinable
19 | public static func ==(left: Self, right: Self) -> Bool {
20 | let lhsCount = left.count
21 | if lhsCount != right.count {
22 | return false
23 | }
24 |
25 | // Test referential equality.
26 | if lhsCount == 0 || left._storage.isIdentical(to: right._storage) {
27 | return true
28 | }
29 |
30 | return left.elementsEqual(right)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Utils/run-benchmarks.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | set -eu
4 |
5 | srcroot="$(dirname "$0")/../Benchmarks"
6 | results="batch.results"
7 |
8 | command="${1:-help}"
9 | shift || :
10 |
11 | if [ "$(uname)" = "Darwin" ]; then
12 | swift="xcrun swift"
13 | else
14 | swift="swift"
15 | fi
16 |
17 | run() {
18 | local flags
19 | flags="-c release"
20 | flags="$flags -Xswiftc -Xllvm -Xswiftc -align-module-to-page-size"
21 | $swift run --package-path "$srcroot" $flags benchmark "$@"
22 | }
23 |
24 | case "$command" in
25 | batch-run)
26 | revision="$(git rev-parse HEAD)"
27 | run library run "$results" \
28 | --source-url "https://github.com/apple/swift-collections/tree/$revision" \
29 | --mode replace-all \
30 | --max-size 4M --cycles 3 \
31 | --amortized-cutoff 10us \
32 | "$@"
33 | ;;
34 | batch-render)
35 | run library render "$results" \
36 | --min-time 100ps --max-time 10us \
37 | --min-size 1 --max-size 4M \
38 | "$@"
39 | ;;
40 | batch-clean)
41 | rm -rf "$out"/results
42 | ;;
43 | *)
44 | run "$command" "$@"
45 | ;;
46 | esac
47 |
--------------------------------------------------------------------------------
/Tests/HeapTests/HeapNodeTests.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if DEBUG // These unit tests need access to HeapModule internals
13 | import XCTest
14 | #if COLLECTIONS_SINGLE_MODULE
15 | @testable import Collections
16 | #else
17 | @testable import HeapModule
18 | #endif
19 |
20 | class HeapNodeTests: XCTestCase {
21 | func test_levelCalculation() {
22 | // Check alternating min and max levels in the heap
23 | var isMin = true
24 | for exp in 0...12 {
25 | // Check [2^exp, 2^(exp + 1))
26 | for offset in Int(pow(2, Double(exp)) - 1).."
17 | }
18 |
19 | internal var _idString: String {
20 | // "<32 items @0x2787abcf>"
21 | _storage.withUnsafeBytes {
22 | guard let p = $0.baseAddress else {
23 | return "nil"
24 | }
25 | return String(UInt(bitPattern: p), radix: 16)
26 | }
27 | }
28 | }
29 |
30 | extension Heap: CustomDebugStringConvertible {
31 | /// A textual representation of this instance, suitable for debugging.
32 | public var debugDescription: String {
33 | description
34 | }
35 | }
36 | #endif
37 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedSet/OrderedSet+Equatable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension OrderedSet: Equatable {
13 | /// Returns a Boolean value indicating whether two values are equal.
14 | ///
15 | /// Two ordered sets are considered equal if they contain the same
16 | /// elements in the same order.
17 | ///
18 | /// - Note: This operator implements different behavior than the
19 | /// `isEqualSet(to:)` method -- the latter implements an unordered
20 | /// comparison, to match the behavior of members like `isSubset(of:)`,
21 | /// `isStrictSuperset(of:)` etc.
22 | ///
23 | /// - Complexity: O(`min(left.count, right.count)`)
24 | @inlinable
25 | public static func ==(left: Self, right: Self) -> Bool {
26 | left._elements == right._elements
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Tests/ContainersTests/BoxTests.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | import XCTest
13 | #if COLLECTIONS_SINGLE_MODULE
14 | import Collections
15 | #else
16 | import _CollectionsTestSupport
17 | import ContainersPreview
18 | #endif
19 |
20 | #if compiler(>=6.2)
21 | final class BoxTests: XCTestCase {
22 | func test_basic() {
23 | var intOnHeap = Box(0)
24 |
25 | XCTAssertEqual(intOnHeap[], 0)
26 |
27 | intOnHeap[] = 123
28 |
29 | XCTAssertEqual(intOnHeap[], 123)
30 |
31 | XCTAssertEqual(intOnHeap.copy(), 123)
32 |
33 | #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
34 | var inoutToIntOnHeap = intOnHeap.leak()
35 |
36 | XCTAssertEqual(inoutToIntOnHeap[], 123)
37 |
38 | inoutToIntOnHeap[] = 321
39 |
40 | XCTAssertEqual(inoutToIntOnHeap[], 321)
41 | #endif
42 | }
43 | }
44 | #endif
45 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitSet/BitSet+ExpressibleByArrayLiteral.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension BitSet: ExpressibleByArrayLiteral {
13 | /// Creates a new bit set from the contents of an array literal.
14 | ///
15 | /// Do not call this initializer directly. It is used by the compiler when
16 | /// you use an array literal. Instead, create a new bit set using an array
17 | /// literal as its value by enclosing a comma-separated list of values in
18 | /// square brackets. You can use an array literal anywhere a bit set is
19 | /// expected by the type context.
20 | ///
21 | /// - Parameter elements: A variadic list of elements of the new set.
22 | /// - Complexity: O(`elements.count`)
23 | @inlinable
24 | public init(arrayLiteral elements: Int...) {
25 | self.init(elements)
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitSet/BitSet+Random.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension BitSet {
17 | public static func random(upTo limit: Int) -> BitSet {
18 | var rng = SystemRandomNumberGenerator()
19 | return random(upTo: limit, using: &rng)
20 | }
21 |
22 | public static func random(
23 | upTo limit: Int,
24 | using rng: inout some RandomNumberGenerator
25 | ) -> BitSet {
26 | precondition(limit >= 0, "Invalid limit value")
27 | guard limit > 0 else { return BitSet() }
28 | let (w, b) = _UnsafeHandle.Index(limit).endSplit
29 | var words = (0 ... w).map { _ in _Word(rng.next() as UInt) }
30 | words[w].formIntersection(_Word(upTo: b))
31 | return BitSet(_words: words)
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionary Utils.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | import _CollectionsTestSupport
15 | import SortedCollections
16 |
17 | extension LifetimeTracker {
18 | func sortedDictionary(
19 | keys: Keys
20 | ) -> (
21 | dictionary: SortedDictionary, LifetimeTracked>,
22 | kvs: [(LifetimeTracked, LifetimeTracked)]
23 | )
24 | where Keys.Element == Int
25 | {
26 | let k = Array(keys)
27 | let keys = self.instances(for: k)
28 | let values = self.instances(for: k.map { -($0 + 1) })
29 |
30 | let kvs = Array(zip(keys, values))
31 |
32 | let dictionary = SortedDictionary(keysWithValues: kvs)
33 |
34 | return (dictionary, kvs)
35 | }
36 | }
37 |
38 | #endif
39 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeSet/TreeSet+Equatable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension TreeSet: Equatable {
17 | /// Returns a Boolean value indicating whether two values are equal.
18 | ///
19 | /// Two persistent sets are considered equal if they contain the same
20 | /// elements, but not necessarily in the same order.
21 | ///
22 | /// - Note: This simply forwards to the ``isEqualSet(to:)-4bc1i`` method.
23 | /// That method has additional overloads that can be used to compare
24 | /// persistent sets with additional types.
25 | ///
26 | /// - Complexity: O(`min(left.count, right.count)`)
27 | @inlinable @inline(__always)
28 | public static func == (left: Self, right: Self) -> Bool {
29 | left.isEqualSet(to: right)
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedSet/SortedSet.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | /// A collection which maintains unique members in ascending sorted order.
15 | public struct SortedSet {
16 | @usableFromInline
17 | internal typealias _Tree = _BTree
18 |
19 | @usableFromInline
20 | internal var _root: _Tree
21 |
22 | //// Creates an empty set.
23 | ///
24 | /// This initializer is equivalent to initializing with an empty array
25 | /// literal.
26 | ///
27 | /// - Complexity: O(1)
28 | @inlinable
29 | @inline(__always)
30 | public init() {
31 | self._root = _Tree()
32 | }
33 |
34 | /// Creates a set rooted at a given B-Tree.
35 | @inlinable
36 | internal init(_rootedAt tree: _Tree) {
37 | self._root = tree
38 | }
39 | }
40 |
41 | #endif
42 |
--------------------------------------------------------------------------------
/Tests/_CollectionsTestSupport/MinimalTypes/ResettableValue.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift.org open source project
4 | //
5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10 | //
11 | //===----------------------------------------------------------------------===//
12 |
13 | // Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibUnittest
14 |
15 | public class ResettableValue {
16 | public init(_ value: Value) {
17 | self.defaultValue = value
18 | self.value = value
19 | }
20 |
21 | public func reset() {
22 | value = defaultValue
23 | }
24 |
25 | public let defaultValue: Value
26 | public var value: Value
27 | }
28 |
29 | extension ResettableValue where Value: Strideable {
30 | public func increment(by delta: Value.Stride = 1) {
31 | value = value.advanced(by: delta)
32 | }
33 | }
34 |
35 | extension ResettableValue: CustomStringConvertible {
36 | public var description: String { "\(value)" }
37 | }
38 |
--------------------------------------------------------------------------------
/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Utils.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_SINGLE_MODULE
13 | import Collections
14 | #else
15 | import _CollectionsTestSupport
16 | import OrderedCollections
17 | #endif
18 |
19 | extension LifetimeTracker {
20 | func orderedDictionary(
21 | keys: Keys
22 | ) -> (
23 | dictionary: OrderedDictionary, LifetimeTracked>,
24 | expected: [(key: LifetimeTracked, value: LifetimeTracked)]
25 | )
26 | where Keys.Element == Int
27 | {
28 | let k = Array(keys)
29 | let keys = self.instances(for: k)
30 | let values = self.instances(for: k.map { $0 + 100 })
31 | let dictionary = OrderedDictionary(uniqueKeys: keys, values: values)
32 | return (dictionary, (0 ..< k.count).map { (key: keys[$0], value: values[$0]) })
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/CppBenchmarks/include/Utils.h:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #ifndef BLACK_HOLE_H
13 | #define BLACK_HOLE_H
14 |
15 | #include
16 |
17 | #ifdef __cplusplus
18 |
19 | // FIXME: Is putting this in a separate compilation unit enough to make
20 | // sure the function call is always emitted?
21 |
22 | extern void black_hole(intptr_t value);
23 | extern void black_hole(void *value);
24 |
25 | extern intptr_t identity(intptr_t value);
26 | extern void *_identity(void *value);
27 | extern const void *_identity(const void *value);
28 |
29 | template
30 | static inline T *identity(T *value)
31 | {
32 | return static_cast(_identity(value));
33 | }
34 |
35 | template
36 | static inline const T *identity(const T *value)
37 | {
38 | return static_cast(_identity(value));
39 | }
40 |
41 | #endif /* __cplusplus */
42 | #endif /* BLACK_HOLE_H */
43 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
14 |
15 | Replace this paragraph with a description of your changes and rationale. Provide links to an existing issue or external references/discussions, if appropriate.
16 |
17 | ### Checklist
18 | - [ ] I've read the [Contribution Guidelines](https://github.com/apple/swift-collections/blob/main/README.md#contributing-to-swift-collections)
19 | - [ ] My contributions are licensed under the [Swift license](https://swift.org/LICENSE.txt).
20 | - [ ] I've followed the coding style of the rest of the project.
21 | - [ ] I've added tests covering all new code paths my change adds to the project (if appropriate).
22 | - [ ] I've added benchmarks covering new functionality (if appropriate).
23 | - [ ] I've verified that my change does not break any existing tests or introduce unexplained benchmark regressions.
24 | - [ ] I've updated the documentation if necessary.
25 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/HashTable/_HashTable+Bucket.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension _HashTable {
13 | /// Identifies a particular bucket within a hash table by its offset.
14 | /// Having a dedicated wrapper type for this prevents passing a bucket number
15 | /// to a function that expects a word index, or vice versa.
16 | @usableFromInline
17 | @frozen
18 | internal struct Bucket {
19 | /// The distance of this bucket from the first bucket in the hash table.
20 | @usableFromInline
21 | internal var offset: Int
22 |
23 | @inlinable
24 | @inline(__always)
25 | internal init(offset: Int) {
26 | assert(offset >= 0)
27 | self.offset = offset
28 | }
29 | }
30 | }
31 |
32 | extension _HashTable.Bucket: Equatable {
33 | @_transparent
34 | public static func == (left: Self, right: Self) -> Bool {
35 | left.offset == right.offset
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedSet/SortedSet+Equatable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | extension SortedSet: Equatable {
15 | /// Returns a Boolean value indicating whether two values are equal.
16 | ///
17 | /// Equality is the inverse of inequality. For any values `a` and `b`,
18 | /// `a == b` implies that `a != b` is false.
19 | ///
20 | /// - Parameters:
21 | /// - lhs: A value to compare.
22 | /// - rhs: Another value to compare.
23 | /// - Complexity: O(`self.count`)
24 | @inlinable
25 | public static func ==(lhs: Self, rhs: Self) -> Bool {
26 | // TODO: optimize/benchmarking by comparing node identity.
27 | if lhs.count != rhs.count { return false }
28 | for (k1, k2) in zip(lhs, rhs) {
29 | if k1 != k2 {
30 | return false
31 | }
32 | }
33 | return true
34 | }
35 | }
36 |
37 | #endif
38 |
--------------------------------------------------------------------------------
/Sources/BitCollections/Shared/Range+Utilities.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension Range where Bound: FixedWidthInteger {
13 | @inlinable
14 | internal func _clampedToUInt() -> Range {
15 | if upperBound <= 0 {
16 | return Range(uncheckedBounds: (0, 0))
17 | }
18 | if lowerBound >= UInt.max {
19 | return Range(uncheckedBounds: (UInt.max, UInt.max))
20 | }
21 | let lower = lowerBound < 0 ? 0 : UInt(lowerBound)
22 | let upper = upperBound > UInt.max ? UInt.max : UInt(upperBound)
23 | return Range(uncheckedBounds: (lower, upper))
24 | }
25 |
26 | @inlinable
27 | internal func _toUInt() -> Range? {
28 | guard
29 | let lower = UInt(exactly: lowerBound),
30 | let upper = UInt(exactly: upperBound)
31 | else {
32 | return nil
33 | }
34 | return Range(uncheckedBounds: (lower: lower, upper: upper))
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Sources/InternalCollectionsUtilities/_SortedCollection.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | /// A Collection type that is guaranteed to contain elements in monotonically
13 | /// increasing order. (Duplicates are still allowed unless the collection
14 | /// also conforms to `_UniqueCollection`.)
15 | ///
16 | /// Types conforming to this protocol must also conform to `Collection`,
17 | /// with an `Element` type that conforms to `Comparable`.
18 | /// (However, this protocol does not specify these as explicit requirements,
19 | /// to allow simple conformance tests such as `someValue is _SortedCollection`
20 | /// to be possible.)
21 | ///
22 | /// For any two valid indices `i` and `j` for a conforming collection `c`
23 | /// (both below the end index), it must hold true that if `i < j`, then
24 | /// `c[i] <= c[j]`.
25 | public protocol _SortedCollection {}
26 |
27 | extension Slice: _SortedCollection where Base: _SortedCollection {}
28 |
--------------------------------------------------------------------------------
/Tests/_CollectionsTestSupport/Utilities/SortedCollectionAPIChecker.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_SINGLE_MODULE
13 | import Collections
14 | #else
15 | import InternalCollectionsUtilities
16 | #endif
17 |
18 | /// This protocol simply lists Collection/Sequence extensions that ought to be
19 | /// customized for sorted collections.
20 | ///
21 | /// Conforming to this protocol admittedly doesn't do much, as the default
22 | /// implementations already exist for most of these requirements
23 | /// (but they aren't doing the right thing).
24 | public protocol SortedCollectionAPIChecker: Collection, _SortedCollection
25 | where Element: Comparable {
26 | // This one actually does not come with a default implementation.
27 | func sorted() -> Self
28 |
29 | // These are also defined on `Sequence`, but the default implementation does
30 | // a linear search, which isn't what we want.
31 | func min() -> Element?
32 | func max() -> Element?
33 | }
34 |
--------------------------------------------------------------------------------
/Sources/DequeModule/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #[[
2 | This source file is part of the Swift Collections Open Source Project
3 |
4 | Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
5 | Licensed under Apache License v2.0 with Runtime Library Exception
6 |
7 | See https://swift.org/LICENSE.txt for license information
8 | #]]
9 |
10 | if(COLLECTIONS_SINGLE_MODULE)
11 | set(module_name ${COLLECTIONS_MODULE_NAME})
12 | else()
13 | set(module_name DequeModule)
14 | add_library(DequeModule
15 | ${COLLECTIONS_DEQUE_SOURCES})
16 | target_link_libraries(DequeModule PRIVATE
17 | InternalCollectionsUtilities)
18 | set_target_properties(DequeModule PROPERTIES
19 | INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
20 |
21 | _install_target(DequeModule)
22 | set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS DequeModule)
23 | endif()
24 |
25 | target_sources(${module_name} PRIVATE
26 | "Deque+Codable.swift"
27 | "Deque+Collection.swift"
28 | "Deque+CustomReflectable.swift"
29 | "Deque+Descriptions.swift"
30 | "Deque+Equatable.swift"
31 | "Deque+ExpressibleByArrayLiteral.swift"
32 | "Deque+Extras.swift"
33 | "Deque+Hashable.swift"
34 | "Deque+Testing.swift"
35 | "Deque._Storage.swift"
36 | "Deque._UnsafeHandle.swift"
37 | "Deque.swift"
38 | "_DequeBuffer.swift"
39 | "_DequeBufferHeader.swift"
40 | "_DequeSlot.swift"
41 | "_UnsafeWrappedBuffer.swift"
42 | )
43 |
--------------------------------------------------------------------------------
/Tests/_CollectionsTestSupport/AssertionContexts/CollectionTestCase.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift.org open source project
4 | //
5 | // Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10 | //
11 | //===----------------------------------------------------------------------===//
12 |
13 | import XCTest
14 |
15 | open class CollectionTestCase: XCTestCase {
16 | internal var _context: TestContext?
17 |
18 | public var context: TestContext { _context! }
19 |
20 | open var isAvailable: Bool { true }
21 |
22 | #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
23 | open override func invokeTest() {
24 | guard isAvailable else {
25 | print("\(Self.self) unavailable; skipping")
26 | return
27 | }
28 | return super.invokeTest()
29 | }
30 | #endif
31 |
32 | open override func setUp() {
33 | super.setUp()
34 | _context = TestContext.pushNew()
35 | }
36 |
37 | open override func tearDown() {
38 | if let context = _context {
39 | TestContext.pop(context)
40 | _context = nil
41 | }
42 | super.tearDown()
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/CppBenchmarks/include/MapBenchmarks.h:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #ifndef CPPBENCHMARKS_MAP_BENCHMARKS_H
13 | #define CPPBENCHMARKS_MAP_BENCHMARKS_H
14 |
15 | #include
16 | #include
17 | #include
18 |
19 | #ifdef __cplusplus
20 | extern "C" {
21 | #endif
22 |
23 | /// Create a std::map, populating it with data from the supplied buffer.
24 | /// Returns an opaque pointer to the created instance.
25 | extern void *cpp_map_create(const intptr_t *start, size_t count);
26 |
27 | /// Destroys an ordered map previously returned by `cpp_map_create`.
28 | extern void cpp_map_destroy(void *ptr);
29 |
30 | extern void cpp_map_insert_integers(const intptr_t *start, size_t count);
31 |
32 | extern void cpp_map_lookups(void *ptr, const intptr_t *start, size_t count);
33 | extern void cpp_map_subscript(void *ptr, const intptr_t *start, size_t count);
34 |
35 | #ifdef __cplusplus
36 | }
37 | #endif
38 |
39 |
40 | #endif /* CPPBENCHMARKS_MAP_BENCHMARKS_H */
41 |
--------------------------------------------------------------------------------
/Sources/BitCollections/Shared/UInt+Tricks.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension UInt {
17 | /// Returns the position of the `n`th set bit in `self`.
18 | ///
19 | /// - Parameter n: The to retrieve. This value is
20 | /// decremented by the number of items found in this `self` towards the
21 | /// value we're looking for. (If the function returns non-nil, then `n`
22 | /// is set to `0` on return.)
23 | /// - Returns: If this integer contains enough set bits to satisfy the
24 | /// request, then this function returns the position of the bit found.
25 | /// Otherwise it returns nil.
26 | internal func _rank(ofBit n: inout UInt) -> UInt? {
27 | let c = self.nonzeroBitCount
28 | guard n < c else {
29 | n &-= UInt(bitPattern: c)
30 | return nil
31 | }
32 | let m = Int(bitPattern: n)
33 | n = 0
34 | return _bit(ranked: m)!
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Sources/BasicContainers/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #[[
2 | This source file is part of the Swift Collections Open Source Project
3 |
4 | Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors
5 | Licensed under Apache License v2.0 with Runtime Library Exception
6 |
7 | See https://swift.org/LICENSE.txt for license information
8 | #]]
9 |
10 | if(COLLECTIONS_SINGLE_MODULE)
11 | set(module_name ${COLLECTIONS_MODULE_NAME})
12 | else()
13 | set(module_name BasicContainers)
14 | add_library(BasicContainers
15 | ${COLLECTIONS_ARRAY_SOURCES})
16 | target_link_libraries(BasicContainers PRIVATE
17 | InternalCollectionsUtilities ContainersPreview)
18 | set_target_properties(BasicContainers PROPERTIES
19 | INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
20 |
21 | _install_target(BasicContainers)
22 | set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS BasicContainers)
23 | endif()
24 |
25 | target_sources(${module_name} PRIVATE
26 | "RigidArray.swift"
27 | "RigidArray+Append.swift"
28 | "RigidArray+Experimental.swift"
29 | "RigidArray+Initializers.swift"
30 | "RigidArray+Insertions.swift"
31 | "RigidArray+Removals.swift"
32 | "RigidArray+Replacements.swift"
33 | "UniqueArray.swift"
34 | "UniqueArray+Append.swift"
35 | "UniqueArray+Experimental.swift"
36 | "UniqueArray+Initializers.swift"
37 | "UniqueArray+Insertions.swift"
38 | "UniqueArray+Removals.swift"
39 | "UniqueArray+Replacements.swift"
40 | )
41 |
--------------------------------------------------------------------------------
/Sources/RopeModule/Rope/Basics/_RopeVersion.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | @usableFromInline
13 | @frozen // Not really! This module isn't ABI stable.
14 | internal struct _RopeVersion {
15 | // FIXME: Replace this probabilistic mess with atomics when Swift gets its act together.
16 | @usableFromInline internal var _value: UInt
17 |
18 | @inlinable
19 | internal init() {
20 | var rng = SystemRandomNumberGenerator()
21 | _value = rng.next()
22 | }
23 |
24 | @inlinable
25 | internal init(_ value: UInt) {
26 | self._value = value
27 | }
28 | }
29 |
30 | extension _RopeVersion: Equatable {
31 | @inlinable
32 | internal static func ==(left: Self, right: Self) -> Bool {
33 | left._value == right._value
34 | }
35 | }
36 |
37 | extension _RopeVersion {
38 | @inlinable
39 | internal mutating func bump() {
40 | _value &+= 1
41 | }
42 |
43 | @inlinable
44 | internal mutating func reset() {
45 | var rng = SystemRandomNumberGenerator()
46 | _value = rng.next()
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Sources/RopeModule/Rope/Basics/RopeMetric.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | public protocol RopeMetric: Sendable {
13 | associatedtype Element: RopeElement
14 |
15 | /// Returns the size of a summarized rope element in this metric.
16 | func size(of summary: Element.Summary) -> Int
17 |
18 | /// Returns an index addressing the content at the given offset from
19 | /// the start of the specified rope element.
20 | ///
21 | /// - Parameter offset: An integer offset from the start of `element` in this
22 | /// metric, not exceeding `size(of: element.summary)`.
23 | /// - Parameter element: An arbitrary rope element.
24 | /// - Returns: The index addressing the desired position in the input element.
25 | func index(at offset: Int, in element: Element) -> Element.Index
26 | }
27 |
28 | extension RopeMetric {
29 | @inlinable @inline(__always)
30 | internal func _nonnegativeSize(of summary: Element.Summary) -> Int {
31 | let r = size(of: summary)
32 | assert(r >= 0)
33 | return r
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedDictionary/SortedDictionary+Equatable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | extension SortedDictionary: Equatable where Value: Equatable {
15 | /// Returns a Boolean value indicating whether two values are equal.
16 | ///
17 | /// Equality is the inverse of inequality. For any values `a` and `b`,
18 | /// `a == b` implies that `a != b` is false.
19 | ///
20 | /// - Parameters:
21 | /// - lhs: A value to compare.
22 | /// - rhs: Another value to compare.
23 | /// - Complexity: O(`self.count`)
24 | @inlinable
25 | public static func ==(lhs: SortedDictionary, rhs: SortedDictionary) -> Bool {
26 | // TODO: optimize/benchmarking by comparing node identity/shared subtrees.
27 | if lhs.count != rhs.count { return false }
28 | for ((k1, v1), (k2, v2)) in zip(lhs, rhs) {
29 | if k1 != k2 || v1 != v2 {
30 | return false
31 | }
32 | }
33 | return true
34 | }
35 | }
36 |
37 | #endif
38 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Invariants.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension OrderedDictionary {
17 | /// True if consistency checking is enabled in the implementation of this
18 | /// type, false otherwise.
19 | ///
20 | /// Documented performance promises are null and void when this property
21 | /// returns true -- for example, operations that are documented to take
22 | /// O(1) time might take O(*n*) time, or worse.
23 | public static var _isConsistencyCheckingEnabled: Bool {
24 | _isCollectionsInternalCheckingEnabled
25 | }
26 |
27 | #if COLLECTIONS_INTERNAL_CHECKS
28 | @inline(never) @_effects(releasenone)
29 | public func _checkInvariants() {
30 | precondition(_keys.count == _values.count)
31 | self._keys._checkInvariants()
32 | }
33 | #else
34 | @inline(__always) @inlinable
35 | public func _checkInvariants() {}
36 | #endif // COLLECTIONS_INTERNAL_CHECKS
37 | }
38 |
--------------------------------------------------------------------------------
/Documentation/Announcement-benchmarks/README.md:
--------------------------------------------------------------------------------
1 | # Benchmark data from the swift.org announcement
2 |
3 | This directory contains the benchmark configuration that we used to collect benchmarking data and render the charts in the [Swift Collections announcement on swift.org][announcement].
4 |
5 | * [`generate-results.sh`](./generate-results.sh): A script that you can use to run the benchmark on your own machine, and to reproduce the charts.
6 | * [`Library.json`](./Library.json): The benchmark library definition collecting the chart definitions used in the blog post.
7 | * [`Theme.json`](./Theme.json): The chart theme to set up colors, line widths, font sizes etc. (Slightly adapted.)
8 | * [`Results.md`](./Results.md): The generated results summary.
9 | * [`Results/`](./Results/): The generated subdirectory containing the PNG files for the charts.
10 | * [`results.json`](./results.json): The result data we collected.
11 |
12 | Note: If you'd like to try reproducing our results (it's easy!), note that the script is configured to collect 20 rounds of data on up to 16 million items, and this will likely take a very long time. Feel free to reduce the maximum size, or just plan to allow the measurement run overnight.
13 |
14 | For more information on how to use the Swift Collections benchmarking tool, please see [Swift Collections Benchmark][swift-collections-benchmark].
15 |
16 | [announcement]: https://swift.org/blog/swift-collections
17 | [swift-collections-benchmark]: https://github.com/apple/swift-collections-benchmark
18 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.UnorderedView.md:
--------------------------------------------------------------------------------
1 | # ``OrderedCollections/OrderedSet/UnorderedView``
2 |
3 |
4 |
5 |
6 |
7 | ## Topics
8 |
9 | ### Binary Set Operations
10 |
11 | - ``intersection(_:)-3q45l``
12 | - ``intersection(_:)-6ee3o``
13 |
14 | - ``union(_:)-79uk3``
15 | - ``union(_:)-23dm1``
16 |
17 | - ``subtracting(_:)-3ct1b``
18 | - ``subtracting(_:)-8e6mw``
19 |
20 | - ``symmetricDifference(_:)-6aed7``
21 | - ``symmetricDifference(_:)-7r79p``
22 |
23 | - ``formIntersection(_:)-4ow38``
24 | - ``formIntersection(_:)-80iht``
25 |
26 | - ``formUnion(_:)-6ijb``
27 | - ``formUnion(_:)-8tuol``
28 |
29 | - ``subtract(_:)-627eq``
30 | - ``subtract(_:)-4pjhu``
31 |
32 | - ``formSymmetricDifference(_:)-8pkt5``
33 | - ``formSymmetricDifference(_:)-75z52``
34 |
35 | ### Binary Set Predicates
36 |
37 | - ``==(_:_:)``
38 | - ``isEqualSet(to:)-1szq``
39 | - ``isEqualSet(to:)-9djqq``
40 |
41 | - ``isSubset(of:)-2dx31``
42 | - ``isSubset(of:)-801lo``
43 | - ``isSubset(of:)-952h5``
44 |
45 | - ``isSuperset(of:)-9t33p``
46 | - ``isSuperset(of:)-2vtig``
47 | - ``isSuperset(of:)-9krpz``
48 |
49 | - ``isStrictSubset(of:)-9o6mg``
50 | - ``isStrictSubset(of:)-91par``
51 | - ``isStrictSubset(of:)-7n66e``
52 |
53 | - ``isStrictSuperset(of:)-89ig3``
54 | - ``isStrictSuperset(of:)-1e0xt``
55 | - ``isStrictSuperset(of:)-5dsfd``
56 |
57 | - ``isDisjoint(with:)-3wuso``
58 | - ``isDisjoint(with:)-25vmx``
59 | - ``isDisjoint(with:)-8nfqs``
60 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Basics/BigString+Invariants.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | @available(SwiftStdlib 6.2, *)
15 | extension BigString {
16 | public func _invariantCheck() {
17 | #if COLLECTIONS_INTERNAL_CHECKS
18 | _rope._invariantCheck()
19 | let allowUndersize = _rope.isSingleton
20 |
21 | var state = _CharacterRecognizer()
22 | for chunk in _rope {
23 | precondition(allowUndersize || !chunk.isUndersized, "Undersized chunk")
24 | let (characters, prefix, suffix) = state.edgeCounts(consuming: chunk)
25 | precondition(
26 | chunk.prefixCount == prefix,
27 | "Inconsistent position of first grapheme break in chunk")
28 | precondition(
29 | chunk.suffixCount == suffix,
30 | "Inconsistent position of last grapheme break in chunk")
31 | precondition(
32 | chunk.characterCount == characters,
33 | "Inconsistent character count in chunk")
34 | }
35 | #endif
36 | }
37 | }
38 |
39 | #endif // compiler(>=6.2) && !$Embedded
40 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Operations/BigString+Split.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | @available(SwiftStdlib 6.2, *)
15 | extension BigString {
16 | mutating func split(
17 | at index: Index
18 | ) -> Builder {
19 | let b = _ropeBuilder(at: index)
20 | let state = b._breakState()
21 | let builder = Builder(base: b, prefixEndState: state, suffixStartState: state)
22 | return builder
23 | }
24 |
25 | mutating func split(
26 | at index: Index,
27 | state: _CharacterRecognizer
28 | ) -> Builder {
29 | let b = _ropeBuilder(at: index)
30 | let builder = Builder(base: b, prefixEndState: state, suffixStartState: state)
31 | return builder
32 | }
33 |
34 | mutating func _ropeBuilder(at index: Index) -> _Rope.Builder {
35 | if let ri = index._rope, _rope.isValid(ri) {
36 | return _rope.split(at: ri, index._chunkIndex)
37 | }
38 | return _rope.builder(splittingAt: index.utf8Offset, in: _UTF8Metric())
39 | }
40 | }
41 |
42 | #endif // compiler(>=6.2) && !$Embedded
43 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+ExpressibleByDictionaryLiteral.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension OrderedDictionary: ExpressibleByDictionaryLiteral {
13 | /// Creates a new ordered dictionary from the contents of a dictionary
14 | /// literal.
15 | ///
16 | /// Do not call this initializer directly. It is used by the compiler when you
17 | /// use a dictionary literal. Instead, create a new ordered dictionary using a
18 | /// dictionary literal as its value by enclosing a comma-separated list of
19 | /// key-value pairs in square brackets. You can use a dictionary literal
20 | /// anywhere an ordered dictionary is expected by the type context.
21 | ///
22 | /// - Parameter elements: A variadic list of key-value pairs for the new
23 | /// ordered dictionary.
24 | ///
25 | /// - Complexity: O(`elements.count`) if `Key` implements
26 | /// high-quality hashing.
27 | @inlinable
28 | public init(dictionaryLiteral elements: (Key, Value)...) {
29 | self.init(uniqueKeysWithValues: elements)
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedSet/SortedSet+CustomStringConvertible.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | #if !$Embedded
15 | extension SortedSet: CustomStringConvertible, CustomDebugStringConvertible {
16 | @inlinable
17 | public var description: String {
18 | var result = "["
19 | var first = true
20 | for element in self {
21 | if first {
22 | first = false
23 | } else {
24 | result += ", "
25 | }
26 | print(element, terminator: "", to: &result)
27 | }
28 | result += "]"
29 | return result
30 | }
31 |
32 | @inlinable
33 | public var debugDescription: String {
34 | var result = "SortedSet<\(Element.self)>(["
35 | var first = true
36 | for element in self {
37 | if first {
38 | first = false
39 | } else {
40 | result += ", "
41 | }
42 |
43 | debugPrint(element, terminator: "", to: &result)
44 | }
45 | result += "])"
46 | return result
47 | }
48 | }
49 | #endif
50 |
51 | #endif
52 |
--------------------------------------------------------------------------------
/Tests/HashTreeCollectionsTests/TreeDictionary.Values Tests.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | import XCTest
13 | #if COLLECTIONS_SINGLE_MODULE
14 | import Collections
15 | #else
16 | import _CollectionsTestSupport
17 | import HashTreeCollections
18 | #endif
19 |
20 | class TreeDictionaryValuesTests: CollectionTestCase {
21 | func test_BidirectionalCollection_fixtures() {
22 | withEachFixture { fixture in
23 | withLifetimeTracking { tracker in
24 | let (d, ref) = tracker.shareableDictionary(for: fixture)
25 | let v = ref.map { $0.value }
26 | checkCollection(d.values, expectedContents: v, by: ==)
27 | _checkBidirectionalCollection_indexOffsetBy(
28 | d.values, expectedContents: v, by: ==)
29 | }
30 | }
31 | }
32 |
33 | func test_descriptions() {
34 | let d: TreeDictionary = [
35 | "a": 1,
36 | "b": 2
37 | ]
38 |
39 | if d.first!.key == "a" {
40 | expectEqual(d.values.description, "[1, 2]")
41 | } else {
42 | expectEqual(d.values.description, "[2, 1]")
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Xcode/Collections.xcconfig:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | PRODUCT_NAME = Collections
13 | PRODUCT_BUNDLE_IDENTIFIER = org.swift.Collections
14 |
15 | SUPPORTED_PLATFORMS = macosx iphoneos iphonesimulator watchos watchsimulator appletvos appletvsimulator
16 | ARCHS = $(ARCHS_STANDARD)
17 |
18 | MACOSX_DEPLOYMENT_TARGET = 12.0
19 | IPHONEOS_DEPLOYMENT_TARGET = 15.0
20 | WATCHOS_DEPLOYMENT_TARGET = 8.0
21 | TVOS_DEPLOYMENT_TARGET = 15.0
22 |
23 | MARKETING_VERSION = 1.1
24 |
25 | CURRENT_PROJECT_VERSION = 1
26 | VERSIONING_SYSTEM = apple-generic
27 | VERSION_INFO_PREFIX =
28 |
29 | DYLIB_COMPATIBILITY_VERSION = $(CURRENT_PROJECT_VERSION)
30 | DYLIB_CURRENT_VERSION = $(CURRENT_PROJECT_VERSION)
31 |
32 | INSTALL_PATH = $(LOCAL_LIBRARY_DIR)/Frameworks
33 | SKIP_INSTALL = YES
34 | DYLIB_INSTALL_NAME_BASE = @rpath
35 | LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/../Frameworks @loader_path/Frameworks
36 |
37 | ENABLE_TESTABILITY = NO
38 | ENABLE_TESTABILITY[config=Debug] = YES
39 |
40 | GENERATE_INFOPLIST_FILE = YES
41 |
42 | CODE_SIGN_STYLE = Automatic
43 | CODE_SIGN_IDENTITY = -
44 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/Benchmarks/Cpp/CppBenchmarks.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | import CollectionsBenchmark
13 | import CppBenchmarks
14 |
15 | extension Benchmark {
16 | public mutating func addCppBenchmarks() {
17 | cpp_set_hash_fn { value in value._rawHashValue(seed: 0) }
18 |
19 | self.addSimple(
20 | title: "std::hash",
21 | input: [Int].self
22 | ) { input in
23 | input.withUnsafeBufferPointer { buffer in
24 | cpp_hash(buffer.baseAddress, buffer.count)
25 | }
26 | }
27 |
28 | self.addSimple(
29 | title: "custom_intptr_hash (using Swift.Hasher)",
30 | input: [Int].self
31 | ) { input in
32 | input.withUnsafeBufferPointer { buffer in
33 | cpp_custom_hash(buffer.baseAddress, buffer.count)
34 | }
35 | }
36 |
37 | _addCppVectorBenchmarks()
38 | _addCppDequeBenchmarks()
39 | _addCppUnorderedSetBenchmarks()
40 | _addCppUnorderedMapBenchmarks()
41 | _addCppPriorityQueueBenchmarks()
42 | _addCppVectorBoolBenchmarks()
43 | _addCppMapBenchmarks()
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedSet/OrderedSet+ExpressibleByArrayLiteral.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension OrderedSet: ExpressibleByArrayLiteral {
13 | /// Creates a new ordered set from the contents of an array literal.
14 | ///
15 | /// Duplicate elements in the literal are allowed, but the resulting ordered
16 | /// set will only contain the first occurrence of each.
17 | ///
18 | /// Do not call this initializer directly. It is used by the compiler when
19 | /// you use an array literal. Instead, create a new ordered set using an array
20 | /// literal as its value by enclosing a comma-separated list of values in
21 | /// square brackets. You can use an array literal anywhere an ordered set is
22 | /// expected by the type context.
23 | ///
24 | /// - Parameter elements: A variadic list of elements of the new ordered set.
25 | ///
26 | /// - Complexity: O(`elements.count`) if `Element` implements
27 | /// high-quality hashing.
28 | @inlinable
29 | public init(arrayLiteral elements: Element...) {
30 | self.init(elements)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/BUG_REPORT.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: 🐛 Bug Report
3 | about: Something isn't working as expected
4 | labels: bug
5 | ---
6 |
7 |
17 |
18 | Replace this paragraph with a short description of the incorrect behavior.
19 | (If this is a regression, please note the last version of the package that exhibited the correct behavior in addition to your current version.)
20 |
21 | ### Information
22 |
23 | - **Package version:** What tag or branch of swift-collections are you using?
24 | - **Platform version:** Please tell us the version number of your operating system.
25 | - **Swift version:** Paste the output of `swift --version` here.
26 |
27 | ### Checklist
28 |
29 | - [ ] If possible, I've reproduced the issue using the `main` branch of this package.
30 | - [ ] I've searched for [existing GitHub issues](https://github.com/apple/swift-collections/issues).
31 |
32 | ### Steps to Reproduce
33 | Replace this paragraph with an explanation of how to reproduce the incorrect behavior.
34 | Include a simple code example, if possible.
35 |
36 | ### Expected behavior
37 | Describe what you expect to happen.
38 |
39 | ### Actual behavior
40 | Describe or copy/paste the behavior you observe.
41 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitSet/BitSet+Codable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !$Embedded
13 | extension BitSet: Codable {
14 | /// Encodes this bit set into the given encoder.
15 | ///
16 | /// Bit sets are encoded as an unkeyed container of `UInt64` values,
17 | /// representing pieces of the underlying bitmap.
18 | ///
19 | /// - Parameter encoder: The encoder to write data to.
20 | public func encode(to encoder: Encoder) throws {
21 | var container = encoder.unkeyedContainer()
22 | try _storage._encodeAsUInt64(to: &container)
23 | }
24 |
25 | /// Creates a new bit set by decoding from the given decoder.
26 | ///
27 | /// Bit sets are encoded as an unkeyed container of `UInt64` values,
28 | /// representing pieces of the underlying bitmap.
29 | ///
30 | /// - Parameter decoder: The decoder to read data from.
31 | public init(from decoder: Decoder) throws {
32 | var container = try decoder.unkeyedContainer()
33 | let words = try [_Word](
34 | _fromUInt64: &container, reservingCount: container.count)
35 | self.init(_words: words)
36 | }
37 | }
38 | #endif
39 |
--------------------------------------------------------------------------------
/Sources/Collections/Collections.docc/Extensions/OrderedSet.UnorderedView.md:
--------------------------------------------------------------------------------
1 | # ``Collections/OrderedSet/UnorderedView``
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | ## Topics
11 |
12 | ### Binary Set Operations
13 |
14 | - ``intersection(_:)-3q45l``
15 | - ``intersection(_:)-6ee3o``
16 |
17 | - ``union(_:)-79uk3``
18 | - ``union(_:)-23dm1``
19 |
20 | - ``subtracting(_:)-3ct1b``
21 | - ``subtracting(_:)-8e6mw``
22 |
23 | - ``symmetricDifference(_:)-6aed7``
24 | - ``symmetricDifference(_:)-7r79p``
25 |
26 | - ``formIntersection(_:)-4ow38``
27 | - ``formIntersection(_:)-80iht``
28 |
29 | - ``formUnion(_:)-6ijb``
30 | - ``formUnion(_:)-8tuol``
31 |
32 | - ``subtract(_:)-627eq``
33 | - ``subtract(_:)-4pjhu``
34 |
35 | - ``formSymmetricDifference(_:)-8pkt5``
36 | - ``formSymmetricDifference(_:)-75z52``
37 |
38 | ### Binary Set Predicates
39 |
40 | - ``==(_:_:)``
41 | - ``isEqualSet(to:)-1szq``
42 | - ``isEqualSet(to:)-9djqq``
43 |
44 | - ``isSubset(of:)-2dx31``
45 | - ``isSubset(of:)-801lo``
46 | - ``isSubset(of:)-952h5``
47 |
48 | - ``isSuperset(of:)-9t33p``
49 | - ``isSuperset(of:)-2vtig``
50 | - ``isSuperset(of:)-9krpz``
51 |
52 | - ``isStrictSubset(of:)-9o6mg``
53 | - ``isStrictSubset(of:)-91par``
54 | - ``isStrictSubset(of:)-7n66e``
55 |
56 | - ``isStrictSuperset(of:)-89ig3``
57 | - ``isStrictSuperset(of:)-1e0xt``
58 | - ``isStrictSuperset(of:)-5dsfd``
59 |
60 | - ``isDisjoint(with:)-3wuso``
61 | - ``isDisjoint(with:)-25vmx``
62 | - ``isDisjoint(with:)-8nfqs``
63 |
--------------------------------------------------------------------------------
/Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension Rope: Sequence {
13 | @inlinable
14 | public func makeIterator() -> Iterator {
15 | Iterator(self, from: self.startIndex)
16 | }
17 |
18 | @inlinable
19 | public func makeIterator(from start: Index) -> Iterator {
20 | Iterator(self, from: start)
21 | }
22 |
23 | @frozen // Not really! This module isn't ABI stable.
24 | public struct Iterator: IteratorProtocol {
25 | @usableFromInline
26 | internal let _rope: Rope
27 |
28 | @usableFromInline
29 | internal var _index: Index
30 |
31 | @inlinable
32 | internal init(_ rope: Rope, from start: Index) {
33 | rope.validate(start)
34 | self._rope = rope
35 | self._index = start
36 | self._rope.grease(&_index)
37 | }
38 |
39 | @inlinable
40 | public mutating func next() -> Element? {
41 | guard let leaf = _index._leaf else { return nil }
42 | let item = leaf.read { $0.children[_index._path[0]].value }
43 | _rope.formIndex(after: &_index)
44 | return item
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedSet/SortedSet+ExpressibleByArrayLiteral.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | extension SortedSet: ExpressibleByArrayLiteral {
15 | /// Creates a new sorted set from the contents of an array literal.
16 | ///
17 | /// Duplicate elements in the literal are allowed, but the resulting
18 | /// set will only contain the last occurrence of each.
19 | ///
20 | /// Do not call this initializer directly. It is used by the compiler when
21 | /// you use an array literal. Instead, create a new set using an array
22 | /// literal as its value by enclosing a comma-separated list of values in
23 | /// square brackets. You can use an array literal anywhere a set is expected
24 | /// by the type context.
25 | ///
26 | /// - Parameter elements: A variadic list of elements of the new set.
27 | ///
28 | /// - Complexity: O(`n log n`) where `n` is the number of elements
29 | /// in `elements`.
30 | @inlinable
31 | public init(arrayLiteral elements: Element...) {
32 | self.init(elements)
33 | }
34 | }
35 |
36 | #endif
37 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeSet/TreeSet+Debugging.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension TreeSet {
17 | /// True if consistency checking is enabled in the implementation of this
18 | /// type, false otherwise.
19 | ///
20 | /// Documented performance promises are null and void when this property
21 | /// returns true -- for example, operations that are documented to take
22 | /// O(1) time might take O(*n*) time, or worse.
23 | public static var _isConsistencyCheckingEnabled: Bool {
24 | _isCollectionsInternalCheckingEnabled
25 | }
26 |
27 | @inlinable
28 | public func _invariantCheck() {
29 | _root._fullInvariantCheck()
30 | }
31 |
32 | public func _dump(iterationOrder: Bool = false) {
33 | _root.dump(iterationOrder: iterationOrder)
34 | }
35 |
36 | public static var _maxDepth: Int {
37 | _HashLevel.limit
38 | }
39 |
40 | public var _statistics: _HashTreeStatistics {
41 | var stats = _HashTreeStatistics()
42 | _root.gatherStatistics(.top, &stats)
43 | return stats
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Debugging.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension TreeDictionary {
17 | /// True if consistency checking is enabled in the implementation of this
18 | /// type, false otherwise.
19 | ///
20 | /// Documented performance promises are null and void when this property
21 | /// returns true -- for example, operations that are documented to take
22 | /// O(1) time might take O(*n*) time, or worse.
23 | public static var _isConsistencyCheckingEnabled: Bool {
24 | _isCollectionsInternalCheckingEnabled
25 | }
26 |
27 | @inlinable
28 | public func _invariantCheck() {
29 | _root._fullInvariantCheck()
30 | }
31 |
32 | public func _dump(iterationOrder: Bool = false) {
33 | _root.dump(iterationOrder: iterationOrder)
34 | }
35 |
36 | public static var _maxDepth: Int {
37 | _HashLevel.limit
38 | }
39 |
40 | public var _statistics: _HashTreeStatistics {
41 | var stats = _HashTreeStatistics()
42 | _root.gatherStatistics(.top, &stats)
43 | return stats
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitSet/BitSet+Invariants.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension BitSet {
17 | /// True if consistency checking is enabled in the implementation of this
18 | /// type, false otherwise.
19 | ///
20 | /// Documented performance promises are null and void when this property
21 | /// returns true -- for example, operations that are documented to take
22 | /// O(1) time might take O(*n*) time, or worse.
23 | public static var _isConsistencyCheckingEnabled: Bool {
24 | _isCollectionsInternalCheckingEnabled
25 | }
26 |
27 | #if COLLECTIONS_INTERNAL_CHECKS
28 | @inline(never)
29 | @_effects(releasenone)
30 | public func _checkInvariants() {
31 | //let actualCount = _storage.reduce(into: 0) { $0 += $1.count }
32 | //precondition(_count == actualCount, "Invalid count")
33 |
34 | precondition(_storage.isEmpty || !_storage.last!.isEmpty,
35 | "Extraneous tail slot")
36 | }
37 | #else
38 | @inline(__always) @inlinable
39 | public func _checkInvariants() {}
40 | #endif // COLLECTIONS_INTERNAL_CHECKS
41 | }
42 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedDictionary/SortedDictionary+ExpressibleByDictionaryLiteral.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | extension SortedDictionary: ExpressibleByDictionaryLiteral {
15 | /// Creates a new sorted dictionary from the contents of a dictionary
16 | /// literal.
17 | ///
18 | /// Duplicate elements in the literal are allowed, but the resulting
19 | /// set will only contain the first occurrence of each.
20 | ///
21 | /// Do not call this initializer directly. It is used by the compiler when you
22 | /// use a dictionary literal. Instead, create a new ordered dictionary using a
23 | /// dictionary literal as its value by enclosing a comma-separated list of
24 | /// values in square brackets. You can use an array literal anywhere a set is
25 | /// expected by the type context.
26 | ///
27 | /// - Parameter elements: A variadic list of key-value pairs for the new
28 | /// dictionary.
29 | ///
30 | /// - Complexity: O(`n log n`)
31 | @inlinable
32 | public init(dictionaryLiteral elements: (Key, Value)...) {
33 | self.init(keysWithValues: elements)
34 | }
35 | }
36 |
37 | #endif
38 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeSet/TreeSet+ExpressibleByArrayLiteral.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension TreeSet: ExpressibleByArrayLiteral {
13 | /// Creates a new set from the contents of an array literal.
14 | ///
15 | /// Duplicate elements in the literal are allowed, but the resulting
16 | /// persistent set will only contain the first occurrence of each.
17 | ///
18 | /// Do not call this initializer directly. It is used by the compiler when
19 | /// you use an array literal. Instead, create a new persistent set using an
20 | /// array literal as its value by enclosing a comma-separated list of values
21 | /// in square brackets. You can use an array literal anywhere a persistent set
22 | /// is expected by the type context.
23 | ///
24 | /// Like the standard `Set`, persistent sets do not preserve the order of
25 | /// elements inside the array literal.
26 | ///
27 | /// - Parameter elements: A variadic list of elements of the new set.
28 | ///
29 | /// - Complexity: O(`elements.count`) if `Element` properly implements
30 | /// hashing.
31 | public init(arrayLiteral elements: Element...) {
32 | self.init(elements)
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Sources/DequeModule/_DequeBufferHeader.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | @usableFromInline
13 | internal struct _DequeBufferHeader {
14 | @usableFromInline
15 | var capacity: Int
16 |
17 | @usableFromInline
18 | var count: Int
19 |
20 | @usableFromInline
21 | var startSlot: _DequeSlot
22 |
23 | @usableFromInline
24 | init(capacity: Int, count: Int, startSlot: _DequeSlot) {
25 | self.capacity = capacity
26 | self.count = count
27 | self.startSlot = startSlot
28 | _checkInvariants()
29 | }
30 |
31 | #if COLLECTIONS_INTERNAL_CHECKS
32 | @usableFromInline @inline(never) @_effects(releasenone)
33 | internal func _checkInvariants() {
34 | precondition(capacity >= 0)
35 | precondition(count >= 0 && count <= capacity)
36 | precondition(startSlot.position >= 0 && startSlot.position <= capacity)
37 | }
38 | #else
39 | @inlinable @inline(__always)
40 | internal func _checkInvariants() {}
41 | #endif // COLLECTIONS_INTERNAL_CHECKS
42 | }
43 |
44 | extension _DequeBufferHeader: CustomStringConvertible {
45 | @usableFromInline
46 | internal var description: String {
47 | "(capacity: \(capacity), count: \(count), startSlot: \(startSlot))"
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Sources/InternalCollectionsUtilities/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | #[[
2 | This source file is part of the Swift Collections Open Source Project
3 |
4 | Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
5 | Licensed under Apache License v2.0 with Runtime Library Exception
6 |
7 | See https://swift.org/LICENSE.txt for license information
8 | #]]
9 |
10 | if(COLLECTIONS_SINGLE_MODULE)
11 | set(module_name ${COLLECTIONS_MODULE_NAME})
12 | else()
13 | set(module_name InternalCollectionsUtilities)
14 | add_library(InternalCollectionsUtilities
15 | ${COLLECTIONS_UTILITIES_SOURCES})
16 | set_target_properties(InternalCollectionsUtilities PROPERTIES
17 | INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
18 |
19 | _install_target(InternalCollectionsUtilities)
20 | set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS InternalCollectionsUtilities)
21 | endif()
22 |
23 | target_sources(${module_name} PRIVATE
24 | "Debugging.swift"
25 | "Descriptions.swift"
26 | "LifetimeOverride.swift"
27 | "RandomAccessCollection+Offsets.swift"
28 | "UnsafeBufferPointer+Extras.swift"
29 | "UnsafeMutableBufferPointer+Extras.swift"
30 | "UnsafeRawBufferPointer+Extras.swift"
31 | "UnsafeMutableRawBufferPointer+Extras.swift"
32 | "IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift"
33 | "IntegerTricks/Integer rank.swift"
34 | "IntegerTricks/UInt+first and last set bit.swift"
35 | "IntegerTricks/UInt+reversed.swift"
36 | "UnsafeBitSet/_UnsafeBitSet+Index.swift"
37 | "UnsafeBitSet/_UnsafeBitSet+_Word.swift"
38 | "UnsafeBitSet/_UnsafeBitSet.swift"
39 | "_SortedCollection.swift"
40 | "_UniqueCollection.swift"
41 | )
42 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitArray/BitArray+Invariants.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension BitArray {
17 | /// True if consistency checking is enabled in the implementation of this
18 | /// type, false otherwise.
19 | ///
20 | /// Documented performance promises are null and void when this property
21 | /// returns true -- for example, operations that are documented to take
22 | /// O(1) time might take O(*n*) time, or worse.
23 | public static var _isConsistencyCheckingEnabled: Bool {
24 | _isCollectionsInternalCheckingEnabled
25 | }
26 |
27 | #if COLLECTIONS_INTERNAL_CHECKS
28 | @inline(never)
29 | @_effects(releasenone)
30 | public func _checkInvariants() {
31 | precondition(_count <= _storage.count * _Word.capacity)
32 | precondition(_count > (_storage.count - 1) * _Word.capacity)
33 | let p = _BitPosition(_count).split
34 | if p.bit > 0 {
35 | precondition(_storage.last!.subtracting(_Word(upTo: p.bit)) == .empty)
36 | }
37 | }
38 | #else
39 | @inline(__always) @inlinable
40 | public func _checkInvariants() {}
41 | #endif // COLLECTIONS_INTERNAL_CHECKS
42 | }
43 |
--------------------------------------------------------------------------------
/Tests/CollectionsTestSupportTests/MinimalTypeConformances.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | import XCTest
13 | #if !COLLECTIONS_SINGLE_MODULE
14 | import _CollectionsTestSupport
15 | #endif
16 |
17 | final class MinimalTypeTests: CollectionTestCase {
18 | func testMinimalSequence() {
19 | withEvery(
20 | "behavior",
21 | in: [
22 | UnderestimatedCountBehavior.precise,
23 | UnderestimatedCountBehavior.half,
24 | UnderestimatedCountBehavior.value(0)
25 | ]
26 | ) { behavior in
27 | withEvery("isContiguous", in: [false, true]) { isContiguous in
28 | func make() -> MinimalSequence {
29 | MinimalSequence(
30 | elements: 0 ..< 50,
31 | underestimatedCount: behavior,
32 | isContiguous: isContiguous)
33 | }
34 | checkSequence(make, expectedContents: 0 ..< 50)
35 | }
36 | }
37 | }
38 |
39 | func testMinimalCollection() {
40 | checkCollection(MinimalCollection(0 ..< 50), expectedContents: 0 ..< 50)
41 | }
42 |
43 | func testMinimalBidirectionalCollection() {
44 | checkBidirectionalCollection(MinimalBidirectionalCollection(0 ..< 50), expectedContents: 0 ..< 50)
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitSet/BitSet+Sorted Collection APIs.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension BitSet: _SortedCollection {
17 | /// Returns the current set (already sorted).
18 | ///
19 | /// - Complexity: O(1)
20 | public func sorted() -> BitSet { self }
21 |
22 | /// Returns the minimum element in this set.
23 | ///
24 | /// Bit sets are sorted, so the minimum element is always at the first
25 | /// position in the set.
26 | ///
27 | /// - Returns: The bit set's minimum element. If the sequence has no
28 | /// elements, returns `nil`.
29 | ///
30 | /// - Complexity: O(1)
31 | @warn_unqualified_access
32 | public func min() -> Element? {
33 | first
34 | }
35 |
36 | /// Returns the maximum element in this set.
37 | ///
38 | /// Bit sets are sorted, so the maximum element is always at the last
39 | /// position in the set.
40 | ///
41 | /// - Returns: The bit set's maximum element. If the sequence has no
42 | /// elements, returns `nil`.
43 | ///
44 | /// - Complexity: O(1)
45 | @warn_unqualified_access
46 | public func max() -> Element? {
47 | last
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension Rope {
13 | @frozen // Not really! This module isn't ABI stable.
14 | @usableFromInline
15 | internal struct _UnmanagedLeaf {
16 | @usableFromInline internal typealias _Item = Rope._Item
17 | @usableFromInline internal typealias _Leaf = _Storage<_Item>
18 | @usableFromInline internal typealias _UnsafeHandle = Rope._UnsafeHandle
19 |
20 | @usableFromInline var _ref: Unmanaged<_Leaf>
21 |
22 | @inlinable
23 | internal init(_ leaf: __shared _Leaf) {
24 | _ref = .passUnretained(leaf)
25 | }
26 | }
27 | }
28 |
29 | extension Rope._UnmanagedLeaf: Equatable {
30 | @inlinable
31 | internal static func ==(left: Self, right: Self) -> Bool {
32 | left._ref.toOpaque() == right._ref.toOpaque()
33 | }
34 | }
35 |
36 | extension Rope._UnmanagedLeaf {
37 | @inlinable
38 | internal func read(
39 | body: (_UnsafeHandle<_Item>) -> R
40 | ) -> R {
41 | _ref._withUnsafeGuaranteedRef { leaf in
42 | leaf.withUnsafeMutablePointers { h, p in
43 | let handle = _UnsafeHandle(isMutable: false, header: h, start: p)
44 | return body(handle)
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+ExpressibleByDictionaryLiteral.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2019 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension TreeDictionary: ExpressibleByDictionaryLiteral {
13 | /// Creates a new dictionary from the contents of a dictionary literal.
14 | ///
15 | /// The literal must not contain duplicate elements.
16 | ///
17 | /// Do not call this initializer directly. It is used by the compiler when
18 | /// you use a dictionary literal. Instead, create a new dictionary using a
19 | /// dictionary literal as its value by enclosing a comma-separated list of
20 | /// values in square brackets. You can use a dictionary literal anywhere a
21 | /// persistent dictionary is expected by the type context.
22 | ///
23 | /// Like the standard `Dictionary`, persistent dictionaries do not preserve
24 | /// the order of elements inside the array literal.
25 | ///
26 | /// - Parameter elements: A variadic list of elements of the new set.
27 | ///
28 | /// - Complexity: O(`elements.count`) if `Element` properly implements
29 | /// hashing.
30 | @inlinable
31 | @inline(__always)
32 | public init(dictionaryLiteral elements: (Key, Value)...) {
33 | self.init(uniqueKeysWithValues: elements)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Sources/HashTreeCollections/HashNode/_HashNode+Structural compactMapValues.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension _HashNode {
13 | @inlinable
14 | internal func compactMapValues(
15 | _ level: _HashLevel,
16 | _ transform: (Value) throws -> T?
17 | ) rethrows -> _HashNode.Builder {
18 | return try self.read {
19 | var result: _HashNode.Builder = .empty(level)
20 |
21 | if isCollisionNode {
22 | let items = $0.reverseItems
23 | for i in items.indices {
24 | if let v = try transform(items[i].value) {
25 | result.addNewCollision(level, (items[i].key, v), $0.collisionHash)
26 | }
27 | }
28 | return result
29 | }
30 |
31 | for (bucket, slot) in $0.itemMap {
32 | let p = $0.itemPtr(at: slot)
33 | if let v = try transform(p.pointee.value) {
34 | result.addNewItem(level, (p.pointee.key, v), at: bucket)
35 | }
36 | }
37 |
38 | for (bucket, slot) in $0.childMap {
39 | let branch = try $0[child: slot]
40 | .compactMapValues(level.descend(), transform)
41 | result.addNewChildBranch(level, branch, at: bucket)
42 | }
43 | return result
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Tests/_CollectionsTestSupport/Utilities/LifetimeTrackedStruct.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift.org open source project
4 | //
5 | // Copyright (c) 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10 | //
11 | //===----------------------------------------------------------------------===//
12 |
13 | /// A type that tracks the number of live instances.
14 | ///
15 | /// `LifetimeTracked` is useful to check for leaks in algorithms and data
16 | /// structures. The easiest way to produce instances is to use the
17 | /// `withLifetimeTracking` function:
18 | ///
19 | /// class FooTests: XCTestCase {
20 | /// func testFoo() {
21 | /// withLifetimeTracking([1, 2, 3]) { instances in
22 | /// _ = instances.sorted(by: >)
23 | /// }
24 | /// }
25 | /// }
26 | public struct LifetimeTrackedStruct: ~Copyable {
27 | public let tracker: LifetimeTracker
28 | internal var serialNumber: Int = 0
29 | public var payload: Payload
30 |
31 | public init(_ payload: consuming Payload, for tracker: LifetimeTracker) {
32 | tracker.instances += 1
33 | tracker._nextSerialNumber += 1
34 | self.tracker = tracker
35 | self.serialNumber = tracker._nextSerialNumber
36 | self.payload = payload
37 | }
38 |
39 | deinit {
40 | precondition(serialNumber != 0, "Double deinit")
41 | tracker.instances -= 1
42 | }
43 | }
44 |
45 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/benchmark-tool/main.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | import CollectionsBenchmark
13 | import Benchmarks
14 | import DequeModule
15 |
16 | if Deque._isConsistencyCheckingEnabled {
17 | complain("""
18 | *** INTERNAL CONSISTENCY CHECKING IS ENABLED ***
19 |
20 | Performance guarantees aren't valid in this configuration,
21 | and benchmarking data will be largely useless. Proceed at
22 | your own risk.
23 |
24 | """)
25 | }
26 |
27 | var benchmark = Benchmark(title: "Collection Benchmarks")
28 | benchmark.registerCustomGenerators()
29 | benchmark.addArrayBenchmarks()
30 | benchmark.addSetBenchmarks()
31 | benchmark.addDictionaryBenchmarks()
32 | benchmark.addTreeDictionaryBenchmarks()
33 | benchmark.addDequeBenchmarks()
34 | benchmark.addOrderedSetBenchmarks()
35 | benchmark.addOrderedDictionaryBenchmarks()
36 | #if false
37 | benchmark.addSortedSetBenchmarks()
38 | benchmark.addSortedDictionaryBenchmarks()
39 | #endif
40 | benchmark.addHeapBenchmarks()
41 | benchmark.addBitSetBenchmarks()
42 | benchmark.addTreeSetBenchmarks()
43 | benchmark.addCppBenchmarks()
44 | benchmark.addBigStringBenchmarks()
45 | #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
46 | benchmark.addFoundationBenchmarks()
47 | #endif
48 |
49 | benchmark.main()
50 |
--------------------------------------------------------------------------------
/Sources/RopeModule/BigString/Conformances/BigString+Comparable.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2023 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && !$Embedded
13 |
14 | @available(SwiftStdlib 6.2, *)
15 | extension BigString: Comparable {
16 | public static func < (left: Self, right: Self) -> Bool {
17 | // FIXME: Implement properly normalized comparisons & hashing.
18 | // This is somewhat tricky as we shouldn't just normalize individual pieces of the string
19 | // split up on random Character boundaries -- Unicode does not promise that
20 | // norm(a + c) == norm(a) + norm(b) in this case.
21 | // To do this properly, we'll probably need to expose new stdlib entry points. :-/
22 | if left.isIdentical(to: right) { return false }
23 | // FIXME: Even if we keep doing characterwise comparisons, we should skip over shared subtrees.
24 | var it1 = left.makeIterator()
25 | var it2 = right.makeIterator()
26 | while true {
27 | switch (it1.next(), it2.next()) {
28 | case (nil, nil): return false
29 | case (nil, .some): return true
30 | case (.some, nil): return false
31 | case let (a?, b?):
32 | if a == b { continue }
33 | return a < b
34 | }
35 | }
36 | }
37 | }
38 |
39 | #endif // compiler(>=6.2) && !$Embedded
40 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/CppBenchmarks/src/PriorityQueueBenchmarks.cpp:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #include
13 | #include "PriorityQueueBenchmarks.h"
14 | #include "Utils.h"
15 |
16 | typedef std::priority_queue pqueue;
17 |
18 | void *
19 | cpp_priority_queue_create(const intptr_t *start, size_t count)
20 | {
21 | auto pq = new pqueue(start, start + count);
22 | return pq;
23 | }
24 |
25 | void
26 | cpp_priority_queue_destroy(void *ptr)
27 | {
28 | delete static_cast(ptr);
29 | }
30 |
31 | void
32 | cpp_priority_queue_push(void *ptr, intptr_t value)
33 | {
34 | auto pq = static_cast(ptr);
35 | pq->push(value);
36 | }
37 |
38 | void
39 | cpp_priority_queue_push_loop(void *ptr, const intptr_t *start, size_t count)
40 | {
41 | auto pq = static_cast(ptr);
42 | for (auto p = start; p < start + count; ++p) {
43 | pq->push(*p);
44 | }
45 | }
46 |
47 | intptr_t cpp_priority_queue_pop(void *ptr)
48 | {
49 | auto pq = static_cast(ptr);
50 | auto result = pq->top();
51 | pq->pop();
52 | return result;
53 | }
54 |
55 | void
56 | cpp_priority_queue_pop_all(void *ptr)
57 | {
58 | auto pq = static_cast(ptr);
59 | while (!pq->empty()) {
60 | black_hole(pq->top());
61 | pq->pop();
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Sources/OrderedCollections/OrderedSet/OrderedSet+UnstableInternals.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | extension OrderedSet {
13 | /// Exposes some private implementation details and low-level unsafe
14 | /// operations, primarily to allow clear box testing.
15 | ///
16 | /// This struct is a private implementation detail, therefore it and its
17 | /// members are not covered by any source compatibility promises -- they
18 | /// may disappear in any new release.
19 | @frozen
20 | public struct _UnstableInternals {
21 | @usableFromInline
22 | internal typealias _Bucket = _HashTable.Bucket
23 |
24 | @usableFromInline
25 | internal var base: OrderedSet
26 |
27 | @inlinable
28 | init(_ base: OrderedSet) {
29 | self.base = base
30 | }
31 | }
32 |
33 | @inlinable
34 | public var __unstable: _UnstableInternals {
35 | @inline(__always)
36 | get {
37 | _UnstableInternals(self)
38 | }
39 |
40 | @inline(__always) // https://github.com/apple/swift-collections/issues/164
41 | _modify {
42 | var view = _UnstableInternals(self)
43 | self = OrderedSet()
44 | defer { self = view.base }
45 | yield &view
46 | }
47 | }
48 | }
49 |
50 | extension OrderedSet._UnstableInternals: Sendable
51 | where Element: Sendable {}
52 |
--------------------------------------------------------------------------------
/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomStringConvertible.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS
13 |
14 | #if !$Embedded
15 | extension SortedDictionary: CustomStringConvertible, CustomDebugStringConvertible {
16 | @inlinable
17 | public var description: String {
18 | if isEmpty { return "[:]" }
19 | var result = "["
20 | var first = true
21 | for (key, value) in self {
22 | if first {
23 | first = false
24 | } else {
25 | result += ", "
26 | }
27 | result += "\(key): \(value)"
28 | }
29 | result += "]"
30 | return result
31 | }
32 |
33 | @inlinable
34 | public var debugDescription: String {
35 | var result = "SortedDictionary<\(Key.self), \(Value.self)>("
36 | if isEmpty {
37 | result += "[:]"
38 | } else {
39 | result += "["
40 | var first = true
41 | for (key, value) in self {
42 | if first {
43 | first = false
44 | } else {
45 | result += ", "
46 | }
47 |
48 | debugPrint(key, value, separator: ": ", terminator: "", to: &result)
49 | }
50 | result += "]"
51 | }
52 | result += ")"
53 | return result
54 | }
55 | }
56 | #endif
57 |
58 | #endif
59 |
--------------------------------------------------------------------------------
/Sources/ContainersPreview/Ref.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
13 | import Builtin
14 |
15 | @frozen
16 | @safe
17 | public struct Ref: Copyable, ~Escapable {
18 | @usableFromInline
19 | package let _pointer: UnsafePointer
20 |
21 | #if compiler(>=6.2) && FIXME
22 | @_lifetime(borrow value)
23 | @_alwaysEmitIntoClient
24 | @_transparent
25 | public init(_ value: borrowing @_addressable T) {
26 | unsafe _pointer = UnsafePointer(Builtin.unprotectedAddressOfBorrow(value))
27 | }
28 | #endif
29 |
30 | @_lifetime(borrow owner)
31 | @_alwaysEmitIntoClient
32 | @_transparent
33 | public init(
34 | unsafeAddress: UnsafePointer,
35 | borrowing owner: borrowing Owner
36 | ) {
37 | unsafe _pointer = unsafeAddress
38 | }
39 |
40 | @_lifetime(copy owner)
41 | @_alwaysEmitIntoClient
42 | @_transparent
43 | public init(
44 | unsafeAddress: UnsafePointer,
45 | copying owner: borrowing Owner
46 | ) {
47 | unsafe _pointer = unsafeAddress
48 | }
49 |
50 | @_alwaysEmitIntoClient
51 | public subscript() -> T {
52 | @_transparent
53 | unsafeAddress {
54 | unsafe _pointer
55 | }
56 | }
57 | }
58 | #endif
59 |
--------------------------------------------------------------------------------
/Sources/BitCollections/BitArray/BitArray+RandomBits.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2022 - 2025 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | #if !COLLECTIONS_SINGLE_MODULE
13 | import InternalCollectionsUtilities
14 | #endif
15 |
16 | extension BitArray {
17 | /// Create and return a new bit array consisting of `count` random bits,
18 | /// using the system random number generator.
19 | ///
20 | /// - Parameter count: The number of random bits to generate.
21 | public static func randomBits(count: Int) -> BitArray {
22 | var rng = SystemRandomNumberGenerator()
23 | return randomBits(count: count, using: &rng)
24 | }
25 |
26 | /// Create and return a new bit array consisting of `count` random bits,
27 | /// using the given random number generator.
28 | ///
29 | /// - Parameter count: The number of random bits to generate.
30 | /// - Parameter rng: The random number generator to use.
31 | public static func randomBits(
32 | count: Int,
33 | using rng: inout some RandomNumberGenerator
34 | ) -> BitArray {
35 | precondition(count >= 0, "Invalid count")
36 | guard count > 0 else { return BitArray() }
37 | let (w, b) = _BitPosition(count).endSplit
38 | var words = (0 ... w).map { _ in _Word(rng.next() as UInt) }
39 | words[w].formIntersection(_Word(upTo: b))
40 | return BitArray(_storage: words, count: count)
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Benchmarks/Sources/Benchmarks/Cpp/CppMapBenchmarks.swift:
--------------------------------------------------------------------------------
1 | //===----------------------------------------------------------------------===//
2 | //
3 | // This source file is part of the Swift Collections open source project
4 | //
5 | // Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | //
10 | //===----------------------------------------------------------------------===//
11 |
12 | import CollectionsBenchmark
13 | import CppBenchmarks
14 |
15 | internal class CppMap {
16 | var ptr: UnsafeMutableRawPointer?
17 |
18 | init(_ input: [Int]) {
19 | self.ptr = input.withUnsafeBufferPointer { buffer in
20 | cpp_map_create(buffer.baseAddress, buffer.count)
21 | }
22 | }
23 |
24 | deinit {
25 | destroy()
26 | }
27 |
28 | func destroy() {
29 | if let ptr = ptr {
30 | cpp_map_destroy(ptr)
31 | }
32 | ptr = nil
33 | }
34 | }
35 |
36 | extension Benchmark {
37 | internal mutating func _addCppMapBenchmarks() {
38 | self.addSimple(
39 | title: "std::map insert",
40 | input: [Int].self
41 | ) { input in
42 | input.withUnsafeBufferPointer { buffer in
43 | cpp_map_insert_integers(buffer.baseAddress, buffer.count)
44 | }
45 | }
46 |
47 | self.add(
48 | title: "std::map successful find",
49 | input: ([Int], [Int]).self
50 | ) { input, lookups in
51 | let map = CppMap(input)
52 | return { timer in
53 | lookups.withUnsafeBufferPointer { buffer in
54 | cpp_map_lookups(map.ptr, buffer.baseAddress, buffer.count)
55 | }
56 | }
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------