Initial import.

Introduce OrderedCollections module
This commit is contained in:
Karoy Lorentey committed 2021-04-05 09:41:00 -07:00
commit a2bcac435f
198 files changed
+38487

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
---
name: 🐛 Bug Report
about: Something isn't working as expected
labels: bug
---
<!--
Thanks for contributing to Swift Collections!
Before you submit your issue, please replace each paragraph
below with the relevant details for your bug, and complete
the steps in the checklist by placing an 'x' in each box:
- [x] I've completed this task
- [ ] This task isn't completed
-->
Replace this paragraph with a short description of the incorrect behavior.
(If this is a regression, please note the last version of the package that exhibited the correct behavior in addition to your current version.)
### Information
- **Package version:** What tag or branch of swift-collections are you using?
- **Platform version:** Please tell us the version number of your operating system.
- **Swift version:** Paste the output of `swift --version` here.
### Checklist
- [ ] If possible, I've reproduced the issue using the `main` branch of this package.
- [ ] I've searched for [existing GitHub issues](https://github.com/apple/swift-collections/issues).
### Steps to Reproduce
Replace this paragraph with an explanation of how to reproduce the incorrect behavior.
Include a simple code example, if possible.
### Expected behavior
Describe what you expect to happen.
### Actual behavior
Describe or copy/paste the behavior you observe.
+16
View File
@@ -0,0 +1,16 @@
---
name: 💡 Feature Request
about: A suggestion for a new feature
labels: enhancement
---
<!--
Thanks for contributing to Swift Collections!
Before you submit your issue, please replace the paragraph
below with information about your proposed feature.
-->
Replace this paragraph with a description of your proposed feature.
Please be sure to describe some concrete use cases for the new feature -- be as specific as possible.
Provide links to existing issues or external references/discussions, if appropriate.
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: ❓ Discussion Forum
url: https://forums.swift.org/c/related-projects/collections/
about: Questions about using Swift Collections? Ask here!
+24
View File
@@ -0,0 +1,24 @@
<!--
Thanks for contributing to Swift Collections!
If this pull request adds new API, please add '?template=new.md'
to the URL to switch to the appropriate template.
Before you submit your request, please replace the paragraph
below with the relevant details, and complete the steps in the
checklist by placing an 'x' in each box:
- [x] I've completed this task
- [ ] This task isn't completed
-->
Replace this paragraph with a description of your changes and rationale. Provide links to an existing issue or external references/discussions, if appropriate.
### Checklist
- [ ] I've read the [Contribution Guidelines](../CONTRIBUTING.md)
- [ ] My contributions are licensed under the [Swift license](https://swift.org/LICENSE.txt).
- [ ] I've followed the coding style of the rest of the project.
- [ ] I've added tests covering all new code paths my change adds to the project (if appropriate).
- [ ] I've added benchmarks covering new functionality (if appropriate).
- [ ] I've verified that my change does not break any existing tests or introduce unexplained benchmark regressions.
- [ ] I've updated the documentation if necessary.
+45
View File
@@ -0,0 +1,45 @@
<!--
Thanks for contributing to Swift Collections!
Before you submit your request, please replace each paragraph
below with the relevant details, and complete the steps in the
checklist by placing an 'x' in each box:
- [x] I've completed this task
- [ ] This task isn't completed
-->
### Description
Replace this paragraph with a description of your changes and rationale.
Provide links to an existing issue or external references/discussions, if appropriate.
### Detailed Design
Include any additional information about the design here. At minimum, describe a synopsis of any public API additions.
```swift
/// The new feature implemented by this pull request.
public struct Example: Collection {
}
```
### Documentation
How has the new feature been documented?
Have the relevant portions of the guides in the Documentation folder been updated in addition to symbol-level documentation?
### Testing
How is the new feature tested?
### Performance
How did you verify the new feature performs as expected?
### Source Impact
What is the impact of this change on existing users of this package? Does it deprecate or remove any existing API?
### Checklist
- [ ] I've read the [Contribution Guidelines](../CONTRIBUTING.md)
- [ ] My contributions are licensed under the [Swift license](https://swift.org/LICENSE.txt).
- [ ] I've followed the coding style of the rest of the project.
- [ ] I've added tests covering all new code paths my change adds to the project (to the extent possible).
- [ ] I've added benchmarks covering new functionality (if appropriate).
- [ ] I've verified that my change does not break any existing tests or introduce unexpected benchmark regressions.
- [ ] I've updated the documentation (if appropriate).
+5
View File
@@ -0,0 +1,5 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -0,0 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1240"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "Collections"
BuildableName = "Collections"
BlueprintName = "Collections"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DequeTests"
BuildableName = "DequeTests"
BlueprintName = "DequeTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedCollectionsTests"
BuildableName = "OrderedCollectionsTests"
BlueprintName = "OrderedCollectionsTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "Collections"
BuildableName = "Collections"
BlueprintName = "Collections"
ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
<InstallAction
buildConfiguration = "Release">
</InstallAction>
</Scheme>
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1240"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DequeModule"
BuildableName = "DequeModule"
BlueprintName = "DequeModule"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DequeTests"
BuildableName = "DequeTests"
BlueprintName = "DequeTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DequeModule"
BuildableName = "DequeModule"
BlueprintName = "DequeModule"
ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
<InstallAction
buildConfiguration = "Release">
</InstallAction>
</Scheme>
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1250"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedCollections"
BuildableName = "OrderedCollections"
BlueprintName = "OrderedCollections"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedCollectionsTests"
BuildableName = "OrderedCollectionsTests"
BlueprintName = "OrderedCollectionsTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedCollections"
BuildableName = "OrderedCollections"
BlueprintName = "OrderedCollections"
ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
<InstallAction
buildConfiguration = "Release">
</InstallAction>
</Scheme>
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1230"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "UniquedModule"
BuildableName = "UniquedModule"
BlueprintName = "UniquedModule"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "UniquedTests"
BuildableName = "UniquedTests"
BlueprintName = "UniquedTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "UniquedModule"
BuildableName = "UniquedModule"
BlueprintName = "UniquedModule"
ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,251 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1250"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "Collections"
BuildableName = "Collections"
BlueprintName = "Collections"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DequeModule"
BuildableName = "DequeModule"
BlueprintName = "DequeModule"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedDictionaryModule"
BuildableName = "OrderedDictionaryModule"
BlueprintName = "OrderedDictionaryModule"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedSetModule"
BuildableName = "OrderedSetModule"
BlueprintName = "OrderedSetModule"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DequeTests"
BuildableName = "DequeTests"
BlueprintName = "DequeTests"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedDictionaryTests"
BuildableName = "OrderedDictionaryTests"
BlueprintName = "OrderedDictionaryTests"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedSetTests"
BuildableName = "OrderedSetTests"
BlueprintName = "OrderedSetTests"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CollectionsTestSupport"
BuildableName = "CollectionsTestSupport"
BlueprintName = "CollectionsTestSupport"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "swift-collections-benchmark"
BuildableName = "swift-collections-benchmark"
BlueprintName = "swift-collections-benchmark"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "Benchmarks"
BuildableName = "Benchmarks"
BlueprintName = "Benchmarks"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CppBenchmarks"
BuildableName = "CppBenchmarks"
BlueprintName = "CppBenchmarks"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DequeTests"
BuildableName = "DequeTests"
BlueprintName = "DequeTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedDictionaryTests"
BuildableName = "OrderedDictionaryTests"
BlueprintName = "OrderedDictionaryTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedSetTests"
BuildableName = "OrderedSetTests"
BlueprintName = "OrderedSetTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "swift-collections-benchmark"
BuildableName = "swift-collections-benchmark"
BlueprintName = "swift-collections-benchmark"
ReferencedContainer = "container:">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "swift-collections-benchmark"
BuildableName = "swift-collections-benchmark"
BlueprintName = "swift-collections-benchmark"
ReferencedContainer = "container:">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
<InstallAction
buildConfiguration = "Release">
</InstallAction>
</Scheme>
@@ -0,0 +1,111 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1250"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "swift-collections-benchmark"
BuildableName = "swift-collections-benchmark"
BlueprintName = "swift-collections-benchmark"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DequeTests"
BuildableName = "DequeTests"
BlueprintName = "DequeTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedDictionaryTests"
BuildableName = "OrderedDictionaryTests"
BlueprintName = "OrderedDictionaryTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "OrderedSetTests"
BuildableName = "OrderedSetTests"
BlueprintName = "OrderedSetTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "swift-collections-benchmark"
BuildableName = "swift-collections-benchmark"
BlueprintName = "swift-collections-benchmark"
ReferencedContainer = "container:">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "swift-collections-benchmark"
BuildableName = "swift-collections-benchmark"
BlueprintName = "swift-collections-benchmark"
ReferencedContainer = "container:">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
<InstallAction
buildConfiguration = "Release">
</InstallAction>
</Scheme>
+276
View File
@@ -0,0 +1,276 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import CollectionsBenchmark
extension Benchmark {
public mutating func addArrayBenchmarks() {
self.addSimple(
title: "Array<Int> init from range",
input: Int.self
) { size in
blackHole(Array(0 ..< size))
}
self.addSimple(
title: "Array<Int> init from unsafe buffer",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
blackHole(Array(buffer))
}
}
self.addSimple(
title: "Array<Int> sequential iteration",
input: [Int].self
) { input in
for i in input {
blackHole(i)
}
}
self.addSimple(
title: "Array<Int> subscript get, random offsets",
input: ([Int], [Int]).self
) { input, lookups in
for i in lookups {
blackHole(input[i])
}
}
self.addSimple(
title: "Array<Int> successful contains",
input: ([Int], [Int]).self
) { input, lookups in
for i in lookups {
precondition(input.contains(i))
}
}
self.addSimple(
title: "Array<Int> unsuccessful contains",
input: ([Int], [Int]).self
) { input, lookups in
let c = input.count
for i in lookups {
precondition(!input.contains(i + c))
}
}
self.add(
title: "Array<Int> mutate through subscript",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var array = input
array.reserveCapacity(0) // Ensure unique storage
timer.measure {
var v = 0
for i in lookups {
array[i] = v
v += 1
}
}
blackHole(array)
}
}
self.add(
title: "Array<Int> random swaps",
input: [Int].self
) { input in
return { timer in
var array = Array(0 ..< input.count)
timer.measure {
var v = 0
for i in input {
array.swapAt(i, v)
v += 1
}
}
blackHole(array)
}
}
self.add(
title: "Array<Int> partitioning around middle",
input: [Int].self
) { input in
return { timer in
let pivot = input.count / 2
var array = input
array.reserveCapacity(0) // Force unique storage
timer.measure {
let r = array.partition(by: { $0 >= pivot })
precondition(r == pivot)
}
blackHole(array)
}
}
self.add(
title: "Array<Int> sort",
input: [Int].self
) { input in
return { timer in
var array = input
array.reserveCapacity(0) // Force unique storage
timer.measure {
array.sort()
}
precondition(array.elementsEqual(0 ..< input.count))
}
}
self.addSimple(
title: "Array<Int> append",
input: [Int].self
) { input in
var array: [Int] = []
for i in input {
array.append(i)
}
precondition(array.count == input.count)
blackHole(array)
}
self.addSimple(
title: "Array<Int> append, reserving capacity",
input: [Int].self
) { input in
var array: [Int] = []
array.reserveCapacity(input.count)
for i in input {
array.append(i)
}
blackHole(array)
}
self.addSimple(
title: "Array<Int> prepend",
input: [Int].self
) { input in
var array: [Int] = []
for i in input {
array.insert(i, at: 0)
}
blackHole(array)
}
self.addSimple(
title: "Array<Int> prepend, reserving capacity",
input: [Int].self
) { input in
var array: [Int] = []
array.reserveCapacity(input.count)
for i in input {
array.insert(i, at: 0)
}
blackHole(array)
}
self.addSimple(
title: "Array<Int> kalimba",
input: [Int].self
) { input in
blackHole(input.kalimbaOrdered())
}
self.addSimple(
title: "Array<Int> kalimba fast",
input: [Int].self
) { input in
blackHole(input.kalimbaOrdered3())
}
self.add(
title: "Array<Int> random insertions",
input: Insertions.self
) { insertions in
return { timer in
let insertions = insertions.values
var array: [Int] = []
timer.measure {
for i in insertions.indices {
array.insert(i, at: insertions[i])
}
}
blackHole(array)
}
}
self.add(
title: "Array<Int> random insertions, reserving capacity",
input: Insertions.self
) { insertions in
return { timer in
let insertions = insertions.values
var array: [Int] = []
array.reserveCapacity(insertions.count)
timer.measure {
for i in insertions.indices {
array.insert(i, at: insertions[i])
}
}
blackHole(array)
}
}
self.add(
title: "Array<Int> removeLast",
input: Int.self
) { size in
return { timer in
var array = Array(0 ..< size)
timer.measure {
for _ in 0 ..< size {
array.removeLast()
}
}
precondition(array.isEmpty)
blackHole(array)
}
}
self.add(
title: "Array<Int> removeFirst",
input: Int.self
) { size in
return { timer in
var array = Array(0 ..< size)
timer.measure {
for _ in 0 ..< size {
array.removeFirst()
}
}
precondition(array.isEmpty)
blackHole(array)
}
}
self.add(
title: "Array<Int> random removals",
input: Insertions.self
) { insertions in
let removals = Array(insertions.values.reversed())
return { timer in
var array = Array(0 ..< removals.count)
timer.measure {
for i in removals {
array.remove(at: i)
}
}
blackHole(array)
}
}
}
}
+629
View File
@@ -0,0 +1,629 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import CollectionsBenchmark
import CppBenchmarks
internal class CppVector {
var ptr: UnsafeMutableRawPointer?
init(_ input: [Int]) {
self.ptr = input.withUnsafeBufferPointer { buffer in
cpp_vector_create(buffer.baseAddress, buffer.count)
}
}
deinit {
destroy()
}
func destroy() {
if let ptr = ptr {
cpp_vector_destroy(ptr)
}
ptr = nil
}
}
internal class CppDeque {
var ptr: UnsafeMutableRawPointer?
init(_ input: [Int]) {
self.ptr = input.withUnsafeBufferPointer { buffer in
cpp_deque_create(buffer.baseAddress, buffer.count)
}
}
deinit {
destroy()
}
func destroy() {
if let ptr = ptr {
cpp_deque_destroy(ptr)
}
ptr = nil
}
}
internal class CppUnorderedSet {
var ptr: UnsafeMutableRawPointer?
init(_ input: [Int]) {
self.ptr = input.withUnsafeBufferPointer { buffer in
cpp_unordered_set_create(buffer.baseAddress, buffer.count)
}
}
deinit {
destroy()
}
func destroy() {
if let ptr = ptr {
cpp_unordered_set_destroy(ptr)
}
ptr = nil
}
}
internal class CppUnorderedMap {
var ptr: UnsafeMutableRawPointer?
init(_ input: [Int]) {
self.ptr = input.withUnsafeBufferPointer { buffer in
cpp_unordered_map_create(buffer.baseAddress, buffer.count)
}
}
deinit {
destroy()
}
func destroy() {
if let ptr = ptr {
cpp_unordered_map_destroy(ptr)
}
ptr = nil
}
}
extension Benchmark {
public mutating func addCppBenchmarks() {
cpp_set_hash_fn { value in value._rawHashValue(seed: 0) }
self.addSimple(
title: "std::hash<intptr_t>",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_hash(buffer.baseAddress, buffer.count)
}
}
self.addSimple(
title: "custom_intptr_hash (using Swift.Hasher)",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_custom_hash(buffer.baseAddress, buffer.count)
}
}
self.addSimple(
title: "std::vector<intptr_t> push_back from integer range",
input: Int.self
) { count in
cpp_vector_from_int_range(count)
}
self.addSimple(
title: "std::deque<intptr_t> push_back from integer range",
input: Int.self
) { count in
cpp_deque_from_int_range(count)
}
//--------------------------------------------------------------------------
self.addSimple(
title: "std::vector<intptr_t> constructor from buffer",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_vector_from_int_buffer(buffer.baseAddress, buffer.count)
}
}
self.addSimple(
title: "std::deque<intptr_t> constructor from buffer",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_deque_from_int_buffer(buffer.baseAddress, buffer.count)
}
}
//--------------------------------------------------------------------------
self.add(
title: "std::vector<intptr_t> sequential iteration",
input: [Int].self
) { input in
let vector = CppVector(input)
return { timer in
cpp_vector_iterate(vector.ptr)
}
}
self.add(
title: "std::deque<intptr_t> sequential iteration",
input: [Int].self
) { input in
let deque = CppDeque(input)
return { timer in
cpp_deque_iterate(deque.ptr)
}
}
//--------------------------------------------------------------------------
self.add(
title: "std::vector<intptr_t> random-access offset lookups (operator [])",
input: ([Int], [Int]).self
) { input, lookups in
let vector = CppVector(input)
return { timer in
lookups.withUnsafeBufferPointer { buffer in
cpp_vector_lookups_subscript(vector.ptr, buffer.baseAddress, buffer.count)
}
}
}
self.add(
title: "std::deque<intptr_t> random-access offset lookups (operator [])",
input: ([Int], [Int]).self
) { input, lookups in
let vector = CppDeque(input)
return { timer in
lookups.withUnsafeBufferPointer { buffer in
cpp_deque_lookups_subscript(vector.ptr, buffer.baseAddress, buffer.count)
}
}
}
//--------------------------------------------------------------------------
self.add(
title: "std::vector<intptr_t> random-access offset lookups (at)",
input: ([Int], [Int]).self
) { input, lookups in
let deque = CppVector(input)
return { timer in
lookups.withUnsafeBufferPointer { buffer in
cpp_vector_lookups_at(deque.ptr, buffer.baseAddress, buffer.count)
}
}
}
self.add(
title: "std::deque<intptr_t> at, random offsets",
input: ([Int], [Int]).self
) { input, lookups in
let deque = CppDeque(input)
return { timer in
lookups.withUnsafeBufferPointer { buffer in
cpp_deque_lookups_at(deque.ptr, buffer.baseAddress, buffer.count)
}
}
}
//--------------------------------------------------------------------------
self.addSimple(
title: "std::vector<intptr_t> push_back",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_vector_append_integers(buffer.baseAddress, buffer.count, false)
}
}
self.addSimple(
title: "std::vector<intptr_t> push_back, reserving capacity",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_vector_append_integers(buffer.baseAddress, buffer.count, true)
}
}
self.addSimple(
title: "std::deque<intptr_t> push_back",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_deque_append_integers(buffer.baseAddress, buffer.count)
}
}
//--------------------------------------------------------------------------
self.addSimple(
title: "std::vector<intptr_t> insert at front",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_vector_prepend_integers(buffer.baseAddress, buffer.count, false)
}
}
self.addSimple(
title: "std::vector<intptr_t> insert at front, reserving capacity",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_vector_prepend_integers(buffer.baseAddress, buffer.count, true)
}
}
self.addSimple(
title: "std::deque<intptr_t> push_front",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_deque_prepend_integers(buffer.baseAddress, buffer.count)
}
}
//--------------------------------------------------------------------------
self.addSimple(
title: "std::vector<intptr_t> random insertions",
input: Insertions.self
) { insertions in
insertions.values.withUnsafeBufferPointer { buffer in
cpp_vector_random_insertions(buffer.baseAddress, buffer.count, false)
}
}
self.addSimple(
title: "std::deque<intptr_t> random insertions",
input: Insertions.self
) { insertions in
insertions.values.withUnsafeBufferPointer { buffer in
cpp_deque_random_insertions(buffer.baseAddress, buffer.count)
}
}
//--------------------------------------------------------------------------
self.add(
title: "std::vector<intptr_t> pop_back",
input: Int.self
) { size in
return { timer in
let vector = CppVector(Array(0 ..< size))
timer.measure {
cpp_vector_pop_back(vector.ptr)
}
vector.destroy()
}
}
self.add(
title: "std::deque<intptr_t> pop_back",
input: Int.self
) { size in
return { timer in
let deque = CppDeque(Array(0 ..< size))
timer.measure {
cpp_deque_pop_back(deque.ptr)
}
deque.destroy()
}
}
//--------------------------------------------------------------------------
self.add(
title: "std::vector<intptr_t> erase first",
input: Int.self
) { size in
return { timer in
let vector = CppVector(Array(0 ..< size))
timer.measure {
cpp_vector_pop_front(vector.ptr)
}
vector.destroy()
}
}
self.add(
title: "std::deque<intptr_t> pop_front",
input: Int.self
) { size in
return { timer in
let deque = CppDeque(Array(0 ..< size))
timer.measure {
cpp_deque_pop_front(deque.ptr)
}
deque.destroy()
}
}
//--------------------------------------------------------------------------
self.add(
title: "std::vector<intptr_t> random removals",
input: Insertions.self
) { insertions in
let removals = Array(insertions.values.reversed())
return { timer in
let vector = CppVector(Array(0 ..< removals.count))
timer.measure {
removals.withUnsafeBufferPointer { buffer in
cpp_vector_random_removals(vector.ptr, buffer.baseAddress, buffer.count)
}
}
vector.destroy()
}
}
self.add(
title: "std::deque<intptr_t> random removals",
input: Insertions.self
) { insertions in
let removals = Array(insertions.values.reversed())
return { timer in
let deque = CppDeque(Array(0 ..< removals.count))
timer.measure {
removals.withUnsafeBufferPointer { buffer in
cpp_deque_random_removals(deque.ptr, buffer.baseAddress, buffer.count)
}
}
deque.destroy()
}
}
//--------------------------------------------------------------------------
self.add(
title: "std::vector<intptr_t> sort",
input: [Int].self
) { input in
return { timer in
let vector = CppVector(input)
timer.measure {
cpp_vector_sort(vector.ptr)
}
vector.destroy()
}
}
self.add(
title: "std::deque<intptr_t> sort",
input: [Int].self
) { input in
return { timer in
let deque = CppDeque(input)
timer.measure {
cpp_deque_sort(deque.ptr)
}
deque.destroy()
}
}
//--------------------------------------------------------------------------
self.addSimple(
title: "std::unordered_set<intptr_t> insert from integer range",
input: Int.self
) { count in
cpp_unordered_set_from_int_range(count)
}
self.addSimple(
title: "std::unordered_set<intptr_t> constructor from buffer",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_unordered_set_from_int_buffer(buffer.baseAddress, buffer.count)
}
}
self.add(
title: "std::unordered_set<intptr_t> sequential iteration",
input: [Int].self
) { input in
let set = CppUnorderedSet(input)
return { timer in
cpp_unordered_set_iterate(set.ptr)
}
}
self.add(
title: "std::unordered_set<intptr_t> successful find",
input: ([Int], [Int]).self
) { input, lookups in
let set = CppUnorderedSet(input)
return { timer in
lookups.withUnsafeBufferPointer { buffer in
cpp_unordered_set_lookups(set.ptr, buffer.baseAddress, buffer.count, true)
}
}
}
self.add(
title: "std::unordered_set<intptr_t> unsuccessful find",
input: ([Int], [Int]).self
) { input, lookups in
let set = CppUnorderedSet(input)
let lookups = lookups.map { $0 + input.count }
return { timer in
lookups.withUnsafeBufferPointer { buffer in
cpp_unordered_set_lookups(set.ptr, buffer.baseAddress, buffer.count, false)
}
}
}
self.addSimple(
title: "std::unordered_set<intptr_t> insert",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_unordered_set_insert_integers(buffer.baseAddress, buffer.count, false)
}
}
self.addSimple(
title: "std::unordered_set<intptr_t> insert, reserving capacity",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_unordered_set_insert_integers(buffer.baseAddress, buffer.count, true)
}
}
self.add(
title: "std::unordered_set<intptr_t> erase",
input: ([Int], [Int]).self
) { input, removals in
return { timer in
let set = CppUnorderedSet(input)
timer.measure {
removals.withUnsafeBufferPointer { buffer in
cpp_unordered_set_removals(set.ptr, buffer.baseAddress, buffer.count)
}
}
set.destroy()
}
}
//--------------------------------------------------------------------------
self.addSimple(
title: "std::unordered_map<intptr_t, intptr_t> insert from integer range",
input: Int.self
) { count in
cpp_unordered_map_from_int_range(count)
}
self.add(
title: "std::unordered_map<intptr_t, intptr_t> sequential iteration",
input: [Int].self
) { input in
let set = CppUnorderedMap(input)
return { timer in
cpp_unordered_map_iterate(set.ptr)
}
}
self.add(
title: "std::unordered_map<intptr_t, intptr_t> successful find",
input: ([Int], [Int]).self
) { input, lookups in
let map = CppUnorderedMap(input)
return { timer in
lookups.withUnsafeBufferPointer { buffer in
cpp_unordered_map_lookups(map.ptr, buffer.baseAddress, buffer.count, true)
}
}
}
self.add(
title: "std::unordered_map<intptr_t, intptr_t> unsuccessful find",
input: ([Int], [Int]).self
) { input, lookups in
let map = CppUnorderedMap(input)
let lookups = lookups.map { $0 + input.count }
return { timer in
lookups.withUnsafeBufferPointer { buffer in
cpp_unordered_map_lookups(map.ptr, buffer.baseAddress, buffer.count, false)
}
}
}
self.add(
title: "std::unordered_map<intptr_t, intptr_t> subscript, existing key",
input: ([Int], [Int]).self
) { input, lookups in
let map = CppUnorderedMap(input)
return { timer in
lookups.withUnsafeBufferPointer { buffer in
cpp_unordered_map_subscript(map.ptr, buffer.baseAddress, buffer.count)
}
}
}
self.add(
title: "std::unordered_map<intptr_t, intptr_t> subscript, new key",
input: ([Int], [Int]).self
) { input, lookups in
let map = CppUnorderedMap(input)
let lookups = lookups.map { $0 + input.count }
return { timer in
lookups.withUnsafeBufferPointer { buffer in
cpp_unordered_map_subscript(map.ptr, buffer.baseAddress, buffer.count)
}
}
}
self.addSimple(
title: "std::unordered_map<intptr_t, intptr_t> insert",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_unordered_map_insert_integers(buffer.baseAddress, buffer.count, false)
}
}
self.addSimple(
title: "std::unordered_map<intptr_t, intptr_t> insert, reserving capacity",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
cpp_unordered_map_insert_integers(buffer.baseAddress, buffer.count, true)
}
}
self.add(
title: "std::unordered_map<intptr_t, intptr_t> erase existing",
input: ([Int], [Int]).self
) { input, removals in
return { timer in
let map = CppUnorderedMap(input)
timer.measure {
removals.withUnsafeBufferPointer { buffer in
cpp_unordered_map_removals(map.ptr, buffer.baseAddress, buffer.count)
}
}
map.destroy()
}
}
self.add(
title: "std::unordered_map<intptr_t, intptr_t> erase missing",
input: ([Int], [Int]).self
) { input, removals in
return { timer in
let map = CppUnorderedMap(input.map { input.count + $0 })
timer.measure {
removals.withUnsafeBufferPointer { buffer in
cpp_unordered_map_removals(map.ptr, buffer.baseAddress, buffer.count)
}
}
map.destroy()
}
}
}
}
+460
View File
@@ -0,0 +1,460 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import CollectionsBenchmark
@_spi(Testing) import DequeModule
extension Deque {
@inline(__always)
internal init(discontiguous contents: [Element]) {
self.init(_capacity: contents.count,
startSlot: contents.count / 4,
contents: contents)
}
}
extension Benchmark {
public mutating func addDequeBenchmarks() {
self.addSimple(
title: "Deque<Int> init from range",
input: Int.self
) { size in
blackHole(Deque(0 ..< size))
}
self.addSimple(
title: "Deque<Int> init from unsafe buffer",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
blackHole(Deque(buffer))
}
}
self.add(
title: "Deque<Int> sequential iteration (contiguous)",
input: [Int].self
) { input in
let deque = Deque(input)
return { timer in
for i in deque {
blackHole(i)
}
}
}
self.add(
title: "Deque<Int> sequential iteration (discontiguous)",
input: [Int].self
) { input in
let deque = Deque(discontiguous: input)
return { timer in
for i in deque {
blackHole(i)
}
}
}
self.add(
title: "Deque<Int> subscript get, random offsets (contiguous)",
input: ([Int], [Int]).self
) { input, lookups in
let deque = Deque(input)
return { timer in
for i in lookups {
blackHole(deque[i])
}
}
}
self.add(
title: "Deque<Int> subscript get, random offsets (discontiguous)",
input: ([Int], [Int]).self
) { input, lookups in
let deque = Deque(discontiguous: input)
return { timer in
for i in lookups {
blackHole(deque[i])
}
}
}
self.add(
title: "Deque<Int> successful contains (contiguous)",
input: ([Int], [Int]).self
) { input, lookups in
let deque = Deque(input)
return { timer in
for i in lookups {
precondition(deque.contains(i))
}
}
}
self.add(
title: "Deque<Int> successful contains (discontiguous)",
input: ([Int], [Int]).self
) { input, lookups in
let deque = Deque(discontiguous: input)
return { timer in
for i in lookups {
precondition(deque.contains(i))
}
}
}
self.add(
title: "Deque<Int> unsuccessful contains (contiguous)",
input: ([Int], [Int]).self
) { input, lookups in
let deque = Deque(input)
return { timer in
let c = input.count
for i in lookups {
precondition(!deque.contains(i + c))
}
}
}
self.add(
title: "Deque<Int> unsuccessful contains (discontiguous)",
input: ([Int], [Int]).self
) { input, lookups in
let deque = Deque(discontiguous: input)
return { timer in
let c = input.count
for i in lookups {
precondition(!deque.contains(i + c))
}
}
}
self.add(
title: "Deque<Int> mutate through subscript (contiguous)",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var deque = Deque(input)
timer.measure {
var v = 0
for i in lookups {
deque[i] = v
v += 1
}
}
blackHole(deque)
}
}
self.add(
title: "Deque<Int> mutate through subscript (discontiguous)",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var deque = Deque(discontiguous: input)
timer.measure {
var v = 0
for i in lookups {
deque[i] = v
v += 1
}
}
blackHole(deque)
}
}
self.add(
title: "Deque<Int> random swaps (contiguous)",
input: [Int].self
) { input in
return { timer in
var deque = Deque(0 ..< input.count)
timer.measure {
var v = 0
for i in input {
deque.swapAt(i, v)
v += 1
}
}
blackHole(deque)
}
}
self.add(
title: "Deque<Int> random swaps (discontiguous)",
input: [Int].self
) { input in
return { timer in
var deque = Deque(discontiguous: input)
timer.measure {
var v = 0
for i in input {
deque.swapAt(i, v)
v += 1
}
}
blackHole(deque)
}
}
self.add(
title: "Deque<Int> partitioning around middle (contiguous)",
input: [Int].self
) { input in
return { timer in
let pivot = input.count / 2
var deque = Deque(input)
timer.measure {
let r = deque.partition(by: { $0 >= pivot })
precondition(r == pivot)
}
blackHole(deque)
}
}
self.add(
title: "Deque<Int> partitioning around middle (discontiguous)",
input: [Int].self
) { input in
return { timer in
let pivot = input.count / 2
var deque = Deque(discontiguous: input)
timer.measure {
let r = deque.partition(by: { $0 >= pivot })
precondition(r == pivot)
}
blackHole(deque)
}
}
self.add(
title: "Deque<Int> sort (contiguous)",
input: [Int].self
) { input in
return { timer in
var deque = Deque(input)
timer.measure {
deque.sort()
}
precondition(deque.elementsEqual(0 ..< input.count))
}
}
self.add(
title: "Deque<Int> sort (discontiguous)",
input: [Int].self
) { input in
return { timer in
var deque = Deque(discontiguous: input)
timer.measure {
deque.sort()
}
precondition(deque.elementsEqual(0 ..< input.count))
}
}
self.addSimple(
title: "Deque<Int> append from range",
input: Int.self
) { count in
var deque: Deque<Int> = []
for i in 0 ..< count {
deque.append(i)
}
precondition(deque.count == count)
blackHole(deque)
}
self.addSimple(
title: "Deque<Int> append",
input: [Int].self
) { input in
var deque: Deque<Int> = []
for i in input {
deque.append(i)
}
precondition(deque.count == input.count)
blackHole(deque)
}
self.addSimple(
title: "Deque<Int> append, reserving capacity",
input: [Int].self
) { input in
var deque: Deque<Int> = []
deque.reserveCapacity(input.count)
for i in input {
deque.append(i)
}
blackHole(deque)
}
self.addSimple(
title: "Deque<Int> prepend",
input: [Int].self
) { input in
var deque: Deque<Int> = []
for i in input {
deque.prepend(i)
}
blackHole(deque)
}
self.addSimple(
title: "Deque<Int> prepend, reserving capacity",
input: [Int].self
) { input in
var deque: Deque<Int> = []
deque.reserveCapacity(input.count)
for i in input {
deque.prepend(i)
}
blackHole(deque)
}
self.addSimple(
title: "Deque<Int> kalimba",
input: [Int].self
) { input in
blackHole(input.kalimbaOrdered2())
}
self.add(
title: "Deque<Int> random insertions",
input: Insertions.self
) { insertions in
return { timer in
let insertions = insertions.values
var deque: Deque<Int> = []
timer.measure {
for i in insertions.indices {
deque.insert(i, at: insertions[i])
}
}
blackHole(deque)
}
}
self.add(
title: "Deque<Int> random insertions, reserving capacity",
input: Insertions.self
) { insertions in
return { timer in
let insertions = insertions.values
var deque: Deque<Int> = []
deque.reserveCapacity(insertions.count)
timer.measure {
for i in insertions.indices {
deque.insert(i, at: insertions[i])
}
}
blackHole(deque)
}
}
self.add(
title: "Deque<Int> removeLast (contiguous)",
input: Int.self
) { size in
return { timer in
var deque = Deque(0 ..< size)
timer.measure {
for _ in 0 ..< size {
deque.removeLast()
}
}
precondition(deque.isEmpty)
blackHole(deque)
}
}
self.add(
title: "Deque<Int> removeLast (discontiguous)",
input: Int.self
) { size in
return { timer in
var deque = Deque(discontiguous: Array(0 ..< size))
timer.measure {
for _ in 0 ..< size {
deque.removeLast()
}
}
precondition(deque.isEmpty)
blackHole(deque)
}
}
self.add(
title: "Deque<Int> removeFirst (contiguous)",
input: Int.self
) { size in
return { timer in
var deque = Deque(0 ..< size)
timer.measure {
for _ in 0 ..< size {
deque.removeFirst()
}
}
precondition(deque.isEmpty)
blackHole(deque)
}
}
self.add(
title: "Deque<Int> removeFirst (discontiguous)",
input: Int.self
) { size in
return { timer in
var deque = Deque(discontiguous: Array(0 ..< size))
timer.measure {
for _ in 0 ..< size {
deque.removeFirst()
}
}
precondition(deque.isEmpty)
blackHole(deque)
}
}
self.add(
title: "Deque<Int> random removals (contiguous)",
input: Insertions.self
) { insertions in
let removals = Array(insertions.values.reversed())
return { timer in
var deque = Deque(0 ..< removals.count)
timer.measure {
for i in removals {
deque.remove(at: i)
}
}
blackHole(deque)
}
}
self.add(
title: "Deque<Int> random removals (discontiguous)",
input: Insertions.self
) { insertions in
let removals = Array(insertions.values.reversed())
return { timer in
let size = removals.count
var deque = Deque(discontiguous: Array(0 ..< size))
timer.measure {
for i in removals {
deque.remove(at: i)
}
}
blackHole(deque)
}
}
}
}
@@ -0,0 +1,342 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import CollectionsBenchmark
extension Benchmark {
public mutating func addDictionaryBenchmarks() {
self.add(
title: "Dictionary<Int, Int> init(uniqueKeysWithValues:)",
input: [Int].self
) { input in
let keysAndValues = input.map { ($0, 2 * $0) }
return { timer in
blackHole(Dictionary(uniqueKeysWithValues: keysAndValues))
}
}
self.add(
title: "Dictionary<Int, Int> sequential iteration",
input: [Int].self
) { input in
let d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
return { timer in
for item in d {
blackHole(item)
}
}
}
self.add(
title: "Dictionary<Int, Int>.Keys sequential iteration",
input: [Int].self
) { input in
let d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
return { timer in
for item in d.keys {
blackHole(item)
}
}
}
self.add(
title: "Dictionary<Int, Int>.Values sequential iteration",
input: [Int].self
) { input in
let d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
return { timer in
for item in d.values {
blackHole(item)
}
}
}
self.add(
title: "Dictionary<Int, Int> subscript, successful lookups",
input: ([Int], [Int]).self
) { input, lookups in
let d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
return { timer in
for i in lookups {
precondition(d[i] == 2 * i)
}
}
}
self.add(
title: "Dictionary<Int, Int> subscript, unsuccessful lookups",
input: ([Int], [Int]).self
) { input, lookups in
let d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
let c = input.count
return { timer in
for i in lookups {
precondition(d[i + c] == nil)
}
}
}
self.add(
title: "Dictionary<Int, Int> subscript, noop setter",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
let c = input.count
timer.measure {
for i in lookups {
d[i + c] = nil
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.add(
title: "Dictionary<Int, Int> subscript, set existing",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
d[i] = 0
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.add(
title: "Dictionary<Int, Int> subscript, _modify",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
d[i]! *= 2
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.addSimple(
title: "Dictionary<Int, Int> subscript, insert",
input: [Int].self
) { input in
var d: [Int: Int] = [:]
for i in input {
d[i] = 2 * i
}
precondition(d.count == input.count)
blackHole(d)
}
self.addSimple(
title: "Dictionary<Int, Int> subscript, insert, reserving capacity",
input: [Int].self
) { input in
var d: [Int: Int] = [:]
d.reserveCapacity(input.count)
for i in input {
d[i] = 2 * i
}
precondition(d.count == input.count)
blackHole(d)
}
self.add(
title: "Dictionary<Int, Int> subscript, remove existing",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
d[i] = nil
}
}
precondition(d.isEmpty)
blackHole(d)
}
}
self.add(
title: "Dictionary<Int, Int> subscript, remove missing",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
let c = input.count
timer.measure {
for i in lookups {
d[i + c] = nil
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.add(
title: "Dictionary<Int, Int> defaulted subscript, successful lookups",
input: ([Int], [Int]).self
) { input, lookups in
let d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
return { timer in
for i in lookups {
precondition(d[i, default: -1] != -1)
}
}
}
self.add(
title: "Dictionary<Int, Int> defaulted subscript, unsuccessful lookups",
input: ([Int], [Int]).self
) { input, lookups in
let d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
return { timer in
let c = d.count
for i in lookups {
precondition(d[i + c, default: -1] == -1)
}
}
}
self.add(
title: "Dictionary<Int, Int> defaulted subscript, _modify existing",
input: [Int].self
) { input in
return { timer in
var d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
timer.measure {
for i in input {
d[i, default: -1] *= 2
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.add(
title: "Dictionary<Int, Int> defaulted subscript, _modify missing",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
let c = input.count
timer.measure {
for i in lookups {
d[c + i, default: -1] *= 2
}
}
precondition(d.count == 2 * input.count)
blackHole(d)
}
}
self.add(
title: "Dictionary<Int, Int> successful index(forKey:)",
input: ([Int], [Int]).self
) { input, lookups in
let d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
return { timer in
for i in lookups {
precondition(d.index(forKey: i) != nil)
}
}
}
self.add(
title: "Dictionary<Int, Int> unsuccessful index(forKey:)",
input: ([Int], [Int]).self
) { input, lookups in
let d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
return { timer in
for i in lookups {
precondition(d.index(forKey: lookups.count + i) == nil)
}
}
}
self.add(
title: "Dictionary<Int, Int> updateValue(_:forKey:), existing",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
d.updateValue(0, forKey: i)
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.add(
title: "Dictionary<Int, Int> updateValue(_:forKey:), insert",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
d.updateValue(0, forKey: input.count + i)
}
}
precondition(d.count == 2 * input.count)
blackHole(d)
}
}
self.add(
title: "Dictionary<Int, Int> random removals (existing keys)",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = Dictionary(uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
precondition(d.removeValue(forKey: i) != nil)
}
}
precondition(d.count == 0)
blackHole(d)
}
}
self.add(
title: "Dictionary<Int, Int> random removals (missing keys)",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
let c = input.count
var d = Dictionary(uniqueKeysWithValues: input.lazy.map { (c + $0, 2 * $0) })
timer.measure {
for i in lookups {
precondition(d.removeValue(forKey: i) == nil)
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
}
}
+64
View File
@@ -0,0 +1,64 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import DequeModule
extension Sequence {
func kalimbaOrdered() -> [Element] {
var kalimba: [Element] = []
kalimba.reserveCapacity(underestimatedCount)
var insertAtStart = false
for element in self {
if insertAtStart {
kalimba.insert(element, at: 0)
} else {
kalimba.append(element)
}
insertAtStart.toggle()
}
return kalimba
}
func kalimbaOrdered2() -> Deque<Element> {
var kalimba: Deque<Element> = []
kalimba.reserveCapacity(underestimatedCount)
var insertAtStart = false
for element in self {
if insertAtStart {
kalimba.prepend(element)
} else {
kalimba.append(element)
}
insertAtStart.toggle()
}
return kalimba
}
func kalimbaOrdered3() -> [Element] {
var odds: [Element] = []
var evens: [Element] = []
odds.reserveCapacity(underestimatedCount)
evens.reserveCapacity(underestimatedCount / 2)
var insertAtStart = false
for element in self {
if insertAtStart {
odds.append(element)
} else {
evens.append(element)
}
insertAtStart.toggle()
}
odds.reverse()
odds.append(contentsOf: evens)
return odds
}
}
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import Foundation
import CollectionsBenchmark
extension Benchmark {
public func loadReferenceLibrary() throws -> ChartLibrary {
let url = Bundle.module.url(forResource: "Library", withExtension: "json")!
return try ChartLibrary.load(from: url)
}
}
@@ -0,0 +1,486 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import CollectionsBenchmark
import OrderedCollections
extension Benchmark {
public mutating func addOrderedDictionaryBenchmarks() {
self.add(
title: "OrderedDictionary<Int, Int> init(uniqueKeysWithValues:)",
input: [Int].self
) { input in
let keysAndValues = input.map { ($0, 2 * $0) }
return { timer in
blackHole(OrderedDictionary(uniqueKeysWithValues: keysAndValues))
}
}
self.add(
title: "OrderedDictionary<Int, Int> init(uncheckedUniqueKeysWithValues:)",
input: [Int].self
) { input in
let keysAndValues = input.map { ($0, 2 * $0) }
return { timer in
blackHole(
OrderedDictionary(uncheckedUniqueKeysWithValues: keysAndValues))
}
}
self.add(
title: "OrderedDictionary<Int, Int> init(uncheckedUniqueKeys:values:)",
input: [Int].self
) { input in
let values = input.map { 2 * $0 }
return { timer in
blackHole(
OrderedDictionary(uncheckedUniqueKeys: input, values: values))
}
}
self.add(
title: "OrderedDictionary<Int, Int> sequential iteration",
input: [Int].self
) { input in
let d = OrderedDictionary(
uncheckedUniqueKeys: input, values: input.map { 2 * $0 })
return { timer in
for item in d {
blackHole(item)
}
}
}
self.add(
title: "OrderedDictionary<Int, Int>.Keys sequential iteration",
input: [Int].self
) { input in
let d = OrderedDictionary(
uncheckedUniqueKeys: input, values: input.map { 2 * $0 })
return { timer in
for item in d.keys {
blackHole(item)
}
}
}
self.add(
title: "OrderedDictionary<Int, Int>.Values sequential iteration",
input: [Int].self
) { input in
let d = OrderedDictionary(
uncheckedUniqueKeys: input, values: input.map { 2 * $0 })
return { timer in
for item in d.values {
blackHole(item)
}
}
}
self.add(
title: "OrderedDictionary<Int, Int> subscript, successful lookups",
input: ([Int], [Int]).self
) { input, lookups in
let d = OrderedDictionary(
uncheckedUniqueKeys: input, values: input.map { 2 * $0 })
return { timer in
for i in lookups {
precondition(d[i] == 2 * i)
}
}
}
self.add(
title: "OrderedDictionary<Int, Int> subscript, unsuccessful lookups",
input: ([Int], [Int]).self
) { input, lookups in
let d = OrderedDictionary(
uncheckedUniqueKeys: input, values: input.map { 2 * $0 })
let c = input.count
return { timer in
for i in lookups {
precondition(d[i + c] == nil)
}
}
}
self.add(
title: "OrderedDictionary<Int, Int> subscript, noop setter",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
let c = input.count
timer.measure {
for i in lookups {
d[i + c] = nil
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> subscript, set existing",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
d[i] = 0
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> subscript, _modify",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
d[i]! *= 2
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.addSimple(
title: "OrderedDictionary<Int, Int> subscript, append",
input: [Int].self
) { input in
var d: OrderedDictionary<Int, Int> = [:]
for i in input {
d[i] = 2 * i
}
precondition(d.count == input.count)
blackHole(d)
}
self.addSimple(
title: "OrderedDictionary<Int, Int> subscript, append, reserving capacity",
input: [Int].self
) { input in
var d: OrderedDictionary<Int, Int> = [:]
d.reserveCapacity(input.count)
for i in input {
d[i] = 2 * i
}
precondition(d.count == input.count)
blackHole(d)
}
self.add(
title: "OrderedDictionary<Int, Int> subscript, remove existing",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
d[i] = nil
}
}
precondition(d.isEmpty)
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> subscript, remove missing",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
let c = input.count
timer.measure {
for i in lookups {
d[i + c] = nil
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> defaulted subscript, successful lookups",
input: ([Int], [Int]).self
) { input, lookups in
let d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
return { timer in
for i in lookups {
precondition(d[i, default: -1] != -1)
}
}
}
self.add(
title: "OrderedDictionary<Int, Int> defaulted subscript, unsuccessful lookups",
input: ([Int], [Int]).self
) { input, lookups in
let d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
return { timer in
let c = d.count
for i in lookups {
precondition(d[i + c, default: -1] == -1)
}
}
}
self.add(
title: "OrderedDictionary<Int, Int> defaulted subscript, _modify existing",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
d[i, default: -1] *= 2
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> defaulted subscript, _modify missing",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
let c = input.count
timer.measure {
for i in lookups {
d[c + i, default: -1] *= 2
}
}
precondition(d.count == 2 * input.count)
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> successful index(forKey:)",
input: ([Int], [Int]).self
) { input, lookups in
let d = OrderedDictionary(
uncheckedUniqueKeys: input,
values: input.map { 2 * $0 })
return { timer in
for i in lookups {
precondition(d.index(forKey: i) != nil)
}
}
}
self.add(
title: "OrderedDictionary<Int, Int> unsuccessful index(forKey:)",
input: ([Int], [Int]).self
) { input, lookups in
let d = OrderedDictionary(
uncheckedUniqueKeys: input,
values: input.map { 2 * $0 })
return { timer in
for i in lookups {
precondition(d.index(forKey: lookups.count + i) == nil)
}
}
}
self.add(
title: "OrderedDictionary<Int, Int> updateValue(_:forKey:), existing",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
d.updateValue(0, forKey: i)
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> updateValue(_:forKey:), append",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
d.updateValue(0, forKey: input.count + i)
}
}
precondition(d.count == 2 * input.count)
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> random swaps",
input: [Int].self
) { input in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
timer.measure {
var v = 0
for i in input {
d.swapAt(i, v)
v += 1
}
}
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> partitioning around middle",
input: [Int].self
) { input in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
let pivot = input.count / 2
timer.measure {
let r = d.partition(by: { $0.key >= pivot })
precondition(r == pivot)
}
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> sort",
input: [Int].self
) { input in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
timer.measure {
d.sort()
}
precondition(d.keys.elementsEqual(0 ..< input.count))
precondition(d.values.elementsEqual((0 ..< input.count).lazy.map { 2 * $0 }))
}
}
self.add(
title: "OrderedDictionary<Int, Int> removeLast",
input: Int.self
) { size in
return { timer in
var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size,
values: size ..< 2 * size)
timer.measure {
for _ in 0 ..< size {
d.removeLast()
}
}
precondition(d.isEmpty)
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> removeFirst",
input: Int.self
) { size in
return { timer in
var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size,
values: size ..< 2 * size)
timer.measure {
for _ in 0 ..< size {
d.removeFirst()
}
}
precondition(d.isEmpty)
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> random removals (offset-based)",
input: Insertions.self
) { insertions in
return { timer in
let insertions = insertions.values
var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< insertions.count,
values: insertions.count ..< 2 * insertions.count)
timer.measure {
for i in stride(from: insertions.count, to: 0, by: -1) {
d.remove(at: insertions[i - 1])
}
}
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> random removals (existing keys)",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { ($0, 2 * $0) })
timer.measure {
for i in lookups {
precondition(d.removeValue(forKey: i) != nil)
}
}
precondition(d.count == 0)
blackHole(d)
}
}
self.add(
title: "OrderedDictionary<Int, Int> random removals (missing keys)",
input: ([Int], [Int]).self
) { input, lookups in
return { timer in
let c = input.count
var d = OrderedDictionary(
uncheckedUniqueKeysWithValues: input.map { (c + $0, 2 * $0) })
timer.measure {
for i in lookups {
precondition(d.removeValue(forKey: i) == nil)
}
}
precondition(d.count == input.count)
blackHole(d)
}
}
}
}
@@ -0,0 +1,514 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import CollectionsBenchmark
import OrderedCollections
extension Benchmark {
public mutating func addOrderedSetBenchmarks() {
self.addSimple(
title: "OrderedSet<Int> init from range",
input: Int.self
) { size in
blackHole(OrderedSet(0 ..< size))
}
self.addSimple(
title: "OrderedSet<Int> init from unsafe buffer",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
blackHole(OrderedSet(buffer))
}
}
self.addSimple(
title: "OrderedSet<Int> init(uncheckedUniqueElements:) from range",
input: Int.self
) { size in
blackHole(OrderedSet(0 ..< size))
}
self.add(
title: "OrderedSet<Int> random-access offset lookups",
input: ([Int], [Int]).self
) { input, lookups in
let set = OrderedSet(input)
return { timer in
for i in lookups {
blackHole(set[i])
}
}
}
self.add(
title: "OrderedSet<Int> sequential iteration",
input: [Int].self
) { input in
let set = OrderedSet(input)
return { timer in
for i in set {
blackHole(i)
}
}
}
self.add(
title: "OrderedSet<Int> successful contains",
input: ([Int], [Int]).self
) { input, lookups in
let set = OrderedSet(input)
return { timer in
for i in lookups {
precondition(set.contains(i))
}
}
}
self.add(
title: "OrderedSet<Int> unsuccessful contains",
input: ([Int], [Int]).self
) { input, lookups in
let set = OrderedSet(input)
let lookups = lookups.map { $0 + input.count }
return { timer in
for i in lookups {
precondition(!set.contains(i))
}
}
}
self.add(
title: "OrderedSet<Int> random swaps",
input: [Int].self
) { input in
return { timer in
var set = OrderedSet(0 ..< input.count)
timer.measure {
for i in input.indices {
set.swapAt(i, input[i])
}
}
blackHole(set)
}
}
self.add(
title: "OrderedSet<Int> partitioning around middle",
input: [Int].self
) { input in
return { timer in
let pivot = input.count / 2
var set = OrderedSet(input)
timer.measure {
let r = set.partition(by: { $0 >= pivot })
precondition(r == pivot)
}
blackHole(set)
}
}
self.add(
title: "OrderedSet<Int> sort",
input: [Int].self
) { input in
return { timer in
var set = OrderedSet(input)
timer.measure {
set.sort()
}
precondition(set.elementsEqual(0 ..< input.count))
}
}
self.addSimple(
title: "OrderedSet<Int> append",
input: [Int].self
) { input in
var set: OrderedSet<Int> = []
for i in input {
set.append(i)
}
precondition(set.count == input.count)
blackHole(set)
}
self.addSimple(
title: "OrderedSet<Int> append, reserving capacity",
input: [Int].self
) { input in
var set: OrderedSet<Int> = []
set.reserveCapacity(input.count)
for i in input {
set.append(i)
}
precondition(set.count == input.count)
blackHole(set)
}
self.addSimple(
title: "OrderedSet<Int> prepend",
input: [Int].self
) { input in
var set: OrderedSet<Int> = []
for i in input {
_ = set.insert(i, at: 0)
}
blackHole(set)
}
self.addSimple(
title: "OrderedSet<Int> prepend, reserving capacity",
input: [Int].self
) { input in
var set: OrderedSet<Int> = []
set.reserveCapacity(input.count)
for i in input {
_ = set.insert(i, at: 0)
}
blackHole(set)
}
self.add(
title: "OrderedSet<Int> random insertions, reserving capacity",
input: Insertions.self
) { insertions in
return { timer in
let insertions = insertions.values
var set: OrderedSet<Int> = []
set.reserveCapacity(insertions.count)
timer.measure {
for i in insertions.indices {
_ = set.insert(i, at: insertions[i])
}
}
blackHole(set)
}
}
self.add(
title: "OrderedSet<Int> remove",
input: ([Int], [Int]).self
) { input, removals in
return { timer in
var set = OrderedSet(input)
timer.measure {
for i in removals {
set.remove(i)
}
}
precondition(set.isEmpty)
blackHole(set)
}
}
self.add(
title: "OrderedSet<Int> removeLast",
input: Int.self
) { size in
return { timer in
var set = OrderedSet(0 ..< size)
timer.measure {
for _ in 0 ..< size {
set.removeLast()
}
}
precondition(set.isEmpty)
blackHole(set)
}
}
self.add(
title: "OrderedSet<Int> removeFirst",
input: Int.self
) { size in
return { timer in
var set = OrderedSet(0 ..< size)
timer.measure {
for _ in 0 ..< size {
set.removeFirst()
}
}
precondition(set.isEmpty)
blackHole(set)
}
}
let overlaps: [(String, (Int) -> Int)] = [
("0%", { c in c }),
("25%", { c in 3 * c / 4 }),
("50%", { c in c / 2 }),
("75%", { c in c / 4 }),
("100%", { c in 0 }),
]
// SetAlgebra operations with Self
do {
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> union with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = OrderedSet(input)
let b = OrderedSet(start ..< start + input.count)
return { timer in
blackHole(a.union(b))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> intersection with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = OrderedSet(input)
let b = OrderedSet(start ..< start + input.count)
return { timer in
blackHole(a.intersection(b))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> symmetricDifference with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = OrderedSet(input)
let b = OrderedSet(start ..< start + input.count)
return { timer in
blackHole(a.symmetricDifference(b))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> subtracting Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = OrderedSet(input)
let b = OrderedSet(start ..< start + input.count)
return { timer in
blackHole(a.subtracting(b))
}
}
}
}
// SetAlgebra operations with Array
do {
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> union with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = OrderedSet(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.union(b))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> intersection with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = OrderedSet(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.intersection(b))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> symmetricDifference with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = OrderedSet(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.symmetricDifference(b))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> subtracting Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = OrderedSet(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.subtracting(b))
}
}
}
}
// SetAlgebra mutations with Self
do {
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> formUnion with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = OrderedSet(start ..< start + input.count)
return { timer in
var a = OrderedSet(input)
timer.measure {
a.formUnion(b)
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> formIntersection with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = OrderedSet(start ..< start + input.count)
return { timer in
var a = OrderedSet(input)
timer.measure {
a.formIntersection(b)
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> formSymmetricDifference with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = OrderedSet(start ..< start + input.count)
return { timer in
var a = OrderedSet(input)
timer.measure {
a.formSymmetricDifference(b)
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> subtract Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = OrderedSet(start ..< start + input.count)
return { timer in
var a = OrderedSet(input)
timer.measure {
a.subtract(b)
}
blackHole(a)
}
}
}
}
// SetAlgebra mutations with Array
do {
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> formUnion with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = OrderedSet(input)
timer.measure {
a.formUnion(b)
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> formIntersection with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = OrderedSet(input)
timer.measure {
a.formIntersection(b)
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> formSymmetricDifference with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = OrderedSet(input)
timer.measure {
a.formSymmetricDifference(b)
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "OrderedSet<Int> subtract Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = OrderedSet(input)
timer.measure {
a.subtract(b)
}
blackHole(a)
}
}
}
}
}
}
+397
View File
@@ -0,0 +1,397 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import CollectionsBenchmark
extension Benchmark {
public mutating func addSetBenchmarks() {
self.addSimple(
title: "Int.hashValue on each value",
input: Int.self
) { size in
for i in 0 ..< size {
blackHole(i.hashValue)
}
}
self.addSimple(
title: "Hasher.combine on a single buffer of integers",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
var hasher = Hasher()
hasher.combine(bytes: UnsafeRawBufferPointer(buffer))
blackHole(hasher.finalize())
}
}
self.addSimple(
title: "Set<Int> init from range",
input: Int.self
) { size in
blackHole(Set(0 ..< size))
}
self.addSimple(
title: "Set<Int> init from unsafe buffer",
input: [Int].self
) { input in
input.withUnsafeBufferPointer { buffer in
blackHole(Set(buffer))
}
}
self.add(
title: "Set<Int> sequential iteration",
input: Int.self
) { size in
let set = Set(0 ..< size)
return { timer in
for i in set {
blackHole(i)
}
}
}
self.add(
title: "Set<Int> successful contains",
input: ([Int], [Int]).self
) { input, lookups in
let set = Set(input)
return { timer in
for i in lookups {
precondition(set.contains(i))
}
}
}
self.add(
title: "Set<Int> unsuccessful contains",
input: ([Int], [Int]).self
) { input, lookups in
let set = Set(input)
let lookups = lookups.map { $0 + input.count }
return { timer in
for i in lookups {
precondition(!set.contains(i))
}
}
}
self.addSimple(
title: "Set<Int> insert",
input: [Int].self
) { input in
var set: Set<Int> = []
for i in input {
set.insert(i)
}
precondition(set.count == input.count)
blackHole(set)
}
self.addSimple(
title: "Set<Int> insert, reserving capacity",
input: [Int].self
) { input in
var set: Set<Int> = []
set.reserveCapacity(input.count)
for i in input {
set.insert(i)
}
precondition(set.count == input.count)
blackHole(set)
}
self.add(
title: "Set<Int> remove",
input: ([Int], [Int]).self
) { input, removals in
return { timer in
var set = Set(input)
for i in removals {
set.remove(i)
}
precondition(set.isEmpty)
blackHole(set)
}
}
let overlaps: [(String, (Int) -> Int)] = [
("0%", { c in c }),
("25%", { c in 3 * c / 4 }),
("50%", { c in c / 2 }),
("75%", { c in c / 4 }),
("100%", { c in 0 }),
]
// SetAlgebra operations with Self
do {
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> union with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = Set(input)
let b = Set(start ..< start + input.count)
return { timer in
blackHole(a.union(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> intersection with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = Set(input)
let b = Set(start ..< start + input.count)
return { timer in
blackHole(a.intersection(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> symmetricDifference with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = Set(input)
let b = Set(start ..< start + input.count)
return { timer in
blackHole(a.symmetricDifference(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> subtracting Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = Set(input)
let b = Set(start ..< start + input.count)
return { timer in
blackHole(a.subtracting(identity(b)))
}
}
}
}
// SetAlgebra operations with Array
do {
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> union with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = Set(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.union(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> intersection with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = Set(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.intersection(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> symmetricDifference with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = Set(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.symmetricDifference(identity(b)))
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> subtracting Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let a = Set(input)
let b = Array(start ..< start + input.count)
return { timer in
blackHole(a.subtracting(identity(b)))
}
}
}
}
// SetAlgebra mutations with Self
do {
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> formUnion with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Set(start ..< start + input.count)
return { timer in
var a = Set(input)
timer.measure {
a.formUnion(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> formIntersection with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Set(start ..< start + input.count)
return { timer in
var a = Set(input)
timer.measure {
a.formIntersection(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> formSymmetricDifference with Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Set(start ..< start + input.count)
return { timer in
var a = Set(input)
timer.measure {
a.formSymmetricDifference(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> subtract Self (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Set(start ..< start + input.count)
return { timer in
var a = Set(input)
timer.measure {
a.subtract(identity(b))
}
blackHole(a)
}
}
}
}
// SetAlgebra mutations with Array
do {
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> formUnion with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = Set(input)
timer.measure {
a.formUnion(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> formIntersection with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = Set(input)
timer.measure {
a.formIntersection(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> formSymmetricDifference with Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = Set(input)
timer.measure {
a.formSymmetricDifference(identity(b))
}
blackHole(a)
}
}
}
for (percentage, start) in overlaps {
self.add(
title: "Set<Int> subtract Array (\(percentage) overlap)",
input: [Int].self
) { input in
let start = start(input.count)
let b = Array(start ..< start + input.count)
return { timer in
var a = Set(input)
timer.measure {
a.subtract(identity(b))
}
blackHole(a)
}
}
}
}
}
}
@@ -0,0 +1,50 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#ifndef CPPBENCHMARKS_DEQUE_BENCHMARKS_H
#define CPPBENCHMARKS_DEQUE_BENCHMARKS_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/// Create a std::deque, populating it with data from the supplied buffer.
/// Returns an opaque pointer to the created instance.
extern void *cpp_deque_create(const intptr_t *start, size_t count);
/// Destroys a deque previously returned by `cpp_deque_create`.
extern void cpp_deque_destroy(void *ptr);
extern void cpp_deque_from_int_range(intptr_t count);
extern void cpp_deque_from_int_buffer(const intptr_t *start, size_t count);
extern void cpp_deque_append_integers(const intptr_t *start, size_t count);
extern void cpp_deque_prepend_integers(const intptr_t *start, size_t count);
extern void cpp_deque_random_insertions(const intptr_t *start, size_t count);
extern void cpp_deque_iterate(void *ptr);
extern void cpp_deque_lookups_subscript(void *ptr, const intptr_t *start, size_t count);
extern void cpp_deque_lookups_at(void *ptr, const intptr_t *start, size_t count);
extern void cpp_deque_pop_back(void *ptr);
extern void cpp_deque_pop_front(void *ptr);
extern void cpp_deque_random_removals(void *ptr, const intptr_t *start, size_t count);
extern void cpp_deque_sort(void *ptr);
#ifdef __cplusplus
}
#endif
#endif /* CPPBENCHMARKS_DEQUE_BENCHMARKS_H */
@@ -0,0 +1,33 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#ifndef CPPBENCHMARKS_HASHING_H
#define CPPBENCHMARKS_HASHING_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef size_t (*cpp_hash_fn)(intptr_t);
extern void cpp_set_hash_fn(cpp_hash_fn fn);
// Benchmarks
void cpp_hash(const intptr_t *start, size_t count);
void cpp_custom_hash(const intptr_t *start, size_t count);
#ifdef __cplusplus
}
#endif
#endif /* CPPBENCHMARKS_HASHING_H */
@@ -0,0 +1,44 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#ifndef CPPBENCHMARKS_UNORDERED_MAP_BENCHMARKS_H
#define CPPBENCHMARKS_UNORDERED_MAP_BENCHMARKS_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/// Create a std::unordered_map, populating it with data from the supplied buffer.
/// Returns an opaque pointer to the created instance.
extern void *cpp_unordered_map_create(const intptr_t *start, size_t count);
/// Destroys an unordered map previously returned by `cpp_unordered_map_create`.
extern void cpp_unordered_map_destroy(void *ptr);
extern void cpp_unordered_map_iterate(void *ptr);
extern void cpp_unordered_map_from_int_range(intptr_t count);
extern void cpp_unordered_map_insert_integers(const intptr_t *start, size_t count, bool reserve);
extern void cpp_unordered_map_lookups(void *ptr, const intptr_t *start, size_t count, bool expectMatch);
extern void cpp_unordered_map_subscript(void *ptr, const intptr_t *start, size_t count);
extern void cpp_unordered_map_removals(void *ptr, const intptr_t *start, size_t count);
#ifdef __cplusplus
}
#endif
#endif /* CPPBENCHMARKS_UNORDERED_MAP_BENCHMARKS_H */
@@ -0,0 +1,46 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#ifndef CPPBENCHMARKS_UNORDERED_SET_BENCHMARKS_H
#define CPPBENCHMARKS_UNORDERED_SET_BENCHMARKS_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
void cpp_hash(const intptr_t *start, size_t count);
/// Create a std::unordered_set, populating it with data from the supplied buffer.
/// Returns an opaque pointer to the created instance.
extern void *cpp_unordered_set_create(const intptr_t *start, size_t count);
/// Destroys an unordered set previously returned by `cpp_unordered_set_create`.
extern void cpp_unordered_set_destroy(void *ptr);
extern void cpp_unordered_set_iterate(void *ptr);
extern void cpp_unordered_set_from_int_range(intptr_t count);
extern void cpp_unordered_set_from_int_buffer(const intptr_t *start, size_t count);
extern void cpp_unordered_set_insert_integers(const intptr_t *start, size_t count, bool reserve);
extern void cpp_unordered_set_lookups(void *ptr, const intptr_t *start, size_t count, bool expectMatch);
extern void cpp_unordered_set_removals(void *ptr, const intptr_t *start, size_t count);
#ifdef __cplusplus
}
#endif
#endif /* CPPBENCHMARKS_UNORDERED_SET_BENCHMARKS_H */
@@ -0,0 +1,50 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#ifndef CPPBENCHMARKS_VECTOR_BENCHMARKS_H
#define CPPBENCHMARKS_VECTOR_BENCHMARKS_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/// Create a std::vector, populating it with data from the supplied buffer.
/// Returns an opaque pointer to the created instance.
extern void *cpp_vector_create(const intptr_t *start, size_t count);
/// Destroys a vector previously returned by `cpp_vector_create`.
extern void cpp_vector_destroy(void *ptr);
extern void cpp_vector_from_int_range(intptr_t count);
extern void cpp_vector_from_int_buffer(const intptr_t *start, size_t count);
extern void cpp_vector_append_integers(const intptr_t *start, size_t count, bool reserve);
extern void cpp_vector_prepend_integers(const intptr_t *start, size_t count, bool reserve);
extern void cpp_vector_random_insertions(const intptr_t *start, size_t count, bool reserve);
extern void cpp_vector_iterate(void *ptr);
extern void cpp_vector_lookups_subscript(void *ptr, const intptr_t *start, size_t count);
extern void cpp_vector_lookups_at(void *ptr, const intptr_t *start, size_t count);
extern void cpp_vector_pop_back(void *ptr);
extern void cpp_vector_pop_front(void *ptr);
extern void cpp_vector_random_removals(void *ptr, const intptr_t *start, size_t count);
extern void cpp_vector_sort(void *ptr);
#ifdef __cplusplus
}
#endif
#endif /* CPPBENCHMARKS_VECTOR_BENCHMARKS_H */
@@ -0,0 +1,9 @@
module CppBenchmarks {
header "Hashing.h"
header "VectorBenchmarks.h"
header "DequeBenchmarks.h"
header "UnorderedSetBenchmarks.h"
header "UnorderedMapBenchmarks.h"
export *
}
+31
View File
@@ -0,0 +1,31 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#ifndef CUSTOMHASH_H
#define CUSTOMHASH_H
#include <stdint.h>
#include <functional>
#include "Hashing.h"
extern cpp_hash_fn custom_hash_fn;
struct custom_intptr_hash: public std::unary_function<intptr_t, std::size_t>
{
std::size_t
operator()(intptr_t value) const
{
return static_cast<std::size_t>(custom_hash_fn(value));
}
};
#endif /* CUSTOMHASH_H */
@@ -0,0 +1,140 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#include "DequeBenchmarks.h"
#include <deque>
#include <algorithm>
#include "utils.h"
void *
cpp_deque_create(const intptr_t *start, size_t count)
{
auto deque = new std::deque<intptr_t>(start, start + count);
return deque;
}
void
cpp_deque_destroy(void *ptr)
{
delete static_cast<std::deque<intptr_t> *>(ptr);
}
void
cpp_deque_from_int_range(intptr_t count)
{
auto deque = std::deque<intptr_t>();
for (intptr_t i = 0; i < count; i++) {
deque.push_back(identity(i));
}
black_hole(&deque);
}
void
cpp_deque_from_int_buffer(const intptr_t *start, size_t count)
{
auto deque = std::deque<intptr_t>(start, start + count);
black_hole(&deque);
}
void
cpp_deque_append_integers(const intptr_t *start, size_t count)
{
auto deque = std::deque<intptr_t>();
auto end = start + count;
for (auto p = start; p != end; ++p) {
deque.push_back(*identity(p));
}
black_hole(&deque);
}
void
cpp_deque_prepend_integers(const intptr_t *start, size_t count)
{
auto deque = std::deque<intptr_t>();
auto end = start + count;
for (auto p = start; p != end; ++p) {
deque.push_front(*identity(p));
}
black_hole(&deque);
}
void
cpp_deque_random_insertions(const intptr_t *start, size_t count)
{
auto deque = std::deque<intptr_t>();
for (intptr_t i = 0; i < count; i++) {
deque.insert(deque.cbegin() + start[i], identity(i));
}
black_hole(&deque);
}
void
cpp_deque_iterate(void *ptr)
{
auto deque = static_cast<std::deque<intptr_t> *>(ptr);
for (auto it = deque->cbegin(); it != deque->cend(); ++it) {
black_hole(*it);
}
}
void
cpp_deque_lookups_subscript(void *ptr, const intptr_t *start, size_t count)
{
auto deque = static_cast<std::deque<intptr_t> *>(ptr);
for (auto it = start; it < start + count; ++it) {
black_hole((*deque)[*it]);
}
}
void
cpp_deque_lookups_at(void *ptr, const intptr_t *start, size_t count)
{
auto deque = static_cast<std::deque<intptr_t> *>(ptr);
for (auto it = start; it < start + count; ++it) {
black_hole((*deque).at(*it));
}
}
void
cpp_deque_pop_back(void *ptr)
{
auto deque = static_cast<std::deque<intptr_t> *>(ptr);
auto size = deque->size();
for (int i = 0; i < size; ++i) {
identity(deque)->pop_back();
}
}
void
cpp_deque_pop_front(void *ptr)
{
auto deque = static_cast<std::deque<intptr_t> *>(ptr);
auto size = deque->size();
for (int i = 0; i < size; ++i) {
identity(deque)->pop_front();
}
}
void
cpp_deque_random_removals(void *ptr, const intptr_t *start, size_t count)
{
auto deque = static_cast<std::deque<intptr_t> *>(ptr);
for (auto it = start; it < start + count; ++it) {
identity(deque)->erase(deque->cbegin() + *it);
}
}
void
cpp_deque_sort(void *ptr)
{
auto deque = static_cast<std::deque<intptr_t> *>(ptr);
std::sort(deque->begin(), deque->end());
}
+39
View File
@@ -0,0 +1,39 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#import "Hashing.h"
#import "CustomHash.h"
#import "utils.h"
cpp_hash_fn custom_hash_fn;
void
cpp_set_hash_fn(cpp_hash_fn fn)
{
custom_hash_fn = fn;
}
void
cpp_hash(const intptr_t *start, size_t count)
{
for (auto p = start; p < start + count; ++p) {
black_hole(std::hash<intptr_t>{}(*p));
}
}
void
cpp_custom_hash(const intptr_t *start, size_t count)
{
for (auto p = start; p < start + count; ++p) {
black_hole(custom_intptr_hash{}(*p));
}
}
@@ -0,0 +1,96 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#include "UnorderedMapBenchmarks.h"
#include <unordered_map>
#include <cstdlib>
#include <algorithm>
#include "CustomHash.h"
#include "utils.h"
typedef std::unordered_map<intptr_t, intptr_t, custom_intptr_hash> custom_map;
void *
cpp_unordered_map_create(const intptr_t *start, size_t count)
{
auto map = new custom_map();
for (size_t i = 0; i < count; ++i) {
map->insert({start[i], 2 * start[i]});
}
return map;
}
void
cpp_unordered_map_destroy(void *ptr)
{
delete static_cast<custom_map *>(ptr);
}
void
cpp_unordered_map_from_int_range(intptr_t count)
{
auto map = custom_map();
for (intptr_t i = 0; i < count; i++) {
map.insert({identity(i), 2 * i});
}
black_hole(&map);
}
void
cpp_unordered_map_insert_integers(const intptr_t *start, size_t count, bool reserve)
{
auto map = custom_map();
if (reserve) map.reserve(count);
auto end = start + count;
for (auto p = start; p != end; ++p) {
auto v = *identity(p);
map.insert({ v, 2 * v });
}
black_hole(&map);
}
void
cpp_unordered_map_iterate(void *ptr)
{
auto map = static_cast<custom_map *>(ptr);
for (auto it = map->cbegin(); it != map->cend(); ++it) {
black_hole(it->first);
black_hole(it->second);
}
}
void
cpp_unordered_map_lookups(void *ptr, const intptr_t *start, size_t count, bool expectMatch)
{
auto map = static_cast<custom_map *>(ptr);
for (auto it = start; it < start + count; ++it) {
auto found = map->find(*it) != map->end();
if (found != expectMatch) { abort(); }
}
}
void
cpp_unordered_map_subscript(void *ptr, const intptr_t *start, size_t count)
{
auto map = static_cast<custom_map *>(ptr);
for (auto it = start; it < start + count; ++it) {
black_hole((*map)[*it]);
}
}
void
cpp_unordered_map_removals(void *ptr, const intptr_t *start, size_t count)
{
auto map = static_cast<custom_map *>(ptr);
for (auto it = start; it < start + count; ++it) {
identity(map)->erase(*it);
}
}
@@ -0,0 +1,90 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#include "UnorderedSetBenchmarks.h"
#include <unordered_set>
#include <cstdlib>
#include <functional>
#include <algorithm>
#include "CustomHash.h"
#include "utils.h"
typedef std::unordered_set<intptr_t, custom_intptr_hash> custom_set;
void *
cpp_unordered_set_create(const intptr_t *start, size_t count)
{
auto set = new custom_set(start, start + count);
return set;
}
void
cpp_unordered_set_destroy(void *ptr)
{
delete static_cast<custom_set *>(ptr);
}
void
cpp_unordered_set_from_int_range(intptr_t count)
{
auto set = custom_set();
for (intptr_t i = 0; i < count; i++) {
set.insert(identity(i));
}
black_hole(&set);
}
void
cpp_unordered_set_from_int_buffer(const intptr_t *start, size_t count)
{
auto set = custom_set(start, start + count);
black_hole(&set);
}
void
cpp_unordered_set_insert_integers(const intptr_t *start, size_t count, bool reserve)
{
auto set = custom_set();
if (reserve) set.reserve(count);
auto end = start + count;
for (auto p = start; p != end; ++p) {
set.insert(*identity(p));
}
black_hole(&set);
}
void
cpp_unordered_set_iterate(void *ptr)
{
auto set = static_cast<custom_set *>(ptr);
for (auto it = set->cbegin(); it != set->cend(); ++it) {
black_hole(*it);
}
}
void
cpp_unordered_set_lookups(void *ptr, const intptr_t *start, size_t count, bool expectMatch)
{
auto set = static_cast<custom_set *>(ptr);
for (auto it = start; it < start + count; ++it) {
auto found = set->find(*it) != set->end();
if (found != expectMatch) { abort(); }
}
}
void
cpp_unordered_set_removals(void *ptr, const intptr_t *start, size_t count)
{
auto set = static_cast<custom_set *>(ptr);
for (auto it = start; it < start + count; ++it) {
identity(set)->erase(*it);
}
}
@@ -0,0 +1,143 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#include "VectorBenchmarks.h"
#include <vector>
#include <algorithm>
#include "utils.h"
void *
cpp_vector_create(const intptr_t *start, size_t count)
{
auto vector = new std::vector<intptr_t>(start, start + count);
return vector;
}
void
cpp_vector_destroy(void *ptr)
{
delete static_cast<std::vector<intptr_t> *>(ptr);
}
void
cpp_vector_from_int_range(intptr_t count)
{
auto vector = std::vector<intptr_t>();
for (intptr_t i = 0; i < count; i++) {
vector.push_back(identity(i));
}
black_hole(&vector);
}
void
cpp_vector_from_int_buffer(const intptr_t *start, size_t count)
{
auto vector = std::vector<intptr_t>(start, start + count);
black_hole(&vector);
}
void
cpp_vector_append_integers(const intptr_t *start, size_t count, bool reserve)
{
auto vector = std::vector<intptr_t>();
if (reserve) vector.reserve(count);
auto end = start + count;
for (auto p = start; p != end; ++p) {
vector.push_back(*identity(p));
}
black_hole(&vector);
}
void
cpp_vector_prepend_integers(const intptr_t *start, size_t count, bool reserve)
{
auto vector = std::vector<intptr_t>();
if (reserve) vector.reserve(count);
auto end = start + count;
for (auto p = start; p != end; ++p) {
vector.insert(vector.cbegin(), *identity(p));
}
black_hole(&vector);
}
void
cpp_vector_random_insertions(const intptr_t *start, size_t count, bool reserve)
{
auto vector = std::vector<intptr_t>();
if (reserve) vector.reserve(count);
for (intptr_t i = 0; i < count; i++) {
vector.insert(vector.cbegin() + start[i], identity(i));
}
black_hole(&vector);
}
void
cpp_vector_iterate(void *ptr)
{
auto vector = static_cast<std::vector<intptr_t> *>(ptr);
for (auto it = vector->cbegin(); it != vector->cend(); ++it) {
black_hole(*it);
}
}
void
cpp_vector_lookups_subscript(void *ptr, const intptr_t *start, size_t count)
{
auto vector = static_cast<std::vector<intptr_t> *>(ptr);
for (auto it = start; it < start + count; ++it) {
black_hole((*vector)[*it]);
}
}
void
cpp_vector_lookups_at(void *ptr, const intptr_t *start, size_t count)
{
auto vector = static_cast<std::vector<intptr_t> *>(ptr);
for (auto it = start; it < start + count; ++it) {
black_hole((*vector).at(*it));
}
}
void
cpp_vector_pop_back(void *ptr)
{
auto vector = static_cast<std::vector<intptr_t> *>(ptr);
auto size = vector->size();
for (int i = 0; i < size; ++i) {
identity(vector)->pop_back();
}
}
void
cpp_vector_pop_front(void *ptr)
{
auto vector = static_cast<std::vector<intptr_t> *>(ptr);
auto size = vector->size();
for (int i = 0; i < size; ++i) {
identity(vector)->erase(vector->cbegin());
}
}
void
cpp_vector_random_removals(void *ptr, const intptr_t *start, size_t count)
{
auto vector = static_cast<std::vector<intptr_t> *>(ptr);
for (auto it = start; it < start + count; ++it) {
identity(vector)->erase(vector->cbegin() + *it);
}
}
void
cpp_vector_sort(void *ptr)
{
auto vector = static_cast<std::vector<intptr_t> *>(ptr);
std::sort(vector->begin(), vector->end());
}
+42
View File
@@ -0,0 +1,42 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#include "utils.h"
void
black_hole(intptr_t value)
{
// Do nothing.
}
void
black_hole(void *value)
{
// Do nothing.
}
intptr_t
identity(intptr_t value)
{
return value;
}
void *
_identity(void *value)
{
return value;
}
const void *
_identity(const void *value)
{
return value;
}
+38
View File
@@ -0,0 +1,38 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#ifndef BLACK_HOLE_H
#define BLACK_HOLE_H
#include <stdint.h>
// FIXME: Is putting this in a separate compilation unit enough to make
// sure the function call is always emitted?
extern void black_hole(intptr_t value);
extern void black_hole(void *value);
extern intptr_t identity(intptr_t value);
extern void *_identity(void *value);
extern const void *_identity(const void *value);
template <typename T>
static inline T *identity(T *value)
{
return static_cast<T *>(_identity(value));
}
template <typename T>
static inline const T *identity(const T *value)
{
return static_cast<const T *>(_identity(value));
}
#endif /* BLACK_HOLE_H */
@@ -0,0 +1,26 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import CollectionsBenchmark
import Benchmarks
var benchmark = Benchmark(title: "Collection Benchmarks")
benchmark.addArrayBenchmarks()
benchmark.addSetBenchmarks()
benchmark.addDictionaryBenchmarks()
benchmark.addDequeBenchmarks()
benchmark.addOrderedSetBenchmarks()
benchmark.addOrderedDictionaryBenchmarks()
benchmark.addCppBenchmarks()
benchmark.chartLibrary = try benchmark.loadReferenceLibrary()
benchmark.main()
+19
View File
@@ -0,0 +1,19 @@
# This file is a list of the people responsible for ensuring that patches for a
# particular part of Swift are reviewed, either by themselves or by someone else.
# They are also the gatekeepers for their part of Swift, with the final word on
# what goes in or not.
#
# The list is sorted by surname and formatted to allow easy grepping and
# beautification by scripts. The fields are: name (N), email (E), web-address
# (W), PGP key ID and fingerprint (P), description (D), and snail-mail address
# (S).
# N: Karoy Lorentey
# E: klorentey@apple.com
# D: Everything in swift-collections not covered by someone else
###
# The following lines are used by GitHub to automatically recommend reviewers.
* @lorentey
+38
View File
@@ -0,0 +1,38 @@
# Code of Conduct
To be a truly great community, Swift.org needs to welcome developers from all walks of life, with different backgrounds, and with a wide range of experience. A diverse and friendly community will have more great ideas, more unique perspectives, and produce more great code. We will work diligently to make the Swift community welcoming to everyone.
To give clarity of what is expected of our members, this code of conduct is based on [contributor-covenant.org](http://contributor-covenant.org). This document is used across many open source communities, and we think it articulates our values well.
### Contributor Code of Conduct v1.4
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language (e.g., prefer non-gendered words like “folks” to “guys”, non-ableist words like “soundness check” to “sanity check”, etc.)
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others’ private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
This Code of Conduct applies within all project spaces managed by Swift.org, including (but not limited to) source code repositories, bug trackers, web sites, documentation, and online forums. It also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a member of the [Swift Core Team](https://swift.org/community/#community-structure) or by flagging the behavior for moderation (e.g., in the Forums), whether you are the target of that behavior or not. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. The site of the disputed behavior is usually not an acceptable place to discuss moderation decisions, and moderators may move or remove any such discussion.
Project maintainers are held to a higher standard, and project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership.
If you disagree with a moderation action, you can appeal to the Core Team (or individual Core Team members) privately.
This policy is adapted from the Contributor Code of Conduct [version 1.4](https://www.contributor-covenant.org/version/1/4/code-of-conduct/).
+11
View File
@@ -0,0 +1,11 @@
By submitting a pull request, you represent that you have the right to license
your contribution to Apple and the community, and agree by submitting the patch
that your contributions are licensed under the [Swift
license](https://swift.org/LICENSE.txt).
---
Before submitting the pull request, please make sure you have tested your
changes and that they follow the Swift project [guidelines for contributing
code](https://swift.org/contributing/#contributing-code).
+93
View File
@@ -0,0 +1,93 @@
# Deque
A collection implementing a double-ended queue.
## Declaration
```swift
import DequeModule
@frozen struct Deque<Element>
```
## Overview
`Deque` (pronounced "deck") implements an ordered random-access
collection that supports efficient insertions and removals from both
ends.
```swift
var colors: Deque = ["red", "yellow", "blue"]
```
Deques implement the same indexing semantics as arrays: they use integer
indices, and the first element of a nonempty deque is always at index zero.
Like arrays, deques conform to `RangeReplaceableCollection`,
`MutableCollection` and `RandomAccessCollection`, providing a familiar
interface for manipulating their contents:
```swift
print(colors[1]) // "yellow"
print(colors[3]) // Runtime error: Index out of range
colors.insert("green", at: 1)
// ["red", "green", "yellow", "blue"]
colors.remove(at: 2) // "yellow"
// ["red", "green", "blue"]
```
Like all variable-size collections on the standard library, `Deque`
implements value semantics: each deque has an independent value that
includes the values of its elements. Modifying one deque does not affect any
others:
```swift
var copy = deque
copy[1] = "violet"
print(copy) // ["red", "violet", "blue"]
print(deque) // ["red", "green", "blue"]
```
This is implemented with the copy-on-write optimization. Multiple copies of
a deque share the same underlying storage until you modify one of the
copies. When that happens, the deque being modified replaces its storage
with a uniquely owned copy of itself, which is then modified in place.
`Deque` stores its elements in a circular buffer, which allows efficient
insertions and removals at both ends of the collection; however, this comes
at the cost of potentially discontiguous storage. In contrast, `Array` is
(usually) backed by a contiguous buffer, where new data can be efficiently
appended to the end, but inserting at the front is relatively slow, as
existing elements need to be shifted to make room.
This difference in implementation means that while the interface of a deque
is very similar to an array, the operations have different performance
characteristics. Mutations near the front are expected to be significantly
faster in deques, but arrays may measure slightly faster for general
random-access lookups.
Deques provide a handful of additional operations that make it easier to
insert and remove elements at the front. This includes queue operations such
as `popFirst` and `prepend`, including the ability to directly prepend a
sequence of elements:
```swift
colors.append("green")
colors.prepend("orange")
// colors: ["orange", "red", "blue", "yellow", "green"]
colors.popLast() // "green"
colors.popFirst() // "orange"
// colors: ["red", "blue", "yellow"]
colors.prepend(contentsOf: ["purple", "teal"])
// colors: ["purple", "teal", "red", "blue", "yellow"]
```
Unlike arrays, deques do not currently provide direct unsafe access to their
underlying storage. They also lack a `capacity` property -- the size of the
storage buffer at any given point is an unstable implementation detail that
should not affect application logic. (However, deques do provide a
`reserveCapacity` method.)
+224
View File
@@ -0,0 +1,224 @@
# `OrderedDictionary`
An ordered collection of key-value pairs.
## Declaration
```swift
import OrderedCollections
@frozen struct OrderedDictionary<Key: Hashable, Value>
```
## Overview
Like the standard `Dictionary`, ordered dictionaries use a hash table to
ensure that no two entries have the same keys, and to efficiently look up
values corresponding to specific keys. However, like an `Array` (and
unlike `Dictionary`), ordered dictionaries maintain their elements in a
particular user-specified order, and they support efficient random-access
traversal of their entries.
`OrderedDictionary` is a useful alternative to `Dictionary` when the order
of elements is important, or when you need to be able to efficiently access
elements at various positions within the collection.
You can create an ordered dictionary with any key type that conforms to the
`Hashable` protocol.
```swift
let responses: OrderedDictionary = [
200: "OK",
403: "Access forbidden",
404: "File not found",
500: "Internal server error",
]
```
### Equality of Ordered Dictionaries
Two ordered dictionaries are considered equal if they contain the same
elements, and *in the same order*. This matches the concept of equality of
an `Array`, and it is different from the unordered `Dictionary`.
```swift
let a: OrderedDictionary = [1: "one", 2: "two"]
let b: OrderedDictionary = [2: "two", 1: "one"]
a == b // false
b.swapAt(0, 1) // `b` now has value [1: "one", 2: "two"]
a == b // true
```
(`OrderedDictionary` only conforms to `Equatable` when its `Value` is
equatable.)
### Dictionary Operations
`OrderedDictionary` provides many of the same operations as `Dictionary`.
For example, you can look up and add/remove values using the familiar
key-based subscript, returning an optional value:
```swift
var dictionary: OrderedDictionary<String, Int> = [:]
dictionary["one"] = 1
dictionary["two"] = 2
dictionary["three"] // nil
// dictionary is now ["one": 1, "two": 2]
```
If a new entry is added using the subscript setter, it gets appended to the
end of the dictionary. (So that by default, the dictionary contains its
elements in the order they were originally inserted.)
`OrderedDictionary` also implements the variant of this subscript that takes
a default value. Like with `Dictionary`, this is useful when you want to
perform in-place mutations on values:
```swift
let text = "short string"
var counts: OrderedDictionary<Character, Int> = [:]
for character in text {
counts[character, default: 0] += 1
}
// counts is ["s": 2, "h": 1, "o": 1,
// "r": 2, "t": 2, " ": 1,
// "i": 1, "n": 1, "g": 1]
```
If the `Value` type implements reference semantics, or when you need to
perform a series of individual mutations on the values, the closure-based
`modifyValue(forKey:default:_:)` method provides an easier-to-use
alternative to the defaulted key-based subscript.
```swift
let text = "short string"
var counts: OrderedDictionary<Character, Int> = [:]
for character in text {
counts.modifyValue(forKey: character, default: 0) { value in
value += 1
}
}
// Same result as before
```
(This isn't currently available on the regular `Dictionary`.)
The `Dictionary` type's original `updateValue(_:forKey:)` method is also
available, and so is `index(forKey:)`, grouping/uniquing initializers
(`init(uniqueKeysWithValues:)`, `init(_:uniquingKeysWith:)`,
`init(grouping:by:)`), methods for merging one dictionary with another
(`merge`, `merging`), filtering dictionary entries (`filter(_:)`),
transforming values (`mapValues(_:)`), and a combination of these two
(`compactMapValues(_:)`).
### Sequence and Collection Operations
Ordered dictionaries use integer indices representing offsets from the
beginning of the collection. However, to avoid ambiguity between key-based
and indexing subscripts, `OrderedDictionary` doesn't directly conform to
`Collection`. Instead, it only conforms to `Sequence`, and provides a
random-access collection view over its key-value pairs:
```swift
responses[0] // `nil` (key-based subscript)
responses.elements[0] // `(200, "OK")` (index-based subscript)
```
Because ordered dictionaries need to maintain unique keys, neither
`OrderedDictionary` nor its `elements` view can conform to the full
`MutableCollection` or `RangeReplaceableCollection` protocols. However, they
are able to partially implement requirements: they support mutations
that merely change the order of elements, or just remove a subset of
existing members:
```swift
// Permutation operations from MutableCollection:
func swapAt(_ i: Index, _ j: Index)
func partition(by predicate: (Element) throws -> Bool) -> rethrows Index
func sort() where Element: Comparable
func sort(by predicate: (Element, Element) throws -> Bool) rethrows
func shuffle()
func shuffle<T: RandomNumberGenerator>(using generator: inout T)
// Removal operations from RangeReplaceableCollection:
func removeAll(keepingCapacity: Bool = false)
func remove(at index: Index) -> Element
func removeSubrange(_ bounds: Range<Int>)
func removeLast() -> Element
func removeLast(_ n: Int)
func removeFirst() -> Element
func removeFirst(_ n: Int)
func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows
```
`OrderedDictionary` also implements `reserveCapacity(_)` from
`RangeReplaceableCollection`, to allow for efficient insertion of a known
number of elements. (However, unlike `Array` and `Dictionary`,
`OrderedDictionary` does not provide a `capacity` property.)
### Keys and Values Views
Like the standard `Dictionary`, `OrderedDictionary` provides `keys` and
`values` properties that provide lightweight views into the corresponding
parts of the dictionary.
The `keys` collection is of type `OrderedSet<Key>`, containing all the keys
in the original dictionary.
```swift
let d: OrderedDictionary = [2: "two", 1: "one", 0: "zero"]
d.keys // [2, 1, 0] as OrderedSet<Int>
```
The `keys` property is read-only, so you cannot mutate the dictionary
through it. However, it returns an ordinary ordered set value, which can be
copied out and then mutated if desired. (Such mutations won't affect the
original dictionary value.)
The `values` collection is a mutable random-access collection of the values
in the dictionary:
```swift
d.values // "two", "one", "zero"
d.values[2] = "nada"
// `d` is now [2: "two", 1: "one", 0: "nada"]
d.values.sort()
// `d` is now [2: "nada", 1: "one", 0: "two"]
```
Both views store their contents in regular `Array` values, accessible
through their `elements` property.
## Performance
Like the standard `Dictionary` type, the performance of hashing operations
in `OrderedDictionary` is highly sensitive to the quality of hashing
implemented by the `Key` type. Failing to correctly implement hashing can
easily lead to unacceptable performance, with the severity of the effect
increasing with the size of the hash table.
In particular, if a certain set of keys all produce the same hash value,
then hash table lookups regress to searching an element in an unsorted
array, i.e., a linear operation. To ensure hashed collection types exhibit
their target performance, it is important to ensure that such collisions
cannot be induced merely by adding a particular list of keys to the
dictionary.
The easiest way to achieve this is to make sure `Key` implements hashing
following `Hashable`'s documented best practices. The conformance must
implement the `hash(into:)` requirement, and every bit of information that
is compared in `==` needs to be combined into the supplied `Hasher` value.
When used correctly, `Hasher` produces high-quality, randomly seeded hash
values that prevent repeatable hash collisions.
When `Key` correctly conforms to `Hashable`, key-based lookups in an ordered
dictionary is expected to take O(1) equality checks on average. Hash
collisions can still occur organically, so the worst-case lookup performance
is technically still O(*n*) (where *n* is the size of the dictionary);
however, long lookup chains are unlikely to occur in practice.
## Implementation Details
An ordered dictionary consists of an ordered set of keys, alongside a
regular `Array` value that contains their associated values.
+255
View File
@@ -0,0 +1,255 @@
# OrderedSet
An ordered collection of unique elements.
## Declaration
```swift
import OrderedCollections
@frozen struct OrderedSet<Element: Hashable>
```
## Overview
Similar to the standard `Set`, ordered sets ensure that each element appears
only once in the collection, and they provide efficient tests for
membership. However, like `Array` (and unlike `Set`), ordered sets maintain
their elements in a particular user-specified order, and they support
efficient random-access traversal of their members.
`OrderedSet` is a useful alternative to `Set` when the order of elements is
important, or when you need to be able to efficiently access elements at
various positions within the collection. It can also be used instead of an
`Array` when each element needs to be unique, or when you need to be able to
quickly determine if a value is a member of the collection.
You can create an ordered set with any element type that conforms to the
`Hashable` protocol.
```swift
let buildingMaterials: OrderedSet = ["straw", "sticks", "bricks"]
```
### Equality of Ordered Sets
Two ordered sets are considered equal if they contain the same elements, and
*in the same order*. This matches the concept of equality of an `Array`, and
it is different from the unordered `Set`.
```swift
let a: OrderedSet = [1, 2, 3, 4]
let b: OrderedSet = [4, 3, 2, 1]
a == b // false
b.sort() // `b` now has value [1, 2, 3, 4]
a == b // true
```
### Set Operations
`OrderedSet` implements most, but not all, `SetAlgebra` requirements. In
particular, it supports the membership test `contains(_:)` as well as all
high-level set operations such as `union(_:)`, `intersection(_:)` or
`isSubset(of:)`.
```swift
buildingMaterials.contains("glass") // false
buildingMaterials.intersection(["brick", "straw"]) // ["straw", "brick"]
```
Operations that return an ordered set usually preserve the ordering of
elements in their input. For example, in the case of the `intersection` call
above, the ordering of elements in the result is guaranteed to match their
order in the first input set, `buildingMaterials`.
On the other hand, predicates such as `isSubset(of:)` tend to ignore element
ordering:
```swift
let moreMaterials: OrderedSet = ["bricks", "glass", "sticks", "straw"]
buildingMaterials.isSubset(of: moreMaterials) // true
```
However, `OrderedSet` does not implement `insert(_:)` nor `update(with:)` --
it provides its own variants for insertion that are more explicit about
where in the collection new elements gets inserted:
```swift
func insert(_ item: Element, at index: Index) -> (inserted: Bool, index: Int)
func append(_ item: Element) -> (inserted: Bool, index: Int)
func update(at index: Int, with item: Element) -> Element
func updateOrAppend(_ item: Element) -> Element?
```
Additionally,`OrderedSet` has an order-sensitive definition of equality (see
above) that is incompatible with `SetAlgebra`'s documented semantic
requirements. Accordingly, `OrderedSet` does not (cannot) itself conform to
`SetAlgebra`.
### Unordered Set View
For cases where `SetAlgebra` conformance is desired (such as when passing an
ordered set to a function that is generic over that protocol), `OrderedSet`
provides an efficient *unordered view* of its elements that conforms to
`SetAlgebra`. The unordered view implements the same concept of equality as
the standard `Set`, ignoring element ordering.
```swift
var a: OrderedSet = [0, 1, 2, 3]
let b: OrderedSet = [3, 2, 1, 0]
a == b // false
a.unordered == b.unordered // true
func frobnicate<S: OrderedSet>(_ set: S) { ... }
frobnicate(a) // error: `OrderedSet<String>` does not conform to `SetAlgebra`
frobnicate(a.unordered) // OK
```
The unordered view is mutable. Insertions into it implicitly append new
elements to the end of the collection.
```swift
buildingMaterials.unordered.insert("glass") // => inserted: true
// buildingMaterials is now ["straw", "sticks", "brick", "glass"]
```
Accessing the unordered view is an efficient operation, with constant
(minimal) overhead. Direct mutations of the unordered view (such as the
insertion above) are executed in place when possible. However, as usual with
copy-on-write collections, if you make a copy of the view (such as by
extracting its value into a named variable), the resulting values will share
the same underlying storage, so mutations of either will incur a copy of the
whole set.
### Sequence and Collection Operations
Ordered sets are random-access collections. Members are assigned integer
indices, with the first element always being at index `0`:
```swift
let buildingMaterials: OrderedSet = ["straw", "sticks", "bricks"]
buildingMaterials[1] // "sticks"
buildingMaterials.firstIndex(of: "bricks") // 2
for i in 0 ..< buildingMaterials.count {
print("Little piggie #\(i) built a house of \(buildingMaterials[i])")
}
// Little piggie #0 built a house of straw
// Little piggie #1 built a house of sticks
// Little piggie #2 built a house of bricks
```
Because `OrderedSet` needs to keep its members unique, it cannot conform to
the full `MutableCollection` or `RangeReplaceableCollection` protocols.
Operations such as `MutableCollection`'s subscript setter or
`RangeReplaceableCollection`'s `replaceSubrange` assume the ability to
insert/replace arbitrary elements in the collection, but allowing that could
lead to duplicate values.
However, `OrderedSet` is able to partially implement these two protocols;
namely, there is no issue with mutation operations that merely change the
order of elements, or just remove some subset of existing members:
```swift
// Permutation operations from MutableCollection:
func swapAt(_ i: Int, _ j: Int)
func partition(by predicate: (Element) throws -> Bool) -> rethrows Int
func sort() where Element: Comparable
func sort(by predicate: (Element, Element) throws -> Bool) rethrows
func shuffle()
func shuffle<T: RandomNumberGenerator>(using generator: inout T)
func reverse()
// Removal operations from RangeReplaceableCollection:
func removeAll(keepingCapacity: Bool = false)
func remove(at index: Int) -> Element
func removeSubrange(_ bounds: Range<Int>)
func removeLast() -> Element
func removeLast(_ n: Int)
func removeFirst() -> Element
func removeFirst(_ n: Int)
func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows
```
`OrderedSet` also implements `reserveCapacity(_)` from
`RangeReplaceableCollection`, to allow for efficient insertion of a known
number of elements. (However, unlike `Array` and `Set`, `OrderedSet` does
not provide a `capacity` property.)
### Accessing The Contents of an Ordered Set as an Array
In cases where you need to pass the contents of an ordered set to a function
that only takes an array value or (or something that's generic over
`RangeReplaceableCollection` or `MutableCollection`), then the best option
is usually to directly extract the members of the `OrderedSet` as an `Array`
value using its `elements` property. `OrderedSet` uses a standard array
value for element storage, so extracting the array value has minimal
overhead.
```swift
func pickyFunction(_ items: Array<Int>)
var set: OrderedSet = [0, 1, 2, 3]
pickyFunction(set) // error
pickyFunction(set.elements) // OK
```
It is also possible to mutate the set by updating the value of the
`elements` property. This guarantees that direct mutations happen in place
when possible (i.e., without spurious copy-on-write copies).
However, the set needs to ensure the uniqueness of its members, so every
update to `elements` includes a postprocessing step to detect and remove
duplicates over the entire array. This can be slower than doing the
equivalent updates with direct `OrderedSet` operations, so updating
`elements` is best used in cases where direct implementations aren't
available -- for example, when you need to call a `MutableCollection`
algorithm that isn't directly implemented by `OrderedSet` itself.
### Performance
Like the standard `Set` type, the performance of hashing operations in
`OrderedSet` is highly sensitive to the quality of hashing implemented by
the `Element` type. Failing to correctly implement hashing can easily lead
to unacceptable performance, with the severity of the effect increasing with
the size of the hash table.
In particular, if a certain set of elements all produce the same hash value,
then hash table lookups regress to searching an element in an unsorted
array, i.e., a linear operation. To ensure hashed collection types exhibit
their target performance, it is important to ensure that such collisions
cannot be induced merely by adding a particular list of members to the set.
The easiest way to achieve this is to make sure `Element` implements hashing
following `Hashable`'s documented best practices. The conformance must
implement the `hash(into:)` requirement, and every bit of information that
is compared in `==` needs to be combined into the supplied `Hasher` value.
When used correctly, `Hasher` produces high-quality, randomly seeded hash
values that prevent repeatable hash collisions.
When `Element` implements `Hashable` correctly, testing for membership in an
ordered set is expected to take O(1) equality checks on average. Hash
collisions can still occur organically, so the worst-case lookup performance
is technically still O(*n*) (where *n* is the size of the set); however,
long lookup chains are unlikely to occur in practice.
### Implementation Details
An `OrderedSet` stores its members in a regular `Array` value (exposed by
the `elements` property). It also maintains a standalone hash table
containing array indices alongside the array; this is used to implement fast
membership tests. The size of the array is limited by the capacity of the
corresponding hash table, so indices stored inside the hash table can be
encoded into fewer bits than a standard `Int` value, leading to a storage
representation that can often be more compact than that of `Set` itself.
Inserting or removing a single member (or a range of members) needs to
perform the corresponding operation in the storage array, in addition to
renumbering any subsequent members in the hash table. Therefore, these
operations are expected to have performance characteristics similar to an
`Array`: inserting or removing an element to the end of an ordered set is
expected to execute in O(1) operations, while they are expected to take
linear time at the front (or in the middle) of the set. (Note that this is
different to the standard `Set`, where insertions and removals are expected
to take amortized O(1) time.)
+211
View File
@@ -0,0 +1,211 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
## Runtime Library Exception to the Apache 2.0 License: ##
As an exception, if you use this Software to compile your source code and
portions of this Software are embedded into the binary product as a result,
you may redistribute such product without providing attribution as would
otherwise be required by Sections 4(a), 4(b) and 4(d) of the License.
+25
View File
@@ -0,0 +1,25 @@
{
"object": {
"pins": [
{
"package": "swift-argument-parser",
"repositoryURL": "https://github.com/apple/swift-argument-parser",
"state": {
"branch": null,
"revision": "831ed5e860a70e745bc1337830af4786b2576881",
"version": "0.4.1"
}
},
{
"package": "swift-system",
"repositoryURL": "https://github.com/apple/swift-system",
"state": {
"branch": null,
"revision": "8ffa04c0a0592e6f4f9c30926dedd8fa1c5371f9",
"version": "0.0.1"
}
}
]
},
"version": 1
}
+141
View File
@@ -0,0 +1,141 @@
// swift-tools-version:5.3
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import PackageDescription
// This package recognizes the conditional compilation flags listed below.
// To use enable them, uncomment the corresponding lines or define them
// from the package manager command line:
//
// swift build -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS
var settings: [SwiftSetting]? = [
// Enables internal consistency checks at the end of initializers and
// mutating operations. This can have very significant overhead, so enabling
// this setting invalidates all documented performance guarantees.
//
// This is mostly useful while debugging an issue with the implementation of
// the hash table itself. This setting should never be enabled in production
// code.
// .define("COLLECTIONS_INTERNAL_CHECKS"),
// Hashing collections provided by this package usually seed their hash
// function with the address of the memory location of their storage,
// to prevent some common hash table merge/copy operations from regressing to
// quadratic behavior. This setting turns off this mechanism, seeding
// the hash function with the table's size instead.
//
// When used in conjunction with the SWIFT_DETERMINISTIC_HASHING environment
// variable, this enables reproducible hashing behavior.
//
// This is mostly useful while debugging an issue with the implementation of
// the hash table itself. This setting should never be enabled in production
// code.
// .define("COLLECTIONS_DETERMINISTIC_HASHING"),
]
// Prevent SPM 5.3 from throwing an error on empty settings arrays.
// (This has been fixed in 5.4.)
if settings?.isEmpty == true { settings = nil }
let package = Package(
name: "swift-collections",
products: [
.library(name: "Collections", targets: ["Collections"]),
.library(name: "DequeModule", targets: ["DequeModule"]),
.library(name: "OrderedCollections", targets: ["OrderedCollections"]),
.library(name: "UniquedModule", targets: ["UniquedModule"]),
.executable(name: "swift-collections-benchmark", targets: ["swift-collections-benchmark"]),
],
dependencies: [
// This is only used in the benchmark executable target.
.package(url: "https://github.com/apple/swift-collections-benchmark", from: "0.0.1"),
],
targets: [
.target(
name: "Collections",
dependencies: [
"DequeModule",
"OrderedCollections",
],
path: "Sources/Collections",
swiftSettings: settings),
// Testing support module
.target(
name: "CollectionsTestSupport",
dependencies: [],
swiftSettings: settings,
linkerSettings: [
.linkedFramework(
"XCTest",
.when(platforms: [.macOS, .iOS, .watchOS, .tvOS])),
]
),
// Benchmarking
.target(
name: "Benchmarks",
dependencies: [
.product(name: "CollectionsBenchmark", package: "swift-collections-benchmark"),
"CppBenchmarks",
"Collections",
],
path: "Benchmarks/Benchmarks",
resources: [
.copy("Library.json"),
]
),
.target(
name: "CppBenchmarks",
path: "Benchmarks/CppBenchmarks"
),
.target(
name: "swift-collections-benchmark",
dependencies: [
"Benchmarks",
],
path: "Benchmarks/swift-collections-benchmark"
),
// Deque<Element>
.target(
name: "DequeModule",
swiftSettings: settings),
.testTarget(
name: "DequeTests",
dependencies: ["DequeModule", "CollectionsTestSupport"],
swiftSettings: settings),
// OrderedSet<Element>, OrderedDictionary<Key, Value>
.target(
name: "OrderedCollections",
swiftSettings: settings),
.testTarget(
name: "OrderedCollectionsTests",
dependencies: ["OrderedCollections", "CollectionsTestSupport"],
swiftSettings: settings),
// Uniqued<Base>
.target(
name: "UniquedModule",
dependencies: ["DequeModule"],
swiftSettings: settings),
.testTarget(
name: "UniquedTests",
dependencies: ["UniquedModule", "CollectionsTestSupport"],
swiftSettings: settings),
],
cxxLanguageStandard: .cxx1z
)
+227
View File
@@ -0,0 +1,227 @@
# Swift Collections
**Swift Collections** is an open-source package of data structure implementations for the Swift programming language.
Read more about the package, and the intent behind it, in the [announcement on swift.org][announcement].
[announcement]: https://swift.org/blog/swift-collections
## Contents
The package currently provides the following implementations:
- [`Deque<Element>`][Deque], a double-ended queue backed by a ring buffer. Deques are range-replaceable, mutable, random-access collections.
- [`OrderedSet<Element>`][OrderedSet], a variant of the standard `Set` where the order of items is well-defined and items can be arbitrarily reordered. Uses a `ContiguousArray` as its backing store, augmented by a separate hash table of bit packed offsets into it.
- [`OrderedDictionary<Key, Value>`][OrderedDictionary], an ordered variant of the standard `Dictionary`, providing similar benefits.
[Deque]: Documentation/Deque.md
[OrderedSet]: Documentation/OrderedSet.md
[OrderedDictionary]: Documentation/OrderedDictionary.md
Swift Collections uses the same modularization approach as [**Swift Numerics**](https://github.com/apple/swift-numerics): it provides a standalone module for each group of data structures it implements. For instance, if you only need a double-ended queue type, you can pull in only that by importing `DequeModule`. `OrderedSet` and `OrderedDictionary` share much of the same underlying implementation, so they are provided by a single module, called `OrderedCollections`. However, there is also a top-level `Collections` module that gives you all of the included modules with a single import statement.
``` swift
import Collections
var deque: Deque<String> = ["Ted", "Rebecca"]
deque.prepend("Keeley")
deque.append("Nathan")
print(deque) // ["Keeley", "Ted", "Rebecca", "Nathan"]
```
## Project Status
We think the implementations in this package are robust, but the interfaces provided have not had time to stabilize. Accordingly, while the package is in its pre-1.0 state, from time to time new releases may sometimes include source-breaking changes. We'll try our best to keep such changes to a minimum, though, even during this chaotic initial period. Whenever feasible, we'll mitigate such changes with a multi-release deprecation period.
Before the 1.0 release, releases containing potentially source-breaking changes will increase the middle version number. The release notes will explain what changed, and how to update your code to work with the new version.
The implementations in this package have gone through an initial performance optimization pass, but there are lots of work still to be done. Still, we think these implementations are already quite fast enough for production use -- sometimes matching or exceeding the performance of similar constructs in popular prexisting implementations in other languages.
### Underscored Interfaces
As customary in Swift, interfaces that are technically declared `public` but begin with an underscore are not considered part of the public interface of this package. We may remove or change them in any release without notice, including minor point releases. (If you have a use case that requires using them, please [submit a Feature Request][feature-request] describing it! We'd like the public interface to be as useful as possible -- preferably without compromising safety or limiting future evolution.)
[feature-request]: https://github.com/apple/swift-collections/issues/new?assignees=&labels=enhancement&template=FEATURE_REQUEST.md
### Benchmarks
The package includes an extensive library of benchmarks in the [Benchmarks](./Benchmarks) directory, driven by a command-line executable target, `swift-collections-benchmark`. These benchmarks, the executable target, and its command-line interface are not considered part of the public interface of the package. As such, new releases may break them without any special ceremony. We do expect the benchmarks will stabilize with time.
For more information on our benchmarking tool, please see its dedicated package, [**Swift Collections Benchmark**][swift-collections-benchmark].
[swift-collections-benchmark]: https://github.com/apple/swift-collections-benchmark
### Test Support Library
The package comes with a rich test support library in the [Sources/CollectionsTestSupport](./Sources/CollectionsTestSupport) directory. These were loosely adapted from the contents of the `StdlibUnittest*` modules in the [Swift compiler repository](https://github.com/apple/swift/tree/main/stdlib/private), with some custom additions.
These components would likely be of interest to the wider Swift community, but they aren't yet stable enough (or documented enough) to publish them. Accordingly, these testing helpers are currently considered implementation details of this package, and are subject to change at whim.
The test support library currently provides the following functionality:
- [`AssertionContexts`](./Sources/CollectionsTestSupport/AssertionContexts): Custom test assertions with support for keeping track of nested context information, including stopping execution when the current context matches a particular value. (Useful for debugging combinatorial tests.)
<details>
<summary><strong>Click here for a short demonstration</strong></summary>
```swift
import XCTest
import CollectionsTestSupport
final class DequeTests: CollectionTestCase {
func test_demo() {
let values = [0, 10, 20, 30, 42, 50, 60]
for i in values.indices {
context.withTrace("i: \(i)") {
expectEqual(values[i], 10 * i)
}
}
}
}
```
```
DemoTests.swift:21: error: -[DemoTests.DemoTests test_demo] : XCTAssertEqual failed: ("42") is not equal to ("40") -
Trace:
- i: 4
```
To debug issues, copy the trace message into a `context.failIfTraceMatches(_:)` invocation and set a breakpoint on test failures.
```swift
let values = [0, 10, 20, 30, 42, 50, 60]
for i in values.indices {
context.withTrace("i: \(i)") {
// This will report a test failure before executing the `i == 4` case,
// letting us investigate what's going on.
context.failIfTraceMatches("""
Trace:
- i: 4
""")
expectEqual(values[i], 10 * i)
}
}
```
</details>
- [`Combinatorics`](./Sources/CollectionsTestSupport/Combinatorics): Basic support for exhaustive combinatorial testing. This allows us to easily verify that a collection operation works correctly on all possible instances up to a certain size, including behavioral variations such as unique/shared storage.
<details>
<summary><strong>Click here for an example</strong></summary>
```swift
func test_popFirst() {
withEveryDeque("deque", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (deque, contents) = tracker.deque(with: layout)
withHiddenCopies(if: isShared, of: &deque) { deque in
let expected = contents[...].popFirst()
let actual = deque.popFirst()
expectEqual(actual, expected)
expectEqualElements(deque, contents)
}
}
}
}
}
```
</details>
- [`ConformanceCheckers`](./Sources/CollectionsTestSupport/ConformanceCheckers): A set of generic, semi-automated protocol conformance tests for some Standard Library protocols. These can be used to easily validate the custom protocol conformances provided by this package. These checks aren't (can't be) complete -- but when used correctly, they are able to detect most accidental mistakes.
We currently have conformance checkers for the following protocols:
- [`Sequence`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift)
- [`Collection`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift)
- [`BidirectionalCollection`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckBidirectionalCollection.swift)
- [`Equatable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckEquatable.swift)
- [`Hashable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckHashable.swift)
- [`Comparable`](./Sources/CollectionsTestSupport/ConformanceCheckers/CheckComparable.swift)
- [`MinimalTypes`](./Sources/CollectionsTestSupport/MinimalTypes): Minimally conforming implementations for standard protocols. These types conform to various standard protocols by implementing the requirements in as narrow-minded way as possible -- sometimes going to extreme lengths to, say, implement collection index invalidation logic in the most unhelpful way possible.
- [`MinimalSequence`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalSequence.swift)
- [`MinimalCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalCollection.swift)
- [`MinimalBidirectionalCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift)
- [`MinimalRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift)
- [`MinimalMutableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift)
- [`MinimalRangeReplaceableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift)
- [`MinimalMutableRangeReplaceableRandomAccessCollection`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift)
- [`MinimalIterator`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalIterator.swift)
- [`MinimalIndex`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalIndex.swift)
- [`MinimalEncoder`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalEncoder.swift)
- [`MinimalDecoder`](./Sources/CollectionsTestSupport/MinimalTypes/MinimalDecoder.swift)
- [`Utilities`](./Sources/CollectionsTestSupport/Utilities): Utility types. Wrapper types for boxed values, a simple deterministic random number generator, and a lifetime tracker for catching simple memory management issues such as memory leaks. (The [Adress Sanitizer][asan] can be used to catch more serious problems.)
[asan]: https://developer.apple.com/documentation/xcode/diagnosing_memory_thread_and_crash_issues_early?language=objc
## Using **Swift Collections** in your project
To use this package in a SwiftPM project, add the following line to the dependencies in your `Package.swift` file:
```swift
.package(url: "https://github.com/apple/swift-collections", from: "0.0.1"),
```
## Contributing to Swift Collections
### Asking questions
We have a dedicated [Swift Collections Forum][forum] where we can ask and answer questions on how to use or work on this package. It's also a great place to discuss its evolution.
[forum]: https://forums.swift.org/c/related-projects/collections
### Reporting a bug
If you find something that looks like a bug, please open a [Bug Report][bugreport]! Fill out as many details as you can.
### Fixing a bug or making a small improvement
1. [Submit a PR][PR] with your change. If there is an [existing issue][issues] for the bug you're fixing, please include a reference to it.
2. Make sure to add tests covering whatever changes you are making.
[PR]: https://github.com/apple/swift-collections/compare
[issues]: https://github.com/apple/swift-collections/issues
[bugreport]: https://github.com/apple/swift-collections/issues/new?assignees=&labels=bug&template=BUG_REPORT.md
### Proposing a small enhancement
1. Raise a [Feature Request][enhancement]. Discuss why it would be important to implement it.
2. Submit a PR with your implementation, participate in the review discussion.
3. When there is a consensus that the feature is desirable, and the implementation works well, it is fully tested and documented, then it will be merged.
4. Rejoice!
[enhancement]: https://github.com/apple/swift-collections/issues/new?assignees=&labels=enhancement&template=FEATURE_REQUEST.md
### Proposing the addition of a new data structure
1. Start a topic on the [forum], explaining why you believe it would be important to implement the data structure. This way we can figure out if it would be right for the package, discuss implementation strategies, and plan to allocate capacity to help.
2. When maintainers agreed to your implementation plan, start work on it, and submit a PR with your implementation as soon as you have something that's ready to show! We'd love to get involved as early as you like.
3. Participate in the review discussion, and adapt the code accordingly. Sometimes we may need to go through several revisions! This is fine -- it makes the end result that much better.
3. When there is a consensus that the feature is ready, and the implementation is fully tested and documented, the PR will be merged by a maintainer.
4. Celebrate! You've achieved something great!
### Licensing
By submitting a pull request, you represent that you have the right to license your contribution to Apple and the community, and agree by submitting the patch that your contributions are licensed under the [Swift License](https://swift.org/LICENSE.txt), a copy of which is [provided in this repository](LICENSE.txt).
### Code of Conduct
Like all Swift.org projects, we would like the Swift Collections project to foster a diverse and friendly community. We expect contributors to adhere to the [Swift.org Code of Conduct](https://swift.org/code-of-conduct/). A copy of this document is [available in this repository][coc].
[coc]: CODE_OF_CONDUCT.md
### Contacting the maintainers
The current code owner of this package is Karoy Lorentey ([@lorentey](https://github.com/lorentey)). You can contact him [on the Swift forums](https://forums.swift.org/u/lorentey/summary), or by writing an email to klorentey at apple dot com. (Please keep it related to this project.)
In case of moderation issues, you can also directly contact a member of the [Swift Core Team](https://swift.org/community/#community-structure).
+13
View File
@@ -0,0 +1,13 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@_exported import DequeModule
@_exported import OrderedCollections
@@ -0,0 +1,390 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
public func expectFailure(
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
let message = message()
XCTFail(
TestContext.currentTrace(message),
file: file, line: line)
if trapping {
fatalError(message, file: file, line: line)
}
}
internal func _expectFailure(
_ diagnostic: String,
_ message: () -> String,
trapping: Bool,
file: StaticString,
line: UInt
) {
let message = message()
XCTFail(
TestContext.currentTrace(
"""
\(diagnostic)
\(message)
"""),
file: file, line: line)
if trapping {
fatalError(message, file: file, line: line)
}
}
public func expectTrue(
_ value: Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if value { return }
_expectFailure(
"'\(value)' is not true",
message, trapping: trapping, file: file, line: line)
}
public func expectFalse(
_ value: Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if !value { return }
_expectFailure(
"'\(value)' is not false",
message, trapping: trapping, file: file, line: line)
}
public func expectNil<T>(
_ value: Optional<T>,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if value == nil { return }
_expectFailure(
"'\(value!)' is not nil",
message, trapping: trapping, file: file, line: line)
}
public func expectNotNil<T>(
_ value: Optional<T>,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if value != nil { return }
_expectFailure(
"value is nil",
message, trapping: trapping, file: file, line: line)
}
public func expectNotNil<T>(
_ value: Optional<T>,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line,
_ handler: (T) throws -> Void = { _ in }
) rethrows {
if let value = value {
try handler(value)
return
}
_expectFailure(
"value is nil",
message, trapping: trapping, file: file, line: line)
}
public func expectIdentical<T: AnyObject>(
_ left: T?, _ right: T?,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if left === right { return }
let l = left.map { "\($0)" } ?? "nil"
let r = right.map { "\($0)" } ?? "nil"
_expectFailure(
"'\(l)' is not identical to '\(r)'",
message, trapping: trapping, file: file, line: line)
}
public func expectNotIdentical<T: AnyObject>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if left !== right { return }
_expectFailure(
"'\(left)' is identical to '\(right)'",
message, trapping: trapping, file: file, line: line)
}
public func expectEquivalent<A, B>(
_ left: A, _ right: B,
by areEquivalent: (A, B) -> Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if areEquivalent(left, right) { return }
_expectFailure(
"'\(left)' is not equivalent to '\(right)'",
message, trapping: trapping, file: file, line: line)
}
public func expectEquivalent<A, B>(
_ left: A?, _ right: B?,
by areEquivalent: (A, B) -> Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if let left = left, let right = right, areEquivalent(left, right) { return }
let l = left.map { "\($0)" } ?? "nil"
let r = right.map { "\($0)" } ?? "nil"
_expectFailure(
"'\(l)' is not equivalent to '\(r)'",
message, trapping: trapping, file: file, line: line)
}
public func expectEqual<T: Equatable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if left == right { return }
_expectFailure(
"'\(left)' is not equal to '\(right)'",
message, trapping: trapping, file: file, line: line)
}
public func expectEqual<T: Equatable>(
_ left: T?, _ right: T?,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if left == right { return }
let l = left.map { "\($0)" } ?? "nil"
let r = right.map { "\($0)" } ?? "nil"
_expectFailure(
"'\(l)' is not equal to '\(r)'",
message, trapping: trapping, file: file, line: line)
}
public func expectNotEqual<T: Equatable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if left != right { return }
_expectFailure(
"'\(left)' is equal to '\(right)'",
message, trapping: trapping, file: file, line: line)
}
public func expectLessThan<T: Comparable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if left < right { return }
_expectFailure(
"'\(left)' is not less than '\(right)'",
message, trapping: trapping, file: file, line: line)
}
public func expectLessThanOrEqual<T: Comparable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if left <= right { return }
_expectFailure(
"'\(left)' is not less than or equal to '\(right)'",
message, trapping: trapping, file: file, line: line)
}
public func expectGreaterThan<T: Comparable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if left > right { return }
_expectFailure(
"'\(left)' is not greater than '\(right)'",
message, trapping: trapping, file: file, line: line)
}
public func expectGreaterThanOrEqual<T: Comparable>(
_ left: T, _ right: T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
if left >= right { return }
_expectFailure(
"'\(left)' is not less than or equal to '\(right)'",
message, trapping: trapping, file: file, line: line)
}
/// Check if `left` and `right` contain equal elements in the same order.
/// Note: `left` and `right` must be restartable sequences.
public func expectEqualElements<S1: Sequence, S2: Sequence>(
_ left: S1,
_ right: S2,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) where S1.Element == S2.Element, S1.Element: Equatable {
let left = Array(left)
let right = Array(right)
if left.elementsEqual(right) { return }
_expectFailure(
"'\(left)' does not have equal elements to '\(right)'",
message, trapping: trapping, file: file, line: line)
}
public func expectEquivalentElements<S1: Sequence, S2: Sequence>(
_ left: S1,
_ right: S2,
by areEquivalent: (S1.Element, S2.Element) -> Bool,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) {
let left = Array(left)
let right = Array(right)
if left.elementsEqual(right, by: areEquivalent) { return }
_expectFailure(
"'\(left)' does not have equivalent elements to '\(right)'",
message, trapping: trapping, file: file, line: line)
}
/// Check if `left` and `right` contain equal elements in the same order.
/// Note: `left` and `right` must be restartable sequences.
public func expectEqualElements<
S1: Sequence, S2: Sequence,
A: Equatable, B: Equatable
>(
_ left: S1,
_ right: S2,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) where S1.Element == (key: A, value: B), S2.Element == (key: A, value: B) {
let left = Array(left)
let right = Array(right)
if
left.elementsEqual(
right,
by: { $0.key == $1.key && $0.value == $1.value })
{ return }
_expectFailure(
"'\(left)' does not have equal elements to '\(right)'",
message, trapping: trapping, file: file, line: line)
}
public func expectMonotonicallyIncreasing<S: Sequence>(
_ items: S,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) where S.Element: Comparable {
let items = Array(items)
var it = items.makeIterator()
guard var prev = it.next() else { return }
while let next = it.next() {
guard prev <= next else {
_expectFailure(
"'\(items)' is not monotonically increasing",
message, trapping: trapping, file: file, line: line)
return
}
prev = next
}
}
public func expectStrictlyMonotonicallyIncreasing<S: Sequence>(
_ items: S,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line
) where S.Element: Comparable {
let items = Array(items)
var it = items.makeIterator()
guard var prev = it.next() else { return }
while let next = it.next() {
guard prev < next else {
_expectFailure(
"'\(items)' is not strictly monotonically increasing",
message, trapping: trapping, file: file, line: line)
return
}
prev = next
}
}
public func expectThrows<T>(
_ expression: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "",
trapping: Bool = false,
file: StaticString = #file,
line: UInt = #line,
_ errorHandler: (Error) -> Void = { _ in }
) {
do {
let result = try expression()
expectFailure("Expression did not throw"
+ (T.self == Void.self ? "" : " (returned '\(result)' instead)"),
trapping: trapping,
file: file, line: line)
} catch {
errorHandler(error)
}
}
@@ -0,0 +1,30 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
open class CollectionTestCase: XCTestCase {
internal var _context: TestContext?
public var context: TestContext { _context! }
public override func setUp() {
super.setUp()
_context = TestContext.pushNew()
}
public override func tearDown() {
super.setUp()
TestContext.pop(context)
_context = nil
}
}
@@ -0,0 +1,177 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// Run the supplied closure with all values in `items` in a loop,
/// recording the current value in the current test trace stack.
public func withEvery<S: Sequence>(
_ label: String,
in items: S,
file: StaticString = #file,
line: UInt = #line,
run body: (S.Element) throws -> Void
) rethrows {
let context = TestContext.current
for item in items {
let entry = context.push("\(label): \(item)", file: file, line: line)
var done = false
defer {
context.pop(entry)
if !done {
print(context.currentTrace(title: "Throwing trace"))
}
}
try body(item)
done = true
}
}
public func withEveryRange<T: Strideable>(
_ label: String,
in bounds: Range<T>,
file: StaticString = #file,
line: UInt = #line,
run body: (Range<T>) throws -> Void
) rethrows where T.Stride == Int {
let context = TestContext.current
for lowerBound in bounds.lowerBound ... bounds.upperBound {
for upperBound in lowerBound ... bounds.upperBound {
let range = lowerBound ..< upperBound
let entry = context.push("\(label): \(range)", file: file, line: line)
var done = false
defer {
context.pop(entry)
if !done {
print(context.currentTrace(title: "Throwing trace"))
}
}
try body(range)
done = true
}
}
}
internal func _samples<C: Collection>(from items: C) -> [C.Element] {
let c = items.count
guard c > 7 else { return Array(items) }
let offsets = [0, 1, c / 2 - 1, c / 2, c / 2 + 1, c - 2, c - 1]
var offset = 0
var index = items.startIndex
var result: [C.Element] = []
result.reserveCapacity(7)
for o in offsets {
items.formIndex(&index, offsetBy: o - offset)
offset = o
result.append(items[index])
}
return result
}
/// Run the supplied closure with all values in `items` in a loop,
/// recording the current value in the current test trace stack.
public func withSome<C: Collection>(
_ label: String,
in items: C,
file: StaticString = #file,
line: UInt = #line,
run body: (C.Element) throws -> Void
) rethrows {
let context = TestContext.current
for item in _samples(from: items) {
let entry = context.push("\(label): \(item)", file: file, line: line)
var done = false
defer {
context.pop(entry)
if !done {
print(context.currentTrace(title: "Throwing trace"))
}
}
try body(item)
done = true
}
}
public func withSomeRanges<T: Strideable>(
_ label: String,
in bounds: Range<T>,
file: StaticString = #file,
line: UInt = #line,
run body: (Range<T>) throws -> Void
) rethrows where T.Stride == Int {
let context = TestContext.current
for lowerBound in _samples(from: bounds) {
for upperBound in _samples(from: lowerBound ... bounds.upperBound) {
let range = lowerBound ..< upperBound
let entry = context.push("\(label): \(range)", file: file, line: line)
var done = false
defer {
context.pop(entry)
if !done {
print(context.currentTrace(title: "Throwing trace"))
}
}
try body(range)
done = true
}
}
}
/// Utility function for testing mutations with value semantics.
///
/// Calls `body` with on given collection value, while optionally keeping
/// hidden a hidden copy of it around. Once `body` returns, checks that the copy
/// remain unchanged.
///
/// - Parameters:
/// - `enabled`: if `false`, then no copies are made -- the values are passed to `body` with no processing.
/// - `value`: The collection value that is being tested.
/// - `body`: A closure performing a mutation on `value`.
public func withHiddenCopies<S: Sequence, R>(
if enabled: Bool,
of value: inout S,
file: StaticString = #file, line: UInt = #line,
_ body: (inout S) throws -> R
) rethrows -> R where S.Element: Equatable {
guard enabled else { return try body(&value) }
let copy = value
let expected = Array(value)
let result = try body(&value)
expectEqualElements(copy, expected, file: file, line: line)
return result
}
/// Utility function for testing mutations with value semantics.
///
/// Calls `body` with on given collection value, while optionally keeping
/// hidden a hidden copy of it around. Once `body` returns, checks that the copy
/// remain unchanged.
///
/// - Parameters:
/// - `enabled`: if `false`, then no copies are made -- the values are passed to `body` with no processing.
/// - `value`: The collection value that is being tested.
/// - `body`: A closure performing a mutation on `value`.
public func withHiddenCopies<
S: Sequence,
Key: Equatable,
Value: Equatable,
R
>(
if enabled: Bool,
of value: inout S,
file: StaticString = #file, line: UInt = #line,
_ body: (inout S) throws -> R
) rethrows -> R where S.Element == (key: Key, value: Value) {
guard enabled else { return try body(&value) }
let copy = value
let expected = Array(value)
let result = try body(&value)
expectEqualElements(copy, expected, file: file, line: line)
return result
}
@@ -0,0 +1,259 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
public final class TestContext {
internal var _nextStateId = 0
internal var _nextIndexId = 0
/// Stack of labels with associated source positions.
/// Useful for tracking failed cases in combinatorial tests.
internal var _trace: [Entry] = []
// FIXME: This ought to be a thread-local variable.
internal static var _current: TestContext?
public init() {}
}
extension TestContext {
public static var current: TestContext {
guard let current = _current else {
fatalError("There is no current test context")
}
return current
}
public static func pushNew() -> TestContext {
let context = TestContext()
push(context)
return context
}
public static func push(_ context: TestContext) {
precondition(_current == nil, "Can't nest test contexts")
_current = context
}
public static func pop(_ context: TestContext) {
precondition(_current === context, "Can't pop mismatching context")
_current = nil
}
}
extension TestContext {
/// An entry in the stack trace. Associates a user-specified label with its associated source position.
public struct Entry: Hashable, CustomStringConvertible {
let label: String
let file: StaticString
let line: UInt
public init(
label: String,
file: StaticString = #file,
line: UInt = #line
) {
self.label = label
self.file = file
self.line = line
}
public var description: String {
"\(label) (\(file):\(line))"
}
public static func ==(left: Self, right: Self) -> Bool {
left.label == right.label
&& left.file.utf8Start == right.file.utf8Start
&& left.file.utf8CodeUnitCount == right.file.utf8CodeUnitCount
&& left.line == right.line
}
public func hash(into hasher: inout Hasher) {
hasher.combine(label)
hasher.combine(file.utf8Start)
hasher.combine(file.utf8CodeUnitCount)
hasher.combine(line)
}
}
}
extension TestContext: Equatable {
public static func ==(left: TestContext, right: TestContext) -> Bool {
return left === right
}
}
extension TestContext {
internal func nextStateId() -> Int {
defer { _nextStateId += 1 }
return _nextStateId
}
internal func nextIndexId() -> Int {
defer { _nextIndexId += 1 }
return _nextIndexId
}
}
extension TestContext {
/// Add the specified trace to the test context trace stack.
/// This call must be paired with a `pop` call with the same value,
/// with no intervening unpopped pushes.
@discardableResult
public func push(_ entry: Entry) -> Entry {
_trace.append(entry)
return entry
}
/// Add the specified label to the test context trace stack.
/// This call must be paired with a `pop` call with the same value,
/// with no intervening unpopped pushes.
@discardableResult
public func push(
_ label: String,
file: StaticString = #file,
line: UInt = #line
) -> Entry {
return push(Entry(label: label, file: file, line: line))
}
/// Cancel the trace push that returned `trace` and pop the context trace back
/// to the state it was before the push. All pushes since the one that pushed `trace`
/// must have been popped at the time this is called.
public func pop(_ entry: Entry) {
let old = _trace.removeLast()
precondition(
old == entry,
"""
Push/pop pairing violation: top of stack doesn't match expectation.
expected: \(entry)
actual: \(old)
""")
}
/// Execute the supplied closure in a new nested trace entry `entry`.
/// Assertion failure messages within the closure will include the specified information to aid with debugging.
public func withTrace<R>(
_ entry: Entry,
_ body: () throws -> R
) rethrows -> R {
push(entry)
defer { pop(entry) }
return try body()
}
/// Execute the supplied closure in a new nested trace entry.
/// Assertion failure messages within the closure will include the specified information to aid with debugging.
public func withTrace<R>(
_ label: String,
file: StaticString = #file,
line: UInt = #line,
_ body: () throws -> R
) rethrows -> R {
let entry = push(label, file: file, line: line)
defer { pop(entry) }
return try body()
}
/// The current stack of tracing labels with their associated source positions.
public var currentTrace: [Entry] { _trace }
/// Return a (multi-line) string describing the current trace stack.
/// This string can be used to identify a particular test context,
/// for use in `failIfTraceMatches`.
public func currentTrace(
_ message: String = "",
title: String = "Trace"
) -> String {
guard !_trace.isEmpty else {
return """
\(message)
\(title): (empty)
"""
}
var result = """
\(message)
\(title):
"""
for trace in _trace {
result += " - \(trace.label)\n"
}
return result
}
public static func currentTrace(
_ message: String = "",
title: String = "Trace"
) -> String {
guard let context = _current else { return message }
return context.currentTrace(message, title: title)
}
/// Set a breakpoint on this function to stop execution only when `failIfTraceMatches`
/// triggers a test failure. The alternative is to set up a "Test Failure" breakpoint,
/// but if you have lots of test failures, that one might trigger too many times.
@inline(never)
public func debuggerBreak(
_ message: String,
file: StaticString = #file,
line: UInt = #line
) {
XCTFail(message, file: file, line: line)
}
/// Call this function to emit a test failure when the current test trace matches
/// the (typically multi-line) string given. By setting a breakpoint on test failures
/// (or on the `debuggerBreak` method above), you can then pause execution to
/// debug the test in that particular context.
///
/// The string you need to pass to this function can be copy and pasted from
/// the failure message of the `expect` family of assertion methods, or
/// it can be manually generated by calling `currentTrace()` during a debug
/// session.
///
/// For example, here we trigger a test failure when `count` is 8 and `offset` is 3:
///
/// func testFoo() {
/// withEvery("count", in: 0 ..< 100) { count in
/// withEvery("offset", in: 0 ... count) { offset in
/// failIfTraceMatches("""
/// Trace:
/// - count: 8
/// - offset: 3
/// """)
/// deque.buggyMethod(...)
/// }
/// }
/// }
///
public func failIfTraceMatches(
_ expectedTrace: String,
file: StaticString = #file,
line: UInt = #line
) {
// Filter for lines that match the regex " *- "
let breakOnTrace: [String] =
expectedTrace.split(separator: "\n").compactMap { line in
guard let i = line.firstIndex(where: { $0 != " " }) else { return nil }
guard line[i...].starts(with: "- ") else { return nil }
return String(line[i...].dropFirst(2))
}
let labels = _trace.map({ $0.label })
if labels == breakOnTrace {
debuggerBreak(currentTrace(title: "Hit trace"), file: file, line: line)
}
}
}
@@ -0,0 +1,147 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
// FIXME: Port all of the collection validation tests from the Swift compiler codebase.
import XCTest
extension BidirectionalCollection {
func _indicesByIndexBefore() -> [Index] {
var result: [Index] = []
var i = endIndex
while i != startIndex {
i = index(before: i)
result.append(i)
}
result.reverse()
return result
}
func _indicesByFormIndexBefore() -> [Index] {
var result: [Index] = []
var i = endIndex
while i != startIndex {
formIndex(before: &i)
result.append(i)
}
result.reverse()
return result
}
}
public func checkBidirectionalCollection<C: BidirectionalCollection, S: Sequence>(
_ collection: C,
expectedContents: S,
file: StaticString = #file,
line: UInt = #line
) where C.Element: Equatable, S.Element == C.Element {
checkBidirectionalCollection(
collection,
expectedContents: expectedContents,
by: ==,
file: file,
line: line)
}
public func checkBidirectionalCollection<C: BidirectionalCollection, S: Sequence>(
_ collection: C,
expectedContents: S,
by areEquivalent: (S.Element, S.Element) -> Bool,
file: StaticString = #file,
line: UInt = #line
) where S.Element == C.Element {
checkSequence(
{ collection }, expectedContents: expectedContents,
by: areEquivalent,
file: file, line: line)
_checkCollection(
collection, expectedContents: expectedContents,
by: areEquivalent,
file: file, line: line)
_checkBidirectionalCollection(
collection, expectedContents: expectedContents,
by: areEquivalent,
file: file, line: line)
}
public func _checkBidirectionalCollection<C: BidirectionalCollection, S: Sequence>(
_ collection: C,
expectedContents: S,
by areEquivalent: (S.Element, S.Element) -> Bool,
file: StaticString = #file,
line: UInt = #line
) where S.Element == C.Element {
let entry = TestContext.current.push("checkBidirectionalCollection", file: file, line: line)
defer { TestContext.current.pop(entry) }
let expectedContents = Array(expectedContents)
// Check that `index(before:)` and `formIndex(before:)` are consistent with `index(after:)`.
let indicesByIndexAfter = collection._indicesByIndexAfter()
let indicesByIndexBefore = collection._indicesByIndexBefore()
let indicesByFormIndexBefore = collection._indicesByFormIndexBefore()
expectEqual(indicesByIndexBefore, indicesByIndexAfter)
expectEqual(indicesByFormIndexBefore, indicesByIndexAfter)
// Check contents using indexing.
let indexContents1 = indicesByIndexBefore.map { collection[$0] }
expectEquivalentElements(
indexContents1, expectedContents,
by: areEquivalent,
"\(expectedContents)")
let indexContents2 = indicesByFormIndexBefore.map { collection[$0] }
expectEquivalentElements(
indexContents2, expectedContents,
by: areEquivalent,
"\(expectedContents)")
// Check the Indices associated type
if C.self != C.Indices.self {
checkBidirectionalCollection(collection.indices, expectedContents: indicesByIndexAfter)
}
var allIndices = indicesByIndexAfter
allIndices.append(collection.endIndex)
// Check `index(_,offsetBy:)`
for (startOffset, start) in allIndices.enumerated() {
for endOffset in 0 ..< allIndices.count {
let end = collection.index(start, offsetBy: endOffset - startOffset)
expectEqual(end, allIndices[endOffset])
if endOffset < expectedContents.count {
expectEquivalent(
collection[end], expectedContents[endOffset],
by: areEquivalent)
}
}
}
// Check `distance(from:to:)`
for i in allIndices.indices {
for j in allIndices.indices {
let d = collection.distance(from: allIndices[i], to: allIndices[j])
expectEqual(d, j - i)
}
}
// Check slicing.
for i in 0 ..< allIndices.count {
for j in i ..< allIndices.count {
let range = allIndices[i] ..< allIndices[j]
let slice = collection[range]
expectEqualElements(slice._indicesByIndexBefore(), allIndices[i ..< j])
expectEqualElements(slice._indicesByFormIndexBefore(), allIndices[i ..< j])
}
}
}
@@ -0,0 +1,270 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
// FIXME: Port all of the collection validation tests from the Swift compiler codebase.
import XCTest
// FIXME: Port the collection validation tests from the Swift compiler codebase.
extension Sequence {
func _contentsByIterator() -> [Element] {
var result: [Element] = []
var it = makeIterator()
while let item = it.next() {
result.append(item)
}
return result
}
func _contentsByCopyContents(_ count: Int? = nil) -> [Element] {
var it: Iterator?
var result = Array(
unsafeUninitializedCapacity: count ?? self.underestimatedCount
) { buffer, count in
(it, count) = self._copyContents(initializing: buffer)
}
while let next = it!.next() {
result.append(next)
}
return result
}
}
extension Collection {
func _indicesByIndexAfter() -> [Index] {
var result: [Index] = []
var i = startIndex
while i != endIndex {
result.append(i)
i = index(after: i)
}
return result
}
func _indicesByFormIndexAfter() -> [Index] {
var result: [Index] = []
var i = startIndex
while i != endIndex {
result.append(i)
formIndex(after: &i)
}
return result
}
}
public func checkCollection<C: Collection, Expected: Sequence>(
_ collection: C,
expectedContents: Expected,
file: StaticString = #file,
line: UInt = #line
) where C.Element: Equatable, Expected.Element == C.Element {
let expectedContents = Array(expectedContents)
checkCollection(
collection,
expectedContents: expectedContents,
by: ==,
file: file, line: line)
let indicesByIndexAfter = collection._indicesByIndexAfter()
for item in expectedContents {
if let first = collection._customIndexOfEquatableElement(item) {
expectNotNil(first) { first in
expectEqual(collection[first], item)
let expected = expectedContents.firstIndex(of: item)!
expectEqual(first, indicesByIndexAfter[expected])
}
}
if let last = collection._customLastIndexOfEquatableElement(item) {
expectNotNil(last) { last in
expectEqual(collection[last], item)
let expected = expectedContents.lastIndex(of: item)!
expectEqual(last, indicesByIndexAfter[expected])
}
}
}
}
public func checkCollection<C: Collection, Expected: Sequence>(
_ collection: C,
expectedContents: Expected,
by areEquivalent: (C.Element, C.Element) -> Bool,
file: StaticString = #file,
line: UInt = #line
) where Expected.Element == C.Element {
checkSequence(
{ collection },
expectedContents: expectedContents,
by: areEquivalent,
file: file, line: line)
_checkCollection(
collection,
expectedContents: expectedContents,
by: areEquivalent,
file: file, line: line)
}
public func _checkCollection<C: Collection, Expected: Sequence>(
_ collection: C,
expectedContents: Expected,
by areEquivalent: (C.Element, C.Element) -> Bool,
file: StaticString = #file,
line: UInt = #line
) where Expected.Element == C.Element {
let entry = TestContext.current.push("checkCollection", file: file, line: line)
defer { TestContext.current.pop(entry) }
let expectedContents = Array(expectedContents)
expectEqual(collection.isEmpty, expectedContents.isEmpty)
expectEqual(collection.count, expectedContents.count)
// Check that `index(after:)` produces the same results as `formIndex(after:)`
let indicesByIndexAfter = collection._indicesByIndexAfter()
let indicesByFormIndexAfter = collection._indicesByFormIndexAfter()
expectEqual(indicesByIndexAfter, indicesByFormIndexAfter)
// Check contents using the iterator.
expectEquivalentElements(
collection._contentsByIterator(),
expectedContents,
by: areEquivalent)
// Check _copyContents.
expectEquivalentElements(
collection._contentsByCopyContents(),
expectedContents,
by: areEquivalent)
// Check contents using indexing.
let indexContents1 = indicesByIndexAfter.map { collection[$0] }
expectEquivalentElements(indexContents1, expectedContents, by: areEquivalent)
let indexContents2 = indicesByFormIndexAfter.map { collection[$0] }
expectEquivalentElements(indexContents2, expectedContents, by: areEquivalent)
// Check the endIndex.
expectEqual(collection.endIndex, collection.indices.endIndex)
// Check the Indices associated type
if C.self != C.Indices.self {
checkCollection(collection.indices, expectedContents: indicesByIndexAfter)
} else {
expectEqual(collection.indices.count, collection.count)
expectEqualElements(collection.indices, indicesByIndexAfter)
}
expectEqual(collection.indices.endIndex, collection.endIndex)
// The sequence of indices must be monotonically increasing.
var allIndices = indicesByIndexAfter
allIndices.append(collection.endIndex)
checkComparable(allIndices, oracle: { .comparing($0, $1) })
// Check `index(_,offsetBy:)`
for (offset, start) in allIndices.enumerated() {
for distance in 0 ... indicesByIndexAfter.count - offset {
let end = collection.index(start, offsetBy: distance)
expectEqual(end, allIndices[offset + distance])
if offset + distance < expectedContents.count {
expectEquivalent(collection[end], expectedContents[offset + distance],
by: areEquivalent)
}
}
}
// Check `index(_,offsetBy:limitedBy:)`
let limits =
Set([0, allIndices.count - 1, allIndices.count / 2])
.sorted()
withEvery("limit", in: limits) { limit in
withEvery("i", in: 0 ..< allIndices.count) { i in
let max = allIndices.count - i + (limit >= i ? 2 : 0)
withEvery("delta", in: 0 ..< max) { delta in
let actual = collection.index(
allIndices[i],
offsetBy: delta,
limitedBy: allIndices[limit])
let j = i + delta
let expected = i > limit || j <= limit ? allIndices[j] : nil
expectEqual(actual, expected)
}
}
}
// Check `distance(from:to:)`
withEvery("i", in: allIndices.indices) { i in
withEvery("j", in: allIndices.indices) { j in
let d = collection.distance(from: allIndices[i], to: allIndices[j])
expectEqual(d, j - i)
}
}
// Check slicing.
withEvery("i", in: 0 ..< allIndices.count) { i in
withEvery("j", in: i ..< allIndices.count) { j in
let range = allIndices[i] ..< allIndices[j]
let slice = collection[range]
expectEqual(slice.count, j - i)
expectEqual(slice.isEmpty, i == j)
expectEqual(slice.startIndex, allIndices[i])
expectEqual(slice.endIndex, allIndices[j])
expectEqual(slice.distance(from: allIndices[i], to: allIndices[j]), j - i)
expectEqual(slice.index(allIndices[i], offsetBy: j - i), allIndices[j])
expectEqual(slice.index(allIndices[i], offsetBy: j - i, limitedBy: allIndices[j]),
allIndices[j])
expectEqual(slice.index(allIndices[i], offsetBy: j - i, limitedBy: allIndices[i]),
j - i > 0 ? nil : allIndices[i])
expectEqual(slice.index(allIndices[i], offsetBy: j - i, limitedBy: allIndices[0]),
i > 0 || j == 0 ? allIndices[j] : nil)
expectEquivalentElements(slice, expectedContents[i ..< j],
by: areEquivalent)
expectEquivalentElements(
slice._contentsByIterator(), expectedContents[i ..< j],
by: areEquivalent)
expectEquivalentElements(
slice._contentsByCopyContents(), expectedContents[i ..< j],
by: areEquivalent)
// Check _copyContents.
let copyContents = collection._contentsByCopyContents()
expectEquivalentElements(
copyContents, expectedContents,
by: areEquivalent)
expectEqualElements(slice._indicesByIndexAfter(), allIndices[i ..< j])
expectEqualElements(slice._indicesByFormIndexAfter(), allIndices[i ..< j])
expectEqualElements(slice.indices, allIndices[i ..< j])
expectEqualElements(slice.indices._indicesByIndexAfter(), allIndices[i ..< j])
expectEqualElements(slice.indices._indicesByFormIndexAfter(), allIndices[i ..< j])
// Check the subsequence iterator.
expectEquivalentElements(
slice, expectedContents[i ..< j],
by: areEquivalent)
// Check the subsequence subscript.
expectEquivalentElements(
allIndices[i ..< j].map { slice[$0] }, expectedContents[i ..< j],
by: areEquivalent)
// Check _copyToContiguousArray.
expectEquivalentElements(
Array(slice), expectedContents[i ..< j],
by: areEquivalent)
// Check slicing of slices.
expectEquivalentElements(
slice[range], expectedContents[i ..< j],
by: areEquivalent)
}
}
}
@@ -0,0 +1,176 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibUnittest
public enum ExpectedComparisonResult: Hashable {
case lt, eq, gt
public func flip() -> ExpectedComparisonResult {
switch self {
case .lt:
return .gt
case .eq:
return .eq
case .gt:
return .lt
}
}
public static func comparing<C: Comparable>(_ left: C, _ right: C) -> Self {
left < right ? .lt
: left > right ? .gt
: .eq
}
}
extension ExpectedComparisonResult: CustomStringConvertible {
public var description: String {
switch self {
case .lt:
return "<"
case .eq:
return "=="
case .gt:
return ">"
}
}
}
public func checkComparable<Instance: Comparable>(
sortedEquivalenceClasses: [[Instance]],
file: StaticString = #file, line: UInt = #line
) {
let instances = sortedEquivalenceClasses.flatMap { $0 }
// oracle[i] is the index of the equivalence class that contains instances[i].
let oracle = sortedEquivalenceClasses.indices.flatMap { i in repeatElement(i, count: sortedEquivalenceClasses[i].count) }
checkComparable(
instances,
oracle: {
if oracle[$0] < oracle[$1] { return .lt }
if oracle[$0] > oracle[$1] { return .gt }
return .eq
},
file: file, line: line)
}
/// Test that the elements of `instances` satisfy the semantic
/// requirements of `Comparable`, using `oracle` to generate comparison
/// expectations from pairs of positions in `instances`.
public func checkComparable<Instances: Collection>(
_ instances: Instances,
oracle: (Instances.Index, Instances.Index) -> ExpectedComparisonResult,
file: StaticString = #file, line: UInt = #line
) where Instances.Element: Comparable {
checkEquatable(instances,
oracle: { oracle($0, $1) == .eq },
file: file, line: line)
_checkComparable(instances, oracle: oracle, file: file, line: line)
}
public func checkComparable<T : Comparable>(
expected: ExpectedComparisonResult, _ lhs: T, _ rhs: T,
file: StaticString = #file, line: UInt = #line
) {
checkComparable(
[lhs, rhs],
oracle: { [[ .eq, expected], [ expected.flip(), .eq]][$0][$1] },
file: file, line: line)
}
/// Same as `checkComparable(_:oracle:file:line:)` but doesn't check
/// `Equatable` conformance. Useful for preventing duplicate testing.
public func _checkComparable<Instances: Collection>(
_ instances: Instances,
oracle: (Instances.Index, Instances.Index) -> ExpectedComparisonResult,
file: StaticString = #file, line: UInt = #line
) where Instances.Element: Comparable {
let entry = TestContext.current.push("checkComparable", file: file, line: line)
defer { TestContext.current.pop(entry) }
for i in instances.indices {
let x = instances[i]
expectFalse(
x < x,
"found 'x < x' at index \(i): \(String(reflecting: x))")
expectFalse(
x > x,
"found 'x > x' at index \(i): \(String(reflecting: x))")
expectTrue(x <= x,
"found 'x <= x' to be false at index \(i): \(String(reflecting: x))")
expectTrue(x >= x,
"found 'x >= x' to be false at index \(i): \(String(reflecting: x))")
for j in instances.indices where i != j {
let y = instances[j]
let expected = oracle(i, j)
expectEqual(
expected.flip(), oracle(j, i),
"""
bad oracle: missing antisymmetry:
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
expectEqual(
expected == .lt, x < y,
"""
x < y doesn't match oracle
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
expectEqual(
expected != .gt, x <= y,
"""
x <= y doesn't match oracle
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
expectEqual(
expected != .lt, x >= y,
"""
x >= y doesn't match oracle
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
expectEqual(
expected == .gt, x > y,
"""
x > y doesn't match oracle
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
for k in instances.indices {
let expected2 = oracle(j, k)
if expected == expected2 {
expectEqual(
expected, oracle(i, k),
"""
bad oracle: transitivity violation
x (at index \(i)): \(String(reflecting: x))
y (at index \(j)): \(String(reflecting: y))
z (at index \(k)): \(String(reflecting: instances[k]))
""")
}
}
}
}
}
@@ -0,0 +1,116 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibUnittest
public func checkEquatable<Instance: Equatable>(
equivalenceClasses: [[Instance]],
file: StaticString = #file,
line: UInt = #line
) {
let instances = equivalenceClasses.flatMap { $0 }
let oracle = equivalenceClasses.indices.flatMap { i in repeatElement(i, count: equivalenceClasses[i].count) }
checkEquatable(instances, oracle: { oracle[$0] == oracle[$1] }, file: file, line: line)
}
public func checkEquatable<C: Collection>(
_ instances: C,
oracle: (C.Index, C.Index) -> Bool,
file: StaticString = #file,
line: UInt = #line
) where C.Element: Equatable {
let indices = Array(instances.indices)
checkEquatable(
Array(instances),
oracle: { oracle(indices[$0], indices[$1]) },
file: file, line: line)
}
public func checkEquatable<T : Equatable>(
expectedEqual: Bool, _ lhs: T, _ rhs: T,
file: StaticString = #file, line: UInt = #line
) {
checkEquatable(
[lhs, rhs],
oracle: { expectedEqual || $0 == $1 },
file: file, line: line)
}
public func checkEquatable<Instance: Equatable>(
_ instances: [Instance],
oracle: (Int, Int) -> Bool,
file: StaticString = #file,
line: UInt = #line
) {
let entry = TestContext.current.push("checkEquatable", file: file, line: line)
defer { TestContext.current.pop(entry) }
// For each index (which corresponds to an instance being tested) track the
// set of equal instances.
var transitivityScoreboard: [Box<Set<Int>>] = instances.map { _ in Box([]) }
for i in instances.indices {
let x = instances[i]
expectTrue(oracle(i, i),
"bad oracle: broken reflexivity at index \(i)")
for j in instances.indices {
let y = instances[j]
let expectedXY = oracle(i, j)
expectEqual(oracle(j, i), expectedXY,
"bad oracle: broken symmetry between indices \(i), \(j)")
let actualXY = (x == y)
expectEqual(
actualXY, expectedXY,
"""
Elements \((expectedXY
? "expected equal, found not equal"
: "expected not equal, found equal")):
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
// Not-equal is an inverse of equal.
expectNotEqual(
x != y, actualXY,
"""
`!=` returns the same result as `==`:
lhs (at index \(i)): \(String(reflecting: x))
rhs (at index \(j)): \(String(reflecting: y))
""")
// Check transitivity of the predicate represented by the oracle.
// If we are adding the instance `j` into an equivalence set, check that
// it is equal to every other instance in the set.
if expectedXY && i < j && transitivityScoreboard[i].value.insert(j).inserted {
if transitivityScoreboard[i].value.count == 1 {
transitivityScoreboard[i].value.insert(i)
}
for k in transitivityScoreboard[i].value {
expectTrue(
oracle(j, k),
"""
bad oracle: transitivity violation
x (at index \(i)): \(String(reflecting: x))
y (at index \(j)): \(String(reflecting: y))
z (at index \(k)): \(String(reflecting: instances[k]))
""")
// No need to check equality between actual values, we will check
// them with the checks above.
}
precondition(transitivityScoreboard[j].value.isEmpty)
transitivityScoreboard[j] = transitivityScoreboard[i]
}
}
}
}
@@ -0,0 +1,124 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibUnittest
/// Produce an integer hash value for `value` by feeding it to a dedicated
/// `Hasher`. This is always done by calling the `hash(into:)` method.
/// If a non-nil `seed` is given, it is used to perturb the hasher state;
/// this is useful for resolving accidental hash collisions.
private func _hash<H: Hashable>(_ value: H, seed: Int? = nil) -> Int {
var hasher = Hasher()
if let seed = seed {
hasher.combine(seed)
}
hasher.combine(value)
return hasher.finalize()
}
/// Test that the elements of `equivalenceClasses` consist of instances that
/// satisfy the semantic requirements of `Hashable`, with each group defining
/// a distinct equivalence class under `==`.
public func checkHashable<Instance: Hashable>(
equivalenceClasses: [[Instance]],
file: StaticString = #file, line: UInt = #line
) {
let instances = equivalenceClasses.flatMap { $0 }
// oracle[i] is the index of the equivalence class that contains instances[i].
let oracle = equivalenceClasses.indices.flatMap { i in repeatElement(i, count: equivalenceClasses[i].count) }
checkHashable(
instances,
equalityOracle: { oracle[$0] == oracle[$1] },
file: file, line: line)
}
public func checkHashable<T : Hashable>(
expectedEqual: Bool, _ lhs: T, _ rhs: T,
file: StaticString = #file, line: UInt = #line
) {
checkHashable(
[lhs, rhs], equalityOracle: { expectedEqual || $0 == $1 }, file: file, line: line)
}
/// Test that the elements of `instances` satisfy the semantic requirements of
/// `Hashable`, using `equalityOracle` to generate equality and hashing
/// expectations from pairs of positions in `instances`.
public func checkHashable<Instances: Collection>(
_ instances: Instances,
equalityOracle: (Instances.Index, Instances.Index) -> Bool,
file: StaticString = #file, line: UInt = #line
) where Instances.Element: Hashable {
checkEquatable(instances, oracle: equalityOracle, file: file, line: line)
_checkHashable(instances, equalityOracle: equalityOracle, file: file, line: line)
}
/// Same as `checkHashable(_:equalityOracle:file:line:)` but doesn't check
/// `Equatable` conformance. Useful for preventing duplicate testing.
public func _checkHashable<Instances: Collection>(
_ instances: Instances,
equalityOracle: (Instances.Index, Instances.Index) -> Bool,
file: StaticString = #file, line: UInt = #line
) where Instances.Element: Hashable {
let entry = TestContext.current.push("checkHashable", file: file, line: line)
defer { TestContext.current.pop(entry) }
for i in instances.indices {
let x = instances[i]
for j in instances.indices {
let y = instances[j]
let expected = equalityOracle(i, j)
if expected {
expectEqual(
_hash(x), _hash(y),
"""
hash(into:) expected to match, found to differ:
lhs (at index \(i)): \(x)
rhs (at index \(j)): \(y)
""")
expectEqual(
x.hashValue, y.hashValue,
"""
hashValue expected to match, found to differ
lhs (at index \(i)): \(x)
rhs (at index \(j)): \(y)
""")
expectEqual(
x._rawHashValue(seed: 0), y._rawHashValue(seed: 0),
"""
_rawHashValue(seed:) expected to match, found to differ
lhs (at index \(i)): \(x)
rhs (at index \(j)): \(y)
""")
} else {
// Try a few different seeds; at least one of them should discriminate
// between the hashes. It is extremely unlikely this check will fail
// all ten attempts, unless the type's hash encoding is not unique,
// or unless the hash equality oracle is wrong.
expectTrue(
(0 ..< 10).contains { _hash(x, seed: $0) != _hash(y, seed: $0) },
"""
hash(into:) expected to differ, found to match
lhs (at index \(i)): \(x)
rhs (at index \(j)): \(y)
""")
expectTrue(
(0 ..< 10).contains { i in
x._rawHashValue(seed: i) != y._rawHashValue(seed: i)
},
"""
_rawHashValue(seed:) expected to differ, found to match
lhs (at index \(i)): \(x)
rhs (at index \(j)): \(y)
""")
}
}
}
}
@@ -0,0 +1,96 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
// FIXME: Port all of the collection validation tests from the Swift compiler codebase.
import XCTest
// FIXME: Port the collection validation tests from the Swift compiler codebase.
public func checkSequence<S: Sequence, Expected: Sequence>(
_ sequenceGenerator: () -> S,
expectedContents: Expected,
file: StaticString = #file,
line: UInt = #line
) where S.Element == Expected.Element, S.Element: Equatable {
checkSequence(
sequenceGenerator,
expectedContents: expectedContents,
by: ==,
file: file,
line: line)
}
public func checkSequence<S: Sequence, Expected: Sequence>(
_ sequenceGenerator: () -> S,
expectedContents: Expected,
by areEquivalent: (S.Element, S.Element) -> Bool,
file: StaticString = #file,
line: UInt = #line
) where S.Element == Expected.Element {
let entry = TestContext.current.push("checkSequence", file: file, line: line)
defer { TestContext.current.pop(entry) }
let expectedContents = Array(expectedContents)
do {
let seq = sequenceGenerator()
let underestimatedCount = seq.underestimatedCount
expectLessThanOrEqual(underestimatedCount, expectedContents.count)
expectGreaterThanOrEqual(underestimatedCount, 0)
}
// Check contiguous storage.
do {
let seq = sequenceGenerator()
let r: Int? = seq.withContiguousStorageIfAvailable { buffer in
expectEquivalentElements(buffer, expectedContents, by: areEquivalent)
return 42
}
expectTrue(r == 42 || r == nil)
}
do {
let seq = sequenceGenerator()
var it = seq.makeIterator()
var i = 0
while i < expectedContents.count {
expectEquivalent(it.next(), expectedContents[i], by: areEquivalent)
i += 1
}
expectNil(it.next())
expectNil(it.next())
}
do {
let seq = sequenceGenerator()
let underestimatedCount = seq.underestimatedCount
var state: (it: S.Iterator, count: Int)!
var array = Array<S.Element>(
unsafeUninitializedCapacity: underestimatedCount
) { buffer, count in
state = seq._copyContents(initializing: buffer)
count = state.count
}
expectEqual(state.count, underestimatedCount)
expectEquivalentElements(
array,
expectedContents[..<state.count],
by: areEquivalent)
while let item = state.it.next() {
array.append(item)
}
expectEquivalentElements(array, expectedContents, by: areEquivalent)
}
}
@@ -0,0 +1,143 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
/// A minimal implementation of `BidirectionalCollection` with extra checks.
public struct MinimalBidirectionalCollection<Element> {
internal var _core: _MinimalCollectionCore<Element>
public let timesMakeIteratorCalled = ResettableValue(0)
public let timesUnderestimatedCountCalled = ResettableValue(0)
public let timesStartIndexCalled = ResettableValue(0)
public let timesEndIndexCalled = ResettableValue(0)
public let timesRangeChecksCalled = ResettableValue(0)
public let timesIndexAfterCalled = ResettableValue(0)
public let timesIndexBeforeCalled = ResettableValue(0)
public let timesSubscriptCalled = ResettableValue(0)
public let timesRangeSubscriptCalled = ResettableValue(0)
public init<S: Sequence>(
_ elements: S,
context: TestContext = TestContext.current,
underestimatedCount: UnderestimatedCountBehavior = .value(0)
) where S.Element == Element {
self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount)
}
var _context: TestContext {
_core.context
}
}
extension MinimalBidirectionalCollection: Sequence {
public typealias Iterator = MinimalIterator<Element>
public func makeIterator() -> MinimalIterator<Element> {
timesMakeIteratorCalled.increment()
return MinimalIterator(_core.elements)
}
public var underestimatedCount: Int {
timesUnderestimatedCountCalled.increment()
return _core.underestimatedCount
}
}
extension MinimalBidirectionalCollection: BidirectionalCollection {
public typealias Index = MinimalIndex
public typealias SubSequence = Slice<MinimalBidirectionalCollection>
public typealias Indices = DefaultIndices<MinimalBidirectionalCollection>
public var startIndex: MinimalIndex {
timesStartIndexCalled.increment()
return _core.startIndex
}
public var endIndex: MinimalIndex {
timesEndIndexCalled.increment()
return _core.endIndex
}
public var isEmpty: Bool {
// Pretend this is implemented as `startIndex == endIndex`.
timesStartIndexCalled.increment()
timesEndIndexCalled.increment()
return _core.isEmpty
}
public var count: Int {
// Pretend this is implemented by counting elements using `index(after:)`.
let result = _core.count
timesIndexAfterCalled.increment(by: result)
return result
}
public func _failEarlyRangeCheck(
_ index: MinimalIndex,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(
_ range: Range<MinimalIndex>,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(range, bounds: bounds)
}
public func index(after i: MinimalIndex) -> MinimalIndex {
timesIndexAfterCalled.increment()
return _core.index(after: i)
}
public func index(before i: MinimalIndex) -> MinimalIndex {
timesIndexBeforeCalled.increment()
return _core.index(before: i)
}
public func distance(from start: MinimalIndex, to end: MinimalIndex)
-> Int {
// Pretend this is implemented by counting elements using `index(after:)`/`index(before:).
let result = _core.distance(from: start, to: end)
if result >= 0 {
timesIndexAfterCalled.increment(by: result)
} else {
timesIndexBeforeCalled.increment(by: -result)
}
return result
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
// Pretend this is implemented by iterating elements using `index(after:)`/`index(before:)`.
if n >= 0 {
timesIndexAfterCalled.increment(by: n)
} else {
timesIndexBeforeCalled.increment(by: -n)
}
return _core.index(i, offsetBy: n)
}
public subscript(i: MinimalIndex) -> Element {
timesSubscriptCalled.increment()
return _core[i]
}
public subscript(bounds: Range<MinimalIndex>) -> SubSequence {
timesRangeSubscriptCalled.increment()
_core.assertValid(bounds)
return Slice(base: self, bounds: bounds)
}
}
@@ -0,0 +1,137 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
/// A minimal implementation of `Collection` with extra checks.
public struct MinimalCollection<Element> {
internal var _core: _MinimalCollectionCore<Element>
public let timesMakeIteratorCalled = ResettableValue(0)
public let timesUnderestimatedCountCalled = ResettableValue(0)
public let timesStartIndexCalled = ResettableValue(0)
public let timesEndIndexCalled = ResettableValue(0)
public let timesRangeChecksCalled = ResettableValue(0)
public let timesIndexAfterCalled = ResettableValue(0)
public let timesSubscriptCalled = ResettableValue(0)
public let timesRangeSubscriptCalled = ResettableValue(0)
public init<S: Sequence>(
_ elements: S,
context: TestContext = TestContext.current,
underestimatedCount: UnderestimatedCountBehavior = .value(0)
) where S.Element == Element {
self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount)
}
var _context: TestContext {
_core.context
}
}
extension MinimalCollection: Sequence {
public typealias Iterator = MinimalIterator<Element>
public func makeIterator() -> MinimalIterator<Element> {
timesMakeIteratorCalled.increment()
return MinimalIterator(_core.elements)
}
public var underestimatedCount: Int {
timesUnderestimatedCountCalled.increment()
return _core.underestimatedCount
}
}
extension MinimalCollection: Collection {
public typealias Index = MinimalIndex
public typealias SubSequence = Slice<Self>
public typealias Indices = DefaultIndices<Self>
public var startIndex: MinimalIndex {
timesStartIndexCalled.increment()
return _core.startIndex
}
public var endIndex: MinimalIndex {
timesEndIndexCalled.increment()
return _core.endIndex
}
public var isEmpty: Bool {
// Pretend this is implemented as `startIndex == endIndex`.
timesStartIndexCalled.increment()
timesEndIndexCalled.increment()
return _core.isEmpty
}
public var count: Int {
// Pretend this is implemented by counting elements using `index(after:)`.
let result = _core.count
timesIndexAfterCalled.increment(by: result)
return result
}
public func _failEarlyRangeCheck(
_ index: MinimalIndex,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(
_ range: Range<MinimalIndex>,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(range, bounds: bounds)
}
public func index(after i: MinimalIndex) -> MinimalIndex {
timesIndexAfterCalled.increment()
return _core.index(after: i)
}
public func distance(from start: MinimalIndex, to end: MinimalIndex)
-> Int {
// Pretend this is implemented by counting elements using `index(after:)`.
expectTrue(
start <= end,
"Only BidirectionalCollections can have end come before start",
trapping: true)
let result = _core.distance(from: start, to: end)
timesIndexAfterCalled.increment(by: result)
return result
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
// Pretend this is implemented by iterating elements using `index(after:)`.
expectTrue(
n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount",
trapping: true)
timesIndexAfterCalled.increment(by: n)
return _core.index(i, offsetBy: n)
}
public subscript(i: MinimalIndex) -> Element {
timesSubscriptCalled.increment()
return _core[i]
}
public subscript(bounds: Range<MinimalIndex>) -> SubSequence {
timesRangeSubscriptCalled.increment()
_core.assertValid(bounds)
return Slice(base: self, bounds: bounds)
}
}
@@ -0,0 +1,756 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
public class MinimalDecoder {
public typealias Value = MinimalEncoder.Value
typealias _Key = MinimalEncoder._Key
public private(set) var userInfo: [CodingUserInfoKey: Any]
public init(userInfo: [CodingUserInfoKey: Any] = [:]) {
self.userInfo = userInfo
}
public func decode<T: Decodable>(_ input: Value, as type: T.Type) throws -> T {
let decoder = Decoder(base: self, parent: nil, input: input, key: nil)
defer {
decoder.finalize()
}
return try T(from: decoder)
}
public static func decode<T: Decodable>(_ input: Value, as type: T.Type) throws -> T {
let decoder = MinimalDecoder()
return try decoder.decode(input, as: T.self)
}
}
protocol _MinimalDecoderContainer: AnyObject {
var base: MinimalDecoder { get }
var parent: _MinimalDecoderContainer? { get }
var key: CodingKey? { get }
var isValid: Bool { get }
func finalize()
}
extension _MinimalDecoderContainer {
var codingPath: [CodingKey] {
expectTrue(isValid, "Container isn't valid", trapping: true)
var path: [CodingKey] = []
var encoder: _MinimalDecoderContainer? = self
while let e = encoder {
if let key = e.key { path.append(key) }
encoder = e.parent
}
path.reverse()
return path
}
var userInfo: [CodingUserInfoKey: Any] {
expectTrue(isValid, "Container isn't valid", trapping: true)
return base.userInfo
}
}
extension DecodingError {
internal static func _typeMismatch(
at path: [CodingKey],
expectation: Any.Type,
reality: MinimalDecoder.Value
) -> DecodingError {
let description = "Expected to decode \(expectation) but found `\(reality.typeDescription))`."
return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description))
}
}
extension MinimalDecoder {
final class Decoder {
typealias Value = MinimalEncoder.Value
unowned let base: MinimalDecoder
unowned let parent: _MinimalDecoderContainer?
let key: CodingKey?
var input: Value
var isValid = true
var pendingContainer: _MinimalDecoderContainer?
init(base: MinimalDecoder, parent: _MinimalDecoderContainer?, input: Value, key: CodingKey?) {
self.base = base
self.parent = parent
self.key = key
self.input = input
}
}
}
extension MinimalDecoder.Decoder: _MinimalDecoderContainer {
func finalize() {
expectTrue(isValid, "Container isn't valid", trapping: true)
isValid = false
}
}
extension MinimalDecoder.Decoder: Decoder {
func container<Key: CodingKey>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(pendingContainer, "Cannot extract multiple containers", trapping: true)
guard case let .dictionary(d) = input else {
throw DecodingError._typeMismatch(at: codingPath, expectation: [String: Value].self, reality: input)
}
let keyed = MinimalDecoder.KeyedContainer<Key>(base: base, parent: parent, input: d, key: key)
pendingContainer = keyed
return .init(keyed)
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(pendingContainer, "Cannot extract multiple containers", trapping: true)
guard case let .array(a) = input else {
throw DecodingError._typeMismatch(at: codingPath, expectation: [Value].self, reality: input)
}
let unkeyed = MinimalDecoder.UnkeyedContainer(base: base, parent: parent, input: a, key: nil)
pendingContainer = unkeyed
return unkeyed
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(pendingContainer, "Cannot extract multiple containers", trapping: true)
let single = MinimalDecoder.SingleValueContainer(base: base, parent: parent, input: input, key: nil)
pendingContainer = single
return single
}
}
extension MinimalDecoder {
final class KeyedContainer<Key: CodingKey> {
typealias Value = MinimalEncoder.Value
unowned let base: MinimalDecoder
unowned let parent: _MinimalDecoderContainer?
let key: CodingKey?
var input: [String: Value]
var isValid = true
var pendingContainer: AnyObject?
init(base: MinimalDecoder, parent: _MinimalDecoderContainer?, input: [String: Value], key: CodingKey?) {
self.base = base
self.parent = parent
self.key = key
self.input = input
}
func commitPendingContainer() {
expectTrue(self.isValid, "Container isn't valid", trapping: true)
guard let c = pendingContainer else { return }
self.pendingContainer = nil
let container = c as! _MinimalDecoderContainer
container.finalize()
}
}
}
extension MinimalDecoder.KeyedContainer: _MinimalDecoderContainer {
func finalize() {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
isValid = false
}
}
extension MinimalDecoder.KeyedContainer: KeyedDecodingContainerProtocol {
var allKeys: [Key] {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
return input.keys.compactMap { Key(stringValue: $0) }
}
func contains(_ key: Key) -> Bool {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
return input[key.stringValue] != nil
}
func _decode<Key: CodingKey>(key: Key) throws -> Value {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
guard let value = input[key.stringValue] else {
let context = DecodingError.Context(
codingPath: codingPath + [key],
debugDescription: "Key not found (\"\(key.stringValue)\")")
throw DecodingError.keyNotFound(key, context)
}
return value
}
func _decode<T>(_ type: T.Type, forKey key: Key, _ extract: (Value) -> T?) throws -> T {
let value = try _decode(key: key)
guard let v = extract(value) else {
throw DecodingError._typeMismatch(at: codingPath + [key], expectation: T.self, reality: value)
}
return v
}
func decodeNil(forKey key: Key) throws -> Bool {
let value = try _decode(key: key)
return value == .null
}
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
try _decode(type, forKey: key) { input in
guard case let .bool(v) = input else { return nil }
return v
}
}
func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
try _decode(type, forKey: key) { input in
guard case let .int(v) = input else { return nil }
return v
}
}
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
try _decode(type, forKey: key) { input in
guard case let .int8(v) = input else { return nil }
return v
}
}
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
try _decode(type, forKey: key) { input in
guard case let .int16(v) = input else { return nil }
return v
}
}
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
try _decode(type, forKey: key) { input in
guard case let .int32(v) = input else { return nil }
return v
}
}
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
try _decode(type, forKey: key) { input in
guard case let .int64(v) = input else { return nil }
return v
}
}
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
try _decode(type, forKey: key) { input in
guard case let .uint(v) = input else { return nil }
return v
}
}
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
try _decode(type, forKey: key) { input in
guard case let .uint8(v) = input else { return nil }
return v
}
}
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
try _decode(type, forKey: key) { input in
guard case let .uint16(v) = input else { return nil }
return v
}
}
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
try _decode(type, forKey: key) { input in
guard case let .uint32(v) = input else { return nil }
return v
}
}
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
try _decode(type, forKey: key) { input in
guard case let .uint64(v) = input else { return nil }
return v
}
}
func decode(_ type: String.Type, forKey key: Key) throws -> String {
try _decode(type, forKey: key) { input in
guard case let .string(v) = input else { return nil }
return v
}
}
func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
try _decode(type, forKey: key) { input in
guard case let .double(v) = input else { return nil }
return v
}
}
func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
try _decode(type, forKey: key) { input in
guard case let .float(v) = input else { return nil }
return v
}
}
func decode<T: Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
let value = try _decode(key: key)
let decoder = MinimalDecoder.Decoder(base: base, parent: self, input: value, key: key)
pendingContainer = decoder
defer {
expectIdentical(pendingContainer, decoder, trapping: true)
commitPendingContainer()
}
return try T(from: decoder)
}
func nestedContainer<NestedKey: CodingKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey> {
let value = try _decode(key: key)
guard case let .dictionary(v) = value else {
throw DecodingError._typeMismatch(at: codingPath + [key],
expectation: [String: Value].self,
reality: value)
}
let nested = MinimalDecoder.KeyedContainer<NestedKey>(base: base, parent: self, input: v, key: key)
pendingContainer = nested
return .init(nested)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
let value = try _decode(key: key)
guard case let .array(v) = value else {
throw DecodingError._typeMismatch(at: codingPath + [key],
expectation: [String: Value].self,
reality: value)
}
let nested = MinimalDecoder.UnkeyedContainer(base: base, parent: self, input: v, key: key)
pendingContainer = nested
return nested
}
func superDecoder() throws -> Decoder {
let value = try _decode(key: MinimalDecoder._Key.super)
let nested = MinimalDecoder.Decoder(base: base, parent: self, input: value, key: key)
pendingContainer = nested
return nested
}
func superDecoder(forKey key: Key) throws -> Decoder {
let value = try _decode(key: key)
let nested = MinimalDecoder.Decoder(base: base, parent: self, input: value, key: key)
pendingContainer = nested
return nested
}
}
extension MinimalDecoder {
class UnkeyedContainer {
typealias Value = MinimalEncoder.Value
unowned let base: MinimalDecoder
unowned let parent: _MinimalDecoderContainer?
let key: CodingKey?
var input: [Value]
var isValid = true
var pendingContainer: AnyObject?
var index: Int = 0
init(base: MinimalDecoder, parent: _MinimalDecoderContainer?, input: [Value], key: CodingKey?) {
self.base = base
self.parent = parent
self.key = key
self.input = input
}
func commitPendingContainer() {
expectTrue(self.isValid, "Container isn't valid", trapping: true)
guard let c = pendingContainer else { return }
self.pendingContainer = nil
let container = c as! _MinimalDecoderContainer
container.finalize()
}
}
}
extension MinimalDecoder.UnkeyedContainer: _MinimalDecoderContainer {
func finalize() {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
isValid = false
}
}
extension MinimalDecoder.UnkeyedContainer: UnkeyedDecodingContainer {
typealias _Key = MinimalDecoder._Key
var count: Int? {
expectTrue(isValid, "Container isn't valid", trapping: true)
return input.count
}
var isAtEnd: Bool {
expectTrue(isValid, "Container isn't valid", trapping: true)
return index == input.count
}
var currentIndex: Int {
expectTrue(isValid, "Container isn't valid", trapping: true)
return index
}
func _decodeNext<T>(_ type: T.Type) throws -> Value {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
guard index < input.count else {
let context = DecodingError.Context(
codingPath: codingPath + [_Key(index)],
debugDescription: "Unkeyed container is at end")
throw DecodingError.valueNotFound(T.self, context)
}
let value = input[index]
index += 1
return value
}
func _decodeNext<T>(_ type: T.Type = T.self, _ extract: (Value) -> T?) throws -> T {
let value = try _decodeNext(type)
guard let v = extract(value) else {
throw DecodingError._typeMismatch(at: codingPath + [_Key(index - 1)],
expectation: T.self,
reality: value)
}
return v
}
func decodeNil() throws -> Bool {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
guard index < input.count else {
let context = DecodingError.Context(
codingPath: codingPath + [_Key(index)],
debugDescription: "Unkeyed container is at end")
throw DecodingError.valueNotFound(Any?.self, context)
}
let value = input[index]
guard value == .null else { return false }
index += 1
return true
}
func decode(_ type: Bool.Type) throws -> Bool {
try _decodeNext() { value in
guard case let .bool(v) = value else { return nil }
return v
}
}
func decode(_ type: Float.Type) throws -> Float {
try _decodeNext() { value in
guard case let .float(v) = value else { return nil }
return v
}
}
func decode(_ type: Double.Type) throws -> Double {
try _decodeNext() { value in
guard case let .double(v) = value else { return nil }
return v
}
}
func decode(_ type: Int.Type) throws -> Int {
try _decodeNext() { value in
guard case let .int(v) = value else { return nil }
return v
}
}
func decode(_ type: Int8.Type) throws -> Int8 {
try _decodeNext() { value in
guard case let .int8(v) = value else { return nil }
return v
}
}
func decode(_ type: Int16.Type) throws -> Int16 {
try _decodeNext() { value in
guard case let .int16(v) = value else { return nil }
return v
}
}
func decode(_ type: Int32.Type) throws -> Int32 {
try _decodeNext() { value in
guard case let .int32(v) = value else { return nil }
return v
}
}
func decode(_ type: Int64.Type) throws -> Int64 {
try _decodeNext() { value in
guard case let .int64(v) = value else { return nil }
return v
}
}
func decode(_ type: UInt.Type) throws -> UInt {
try _decodeNext() { value in
guard case let .uint(v) = value else { return nil }
return v
}
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
try _decodeNext() { value in
guard case let .uint8(v) = value else { return nil }
return v
}
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
try _decodeNext() { value in
guard case let .uint16(v) = value else { return nil }
return v
}
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
try _decodeNext() { value in
guard case let .uint32(v) = value else { return nil }
return v
}
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
try _decodeNext() { value in
guard case let .uint64(v) = value else { return nil }
return v
}
}
func decode(_ type: String.Type) throws -> String {
try _decodeNext() { value in
guard case let .string(v) = value else { return nil }
return v
}
}
func decode<T: Decodable>(_ type: T.Type) throws -> T {
let key = _Key(index)
let value = try _decodeNext(T.self)
let decoder = MinimalDecoder.Decoder(base: base, parent: self, input: value, key: key)
pendingContainer = decoder
defer {
expectIdentical(pendingContainer, decoder, trapping: true)
commitPendingContainer()
}
return try T(from: decoder)
}
func nestedContainer<NestedKey: CodingKey>(
keyedBy type: NestedKey.Type
) throws -> KeyedDecodingContainer<NestedKey> {
let key = _Key(index)
let value = try _decodeNext([String: Value].self)
guard case let .dictionary(v) = value else {
throw DecodingError._typeMismatch(at: codingPath + [key],
expectation: [String: Value].self,
reality: value)
}
let nested = MinimalDecoder.KeyedContainer<NestedKey>(base: base, parent: parent, input: v, key: key)
pendingContainer = nested
return .init(nested)
}
func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
let key = _Key(index)
let value = try _decodeNext([Value].self)
guard case let .array(v) = value else {
throw DecodingError._typeMismatch(at: codingPath + [key],
expectation: [Value].self,
reality: value)
}
let nested = MinimalDecoder.UnkeyedContainer(base: base, parent: parent, input: v, key: key)
pendingContainer = nested
return nested
}
func superDecoder() throws -> Decoder {
let key = _Key(index)
let value = try _decodeNext(Any.self)
let nested = MinimalDecoder.Decoder(base: base, parent: self, input: value, key: key)
pendingContainer = nested
return nested
}
}
extension MinimalDecoder {
class SingleValueContainer {
typealias Value = MinimalEncoder.Value
unowned let base: MinimalDecoder
unowned let parent: _MinimalDecoderContainer?
let key: CodingKey?
var input: Value
var isValid = true
var done = false
init(base: MinimalDecoder, parent: _MinimalDecoderContainer?, input: Value, key: CodingKey?) {
self.base = base
self.parent = parent
self.key = key
self.input = input
}
}
}
extension MinimalDecoder.SingleValueContainer: _MinimalDecoderContainer {
func finalize() {
expectTrue(isValid, "Container isn't valid")
isValid = false
}
}
extension MinimalDecoder.SingleValueContainer: SingleValueDecodingContainer {
func _decodeNext<T>(_ type: T.Type = T.self, _ extract: (Value) -> T?) throws -> T {
expectTrue(isValid, "Container isn't valid")
expectFalse(done, "Cannot decode multiple values from a single-value container")
guard let v = extract(input) else {
throw DecodingError._typeMismatch(at: codingPath,
expectation: T.self,
reality: input)
}
done = true
return v
}
func decodeNil() -> Bool {
expectTrue(isValid, "Container isn't valid")
expectFalse(done, "Cannot decode multiple values from a single-value container")
guard input == .null else { return false }
done = true
return true
}
func decode(_ type: Bool.Type) throws -> Bool {
try _decodeNext { value in
guard case let .bool(v) = value else { return nil }
return v
}
}
func decode(_ type: Int.Type) throws -> Int {
try _decodeNext { value in
guard case let .int(v) = value else { return nil }
return v
}
}
func decode(_ type: Int8.Type) throws -> Int8 {
try _decodeNext { value in
guard case let .int8(v) = value else { return nil }
return v
}
}
func decode(_ type: Int16.Type) throws -> Int16 {
try _decodeNext { value in
guard case let .int16(v) = value else { return nil }
return v
}
}
func decode(_ type: Int32.Type) throws -> Int32 {
try _decodeNext { value in
guard case let .int32(v) = value else { return nil }
return v
}
}
func decode(_ type: Int64.Type) throws -> Int64 {
try _decodeNext { value in
guard case let .int64(v) = value else { return nil }
return v
}
}
func decode(_ type: UInt.Type) throws -> UInt {
try _decodeNext { value in
guard case let .uint(v) = value else { return nil }
return v
}
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
try _decodeNext { value in
guard case let .uint8(v) = value else { return nil }
return v
}
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
try _decodeNext { value in
guard case let .uint16(v) = value else { return nil }
return v
}
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
try _decodeNext { value in
guard case let .uint32(v) = value else { return nil }
return v
}
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
try _decodeNext { value in
guard case let .uint64(v) = value else { return nil }
return v
}
}
func decode(_ type: Float.Type) throws -> Float {
try _decodeNext { value in
guard case let .float(v) = value else { return nil }
return v
}
}
func decode(_ type: Double.Type) throws -> Double {
try _decodeNext { value in
guard case let .double(v) = value else { return nil }
return v
}
}
func decode(_ type: String.Type) throws -> String {
try _decodeNext { value in
guard case let .string(v) = value else { return nil }
return v
}
}
func decode<T: Decodable>(_ type: T.Type) throws -> T {
expectTrue(isValid, "Container isn't valid")
expectFalse(done, "Cannot decode multiple values from a single-value container")
let decoder = MinimalDecoder.Decoder(base: base, parent: self, input: input, key: nil)
defer {
done = true
decoder.finalize()
}
return try T(from: decoder)
}
}
@@ -0,0 +1,716 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A Plist-style encoder that attempts to enforce a strict interpretation of
/// the `Encodable` protocol requirements. The encoded value is of an enum type
/// that exactly reflects the values encoded, allowing easy matching of
/// actual vs expected outputs.
///
/// This encoder verifies that `encoder(to:)` implementations do not keep
/// containers alive beyond their expected lifetime.
///
/// FIXME: Fix error reporting. We ought to throw errors instead of trapping
/// on validation problems, and we should include context information to help
/// isolating the problem.
public class MinimalEncoder {
public enum Value: Hashable {
case null
case bool(Bool)
case int(Int)
case int8(Int8)
case int16(Int16)
case int32(Int32)
case int64(Int64)
case uint(UInt)
case uint8(UInt8)
case uint16(UInt16)
case uint32(UInt32)
case uint64(UInt64)
case float(Float)
case double(Double)
case string(String)
case array([Value])
case dictionary([String: Value])
}
var userInfo: [CodingUserInfoKey: Any]
public init(userInfo: [CodingUserInfoKey: Any] = [:]) {
self.userInfo = userInfo
}
public func encode<T: Encodable>(_ value: T) throws -> Value {
let encoder = Encoder(base: self, parent: nil, key: nil)
return try encoder._encode(value, key: nil)
}
public static func encode<T: Encodable>(_ value: T) throws -> Value {
let base = MinimalEncoder()
return try base.encode(value)
}
}
extension MinimalEncoder {
struct _Key: CodingKey {
var stringValue: String
var intValue: Int?
static let `super` = Self("super")
init(_ string: String) {
self.stringValue = string
self.intValue = nil
}
init(_ index: Int) {
self.stringValue = "Index \(index)"
self.intValue = index
}
init?(stringValue: String) {
self.init(stringValue)
}
init?(intValue: Int) {
self.init(intValue)
}
}
}
extension MinimalEncoder.Value: CustomStringConvertible {
func _description(prefix: String, indent: String) -> String {
switch self {
case .null: return ".null"
case .bool(let v): return ".bool(\(v))"
case .int(let v): return ".int(\(v))"
case .int8(let v): return ".int8(\(v))"
case .int16(let v): return ".int16(\(v))"
case .int32(let v): return ".int32(\(v))"
case .int64(let v): return ".int64(\(v))"
case .uint(let v): return ".uint(\(v))"
case .uint8(let v): return ".uint8(\(v))"
case .uint16(let v): return ".uint16(\(v))"
case .uint32(let v): return ".uint32(\(v))"
case .uint64(let v): return ".uint64(\(v))"
case .float(let v): return ".float(\(v))"
case .double(let v): return ".double(\(v))"
case .string(let v): return ".string(\(String(reflecting: v)))"
case .array(let value):
if value.count == 0 { return ".array([])" }
var result = ".array([\n"
for v in value {
result += prefix
result += indent
result += v._description(prefix: prefix + indent, indent: indent)
result += ",\n"
}
result += prefix + "])"
return result
case .dictionary(let value):
if value.count == 0 { return ".dictionary([:])" }
var result = ".dictionary([\n"
for (k, v) in value.sorted(by: { $0.key < $1.key }) {
result += prefix
result += indent
result += String(reflecting: k)
result += ": "
result += v._description(prefix: prefix + indent, indent: indent)
result += ",\n"
}
result += prefix + "])"
return result
}
}
public var description: String {
self._description(prefix: "", indent: " ")
}
}
extension MinimalDecoder.Value {
public var typeDescription: String {
switch self {
case .null: return ".null"
case .bool(_): return ".bool"
case .int(_): return ".int"
case .int8(_): return ".int8"
case .int16(_): return ".int16"
case .int32(_): return ".int32"
case .int64(_): return ".int64"
case .uint(_): return ".uint"
case .uint8(_): return ".uint8"
case .uint16(_): return ".uint16"
case .uint32(_): return ".uint32"
case .uint64(_): return ".uint64"
case .float(_): return ".float"
case .double(_): return ".double"
case .string(_): return ".string"
case .array(_): return ".array"
case .dictionary(_): return ".dictionary"
}
}
}
protocol _MinimalEncoderContainer: AnyObject {
var base: MinimalEncoder { get }
var parent: _MinimalEncoderContainer? { get }
var key: CodingKey? { get }
var isValid: Bool { get }
func finalize() -> MinimalEncoder.Value?
}
extension _MinimalEncoderContainer {
var codingPath: [CodingKey] {
expectTrue(isValid, "Container isn't valid", trapping: true)
var path: [CodingKey] = []
var encoder: _MinimalEncoderContainer? = self
while let e = encoder {
if let key = e.key { path.append(key) }
encoder = e.parent
}
path.reverse()
return path
}
func _encode<T: Encodable>(_ value: T, key: CodingKey?) throws -> MinimalEncoder.Value {
expectTrue(isValid, "Container isn't valid", trapping: true)
var encoder = MinimalEncoder.Encoder(base: base, parent: self, key: key)
try value.encode(to: encoder)
expectTrue(isKnownUniquelyReferenced(&encoder), "\(T.self).encode(to:) retained its encoder", trapping: true)
guard let result = encoder.finalize() else {
preconditionFailure("\(T.self).encode(to:) failed to encode anything")
}
return result
}
}
extension MinimalEncoder {
final class Encoder {
unowned let base: MinimalEncoder
unowned let parent: _MinimalEncoderContainer?
let key: CodingKey?
var container: _MinimalEncoderContainer?
var isValid = true
init(base: MinimalEncoder, parent: _MinimalEncoderContainer?, key: CodingKey?) {
self.base = base
self.parent = parent
self.key = key
}
}
}
extension MinimalEncoder.Encoder: _MinimalEncoderContainer {
func finalize() -> MinimalEncoder.Value? {
expectTrue(isValid, "Container isn't valid", trapping: true)
let value = container?.finalize()
isValid = false
return value
}
}
extension MinimalEncoder.Encoder: Encoder {
var userInfo: [CodingUserInfoKey: Any] { base.userInfo }
func container<Key: CodingKey>(
keyedBy type: Key.Type
) -> KeyedEncodingContainer<Key> {
expectTrue(isValid, "Encoder isn't valid", trapping: true)
expectNil(container, "Cannot extract multiple containers", trapping: true)
let keyed = MinimalEncoder.KeyedContainer<Key>(base: base, parent: self, key: nil)
self.container = keyed
return .init(keyed)
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
expectTrue(isValid, "Encoder isn't valid", trapping: true)
expectNil(container, "Cannot extract multiple containers", trapping: true)
let unkeyed = MinimalEncoder.UnkeyedContainer(base: base, parent: self, key: nil)
self.container = unkeyed
return unkeyed
}
func singleValueContainer() -> SingleValueEncodingContainer {
expectTrue(isValid, "Encoder isn't valid", trapping: true)
expectNil(container, "Cannot extract multiple containers", trapping: true)
let single = MinimalEncoder.SingleValueContainer(base: base, parent: self, key: nil)
self.container = single
return single
}
}
extension MinimalEncoder {
final class KeyedContainer<Key: CodingKey> {
unowned let base: MinimalEncoder
unowned let parent: _MinimalEncoderContainer?
var key: CodingKey?
var values: [String: Value] = [:]
var isValid = true
var pendingContainer: AnyObject?
init(base: MinimalEncoder, parent: _MinimalEncoderContainer?, key: CodingKey?) {
self.base = base
self.parent = parent
self.key = key
}
func commitPendingContainer() {
expectTrue(self.isValid, "Container isn't valid", trapping: true)
guard var c = pendingContainer else { return }
self.pendingContainer = nil
expectTrue(isKnownUniquelyReferenced(&c), "Container was retained", trapping: true)
let container = c as! _MinimalEncoderContainer
let key = container.key!
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
guard let v = container.finalize() else { preconditionFailure("Container remained empty")}
values[key.stringValue] = v
}
}
}
extension MinimalEncoder.KeyedContainer: _MinimalEncoderContainer {
func finalize() -> MinimalEncoder.Value? {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
isValid = false
return .dictionary(values)
}
}
extension MinimalEncoder.KeyedContainer: KeyedEncodingContainerProtocol {
func encodeNil(forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .null
}
func encode(_ value: Bool, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .bool(value)
}
func encode(_ value: Int, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .int(value)
}
func encode(_ value: Int8, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .int8(value)
}
func encode(_ value: Int16, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .int16(value)
}
func encode(_ value: Int32, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .int32(value)
}
func encode(_ value: Int64, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .int64(value)
}
func encode(_ value: UInt, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .uint(value)
}
func encode(_ value: UInt8, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .uint8(value)
}
func encode(_ value: UInt16, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .uint16(value)
}
func encode(_ value: UInt32, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .uint32(value)
}
func encode(_ value: UInt64, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .uint64(value)
}
func encode(_ value: Float, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .float(value)
}
func encode(_ value: Double, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .double(value)
}
func encode(_ value: String, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = .string(value)
}
func encode<T: Encodable>(_ value: T, forKey key: Key) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
values[key.stringValue] = try _encode(value, key: key)
}
func nestedContainer<NestedKey: CodingKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key
) -> KeyedEncodingContainer<NestedKey> {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
let keyed = MinimalEncoder.KeyedContainer<NestedKey>(base: base, parent: self, key: key)
pendingContainer = keyed
return .init(keyed)
}
func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key.stringValue) has already been encoded", trapping: true)
let unkeyed = MinimalEncoder.UnkeyedContainer(base: base, parent: self, key: key)
pendingContainer = unkeyed
return unkeyed
}
func superEncoder() -> Encoder {
let key = MinimalEncoder._Key.super
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key) has already been encoded", trapping: true)
let sup = MinimalEncoder.Encoder(base: base, parent: self, key: key)
pendingContainer = sup
return sup
}
func superEncoder(forKey key: Key) -> Encoder {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
expectNil(values[key.stringValue], "Key \(key) has already been encoded", trapping: true)
let sup = MinimalEncoder.Encoder(base: base, parent: self, key: key)
pendingContainer = sup
return sup
}
}
extension MinimalEncoder {
final class UnkeyedContainer {
unowned let base: MinimalEncoder
unowned let parent: _MinimalEncoderContainer?
let key: CodingKey?
var values: [Value] = []
var isValid = true
var pendingContainer: AnyObject?
init(base: MinimalEncoder, parent: _MinimalEncoderContainer?, key: CodingKey?) {
self.base = base
self.parent = parent
self.key = key
}
func commitPendingContainer() {
expectTrue(self.isValid, "Container isn't valid", trapping: true)
guard var c = pendingContainer else { return }
self.pendingContainer = nil
expectTrue(isKnownUniquelyReferenced(&c), "Container was retained", trapping: true)
let container = c as! _MinimalEncoderContainer
guard let v = container.finalize() else { preconditionFailure("Container remained empty")}
values.append(v)
}
}
}
extension MinimalEncoder.UnkeyedContainer: _MinimalEncoderContainer {
func finalize() -> MinimalEncoder.Value? {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
isValid = false
return .array(values)
}
}
extension MinimalEncoder.UnkeyedContainer: UnkeyedEncodingContainer {
var count: Int {
values.count
}
func encodeNil() throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.null)
}
func encode(_ value: Bool) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.bool(value))
}
func encode(_ value: Int) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.int(value))
}
func encode(_ value: Int8) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.int8(value))
}
func encode(_ value: Int16) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.int16(value))
}
func encode(_ value: Int32) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.int32(value))
}
func encode(_ value: Int64) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.int64(value))
}
func encode(_ value: UInt) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.uint(value))
}
func encode(_ value: UInt8) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.uint8(value))
}
func encode(_ value: UInt16) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.uint16(value))
}
func encode(_ value: UInt32) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.uint32(value))
}
func encode(_ value: UInt64) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.uint64(value))
}
func encode(_ value: Float) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.float(value))
}
func encode(_ value: Double) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.double(value))
}
func encode(_ value: String) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(.string(value))
}
func encode<T: Encodable>(_ value: T) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
values.append(try _encode(value, key: key))
}
func nestedContainer<NestedKey: CodingKey>(
keyedBy keyType: NestedKey.Type
) -> KeyedEncodingContainer<NestedKey> {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
let keyed = MinimalEncoder.KeyedContainer<NestedKey>(
base: base,
parent: self,
key: MinimalEncoder._Key(count))
pendingContainer = keyed
return .init(keyed)
}
func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
let unkeyed = MinimalEncoder.UnkeyedContainer(base: base, parent: self, key: MinimalEncoder._Key(count))
pendingContainer = unkeyed
return unkeyed
}
func superEncoder() -> Encoder {
expectTrue(isValid, "Container isn't valid", trapping: true)
commitPendingContainer()
let sup = MinimalEncoder.Encoder(base: base, parent: self, key: MinimalEncoder._Key(count))
pendingContainer = sup
return sup
}
}
extension MinimalEncoder {
final class SingleValueContainer {
unowned let base: MinimalEncoder
unowned let parent: _MinimalEncoderContainer?
let key: CodingKey?
var value: Value?
var isValid = true
init(base: MinimalEncoder, parent: _MinimalEncoderContainer?, key: CodingKey?) {
self.base = base
self.parent = parent
self.key = key
}
}
}
extension MinimalEncoder.SingleValueContainer: _MinimalEncoderContainer {
func finalize() -> MinimalEncoder.Value? {
expectTrue(isValid, "Container isn't valid", trapping: true)
isValid = false
return value
}
}
extension MinimalEncoder.SingleValueContainer: SingleValueEncodingContainer {
func encodeNil() throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .null
}
func encode(_ value: Bool) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .bool(value)
}
func encode(_ value: Int) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .int(value)
}
func encode(_ value: Int8) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .int8(value)
}
func encode(_ value: Int16) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .int16(value)
}
func encode(_ value: Int32) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .int32(value)
}
func encode(_ value: Int64) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .int64(value)
}
func encode(_ value: UInt) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .uint(value)
}
func encode(_ value: UInt8) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .uint8(value)
}
func encode(_ value: UInt16) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .uint16(value)
}
func encode(_ value: UInt32) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .uint32(value)
}
func encode(_ value: UInt64) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .uint64(value)
}
func encode(_ value: Float) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .float(value)
}
func encode(_ value: Double) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .double(value)
}
func encode(_ value: String) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = .string(value)
}
func encode<T: Encodable>(_ value: T) throws {
expectTrue(isValid, "Container isn't valid", trapping: true)
expectNil(self.value, "Cannot encode multiple values into a single-value container", trapping: true)
self.value = try _encode(value, key: nil)
}
}
@@ -0,0 +1,59 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibUnittest
import XCTest
public struct MinimalIndex {
internal let _state: _CollectionState
internal let _id: Int
internal var _offset: Int
internal init(state: _CollectionState, offset: Int) {
_state = state
_id = state.context.nextIndexId()
_offset = offset
precondition(_offset >= 0 && _offset <= state.count)
}
public var offset: Int { _offset }
public var context: TestContext { _state.context }
}
extension MinimalIndex: Equatable {
public static func == (left: Self, right: Self) -> Bool {
left._assertCompatible(with: right)
return left._offset == right._offset
}
}
extension MinimalIndex: Comparable {
public static func < (left: Self, right: Self) -> Bool {
left._assertCompatible(with: right)
return left._offset < right._offset
}
}
extension MinimalIndex: CustomStringConvertible {
public var description: String {
return "MinimalIndex(offset: \(_offset), state: \(_state.id))"
}
}
extension MinimalIndex {
func _assertCompatible(with other: Self) {
if self._state === other._state { return }
expectTrue(self._state.isValidIndex(other), "Invalid index", trapping: true)
expectTrue(other._state.isValidIndex(self), "Invalid index", trapping: true)
}
}
@@ -0,0 +1,54 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
/// State shared by all iterators of a MinimalSequence instance.
internal class _MinimalIteratorSharedState<Element> {
internal init(_ data: [Element]) {
self.data = data
}
internal let data: [Element]
internal var i: Int = 0
internal var underestimatedCount: Int = 0
public func next() -> Element? {
if i == data.count {
return nil
}
defer { i += 1 }
return data[i]
}
}
/// An iterator that implements the IteratorProtocol contract in the most
/// narrow way possible.
public struct MinimalIterator<Element>: IteratorProtocol {
internal let _sharedState: _MinimalIteratorSharedState<Element>
public init<S: Sequence>(_ s: S) where S.Element == Element {
self._sharedState = _MinimalIteratorSharedState(Array(s))
}
public init(_ data: [Element]) {
self._sharedState = _MinimalIteratorSharedState(data)
}
internal init(_ _sharedState: _MinimalIteratorSharedState<Element>) {
self._sharedState = _sharedState
}
public func next() -> Element? {
_sharedState.next()
}
}
@@ -0,0 +1,182 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
/// A minimal implementation of `RandomAccessCollection & MutableCollection` with extra checks.
public struct MinimalMutableRandomAccessCollection<Element> {
internal var _core: _MinimalCollectionCore<Element>
public let timesMakeIteratorCalled = ResettableValue(0)
public let timesUnderestimatedCountCalled = ResettableValue(0)
public let timesRangeChecksCalled = ResettableValue(0)
public let timesIndexNavigationCalled = ResettableValue(0)
public let timesSubscriptGetterCalled = ResettableValue(0)
public let timesSubscriptSetterCalled = ResettableValue(0)
public let timesRangeSubscriptGetterCalled = ResettableValue(0)
public let timesRangeSubscriptSetterCalled = ResettableValue(0)
public let timesSwapCalled = ResettableValue(0)
public let timesPartitionCalled = ResettableValue(0)
public init<S: Sequence>(
_ elements: S,
context: TestContext = TestContext.current,
underestimatedCount: UnderestimatedCountBehavior = .value(0)
) where S.Element == Element {
self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount)
}
var _context: TestContext {
_core.context
}
}
extension MinimalMutableRandomAccessCollection: Sequence {
public typealias Iterator = MinimalIterator<Element>
public func makeIterator() -> MinimalIterator<Element> {
timesMakeIteratorCalled.increment()
return MinimalIterator(_core.elements)
}
public var underestimatedCount: Int {
timesUnderestimatedCountCalled.increment()
return _core.underestimatedCount
}
}
extension MinimalMutableRandomAccessCollection: RandomAccessCollection {
public typealias Index = MinimalIndex
public typealias SubSequence = Slice<Self>
public typealias Indices = DefaultIndices<Self>
public var startIndex: MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.startIndex
}
public var endIndex: MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.endIndex
}
public var isEmpty: Bool {
timesIndexNavigationCalled.increment()
return _core.isEmpty
}
public var count: Int {
timesIndexNavigationCalled.increment()
return _core.count
}
public func _failEarlyRangeCheck(
_ index: MinimalIndex,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(
_ range: Range<MinimalIndex>,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(range, bounds: bounds)
}
public func index(after i: MinimalIndex) -> MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.index(after: i)
}
public func index(before i: MinimalIndex) -> MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.index(before: i)
}
public func distance(from start: MinimalIndex, to end: MinimalIndex)
-> Int {
timesIndexNavigationCalled.increment()
return _core.distance(from: start, to: end)
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
timesIndexNavigationCalled.increment()
return _core.index(i, offsetBy: n)
}
public subscript(i: MinimalIndex) -> Element {
get {
timesSubscriptGetterCalled.increment()
return _core[i]
}
set {
timesSubscriptSetterCalled.increment()
_core[i] = newValue
}
}
public subscript(bounds: Range<MinimalIndex>) -> SubSequence {
get {
timesRangeSubscriptGetterCalled.increment()
_core.assertValid(bounds)
return Slice(base: self, bounds: bounds)
}
set {
timesRangeSubscriptSetterCalled.increment()
_core.assertValid(bounds)
expectEqual(bounds.upperBound._offset - bounds.lowerBound._offset,
newValue.endIndex._offset - newValue.startIndex._offset,
"Range assignment cannot change number of elements in MutableCollection")
_core.elements[bounds.lowerBound._offset ..< bounds.upperBound._offset] =
Self._coreSlice(from: newValue)
// Don't invalidate indices.
}
}
static func _coreSlice(from slice: SubSequence) -> ArraySlice<Element> {
slice.base._core.assertValid(slice.startIndex ..< slice.endIndex)
return slice.base._core.elements[slice.startIndex._offset ..< slice.endIndex._offset]
}
}
extension MinimalMutableRandomAccessCollection: MutableCollection {
public mutating func partition(
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
timesPartitionCalled.increment()
let pivot = try _core.elements.partition(by: belongsInSecondPartition)
return _core.index(at: pivot)
}
public mutating func swapAt(_ i: Index, _ j: Index) {
_core.assertValidIndexBeforeEnd(i)
_core.assertValidIndexBeforeEnd(j)
timesSwapCalled.increment()
_core.elements.swapAt(i._offset, j._offset)
// Don't invalidate indices.
}
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return nil
}
public mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return nil
}
}
@@ -0,0 +1,249 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
/// A minimal implementation of `RandomAccessCollection & MutableCollection & RangeReplaceableCollection` with extra checks.
public struct MinimalMutableRangeReplaceableRandomAccessCollection<Element> {
internal var _core: _MinimalCollectionCore<Element>
public let timesMakeIteratorCalled = ResettableValue(0)
public let timesUnderestimatedCountCalled = ResettableValue(0)
public let timesRangeChecksCalled = ResettableValue(0)
public let timesIndexNavigationCalled = ResettableValue(0)
public let timesSubscriptGetterCalled = ResettableValue(0)
public let timesSubscriptSetterCalled = ResettableValue(0)
public let timesRangeSubscriptGetterCalled = ResettableValue(0)
public let timesRangeSubscriptSetterCalled = ResettableValue(0)
public let timesSwapCalled = ResettableValue(0)
public let timesPartitionCalled = ResettableValue(0)
public init<S: Sequence>(
_ elements: S,
context: TestContext = TestContext.current,
underestimatedCount: UnderestimatedCountBehavior = .value(0)
) where S.Element == Element {
self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount)
}
var _context: TestContext {
_core.context
}
}
extension MinimalMutableRangeReplaceableRandomAccessCollection: Sequence {
public typealias Iterator = MinimalIterator<Element>
public func makeIterator() -> MinimalIterator<Element> {
timesMakeIteratorCalled.increment()
return MinimalIterator(_core.elements)
}
public var underestimatedCount: Int {
timesUnderestimatedCountCalled.increment()
return _core.underestimatedCount
}
}
extension MinimalMutableRangeReplaceableRandomAccessCollection: RandomAccessCollection {
public typealias Index = MinimalIndex
public typealias SubSequence = Slice<Self>
public typealias Indices = DefaultIndices<Self>
public var startIndex: MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.startIndex
}
public var endIndex: MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.endIndex
}
public var isEmpty: Bool {
timesIndexNavigationCalled.increment()
return _core.isEmpty
}
public var count: Int {
timesIndexNavigationCalled.increment()
return _core.count
}
public func _failEarlyRangeCheck(
_ index: MinimalIndex,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(
_ range: Range<MinimalIndex>,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(range, bounds: bounds)
}
public func index(after i: MinimalIndex) -> MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.index(after: i)
}
public func index(before i: MinimalIndex) -> MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.index(before: i)
}
public func distance(from start: MinimalIndex, to end: MinimalIndex)
-> Int {
timesIndexNavigationCalled.increment()
return _core.distance(from: start, to: end)
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
timesIndexNavigationCalled.increment()
return _core.index(i, offsetBy: n)
}
public subscript(i: MinimalIndex) -> Element {
get {
timesSubscriptGetterCalled.increment()
return _core[i]
}
set {
timesSubscriptSetterCalled.increment()
_core[i] = newValue
}
}
public subscript(bounds: Range<MinimalIndex>) -> SubSequence {
get {
timesRangeSubscriptGetterCalled.increment()
_core.assertValid(bounds)
return Slice(base: self, bounds: bounds)
}
set {
timesRangeSubscriptSetterCalled.increment()
_core.assertValid(bounds)
_core.elements[bounds.lowerBound._offset ..< bounds.upperBound._offset] =
Self._coreSlice(from: newValue)
// Don't invalidate indices.
}
}
static func _coreSlice(from slice: SubSequence) -> ArraySlice<Element> {
slice.base._core.assertValid(slice.startIndex ..< slice.endIndex)
return slice.base._core.elements[slice.startIndex._offset ..< slice.endIndex._offset]
}
}
extension MinimalMutableRangeReplaceableRandomAccessCollection: MutableCollection {
public mutating func partition(
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
timesPartitionCalled.increment()
let pivot = try _core.elements.partition(by: belongsInSecondPartition)
return _core.index(at: pivot)
}
public mutating func swapAt(_ i: Index, _ j: Index) {
_core.assertValidIndexBeforeEnd(i)
_core.assertValidIndexBeforeEnd(j)
timesSwapCalled.increment()
_core.elements.swapAt(i._offset, j._offset)
// Don't invalidate indices.
}
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return nil
}
public mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return nil
}
}
extension MinimalMutableRangeReplaceableRandomAccessCollection: RangeReplaceableCollection {
public init() {
self.init([])
}
public mutating func replaceSubrange<C: Collection>(
_ subrange: Range<Index>,
with newElements: C
) where C.Element == Element {
_core.replaceSubrange(subrange, with: newElements)
}
public mutating func reserveCapacity(_ n: Int) {
_core.reserveCapacity(minimumCapacity: n)
}
public init<S: Sequence>(_ elements: S) where S.Element == Element {
self.init(elements, context: TestContext.current)
}
public mutating func append(_ newElement: Element) {
_core.append(newElement)
}
public mutating func append<S: Sequence>(
contentsOf newElements: S
) where S.Element == Element {
_core.append(contentsOf: newElements)
}
public mutating func insert(_ newElement: Element, at i: Index) {
_core.insert(newElement, at: i)
}
@discardableResult
public mutating func remove(at i: Index) -> Element {
return _core.remove(at: i)
}
public mutating func removeSubrange(_ bounds: Range<Index>) {
_core.removeSubrange(bounds)
}
public mutating func _customRemoveLast() -> Element? {
return _core._customRemoveLast()
}
public mutating func _customRemoveLast(_ n: Int) -> Bool {
return _core._customRemoveLast(n)
}
@discardableResult
public mutating func removeFirst() -> Element {
return _core.removeFirst()
}
public mutating func removeFirst(_ n: Int) {
_core.removeFirst(n)
}
public mutating func removeAll(keepingCapacity keepCapacity: Bool) {
_core.removeAll(keepingCapacity: keepCapacity)
}
public mutating func removeAll(
where shouldBeRemoved: (Element) throws -> Bool) rethrows {
try _core.removeAll(where: shouldBeRemoved)
}
}
@@ -0,0 +1,125 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
/// A minimal implementation of `RandomAccessCollection` with extra checks.
public struct MinimalRandomAccessCollection<Element> {
internal var _core: _MinimalCollectionCore<Element>
public let timesMakeIteratorCalled = ResettableValue(0)
public let timesUnderestimatedCountCalled = ResettableValue(0)
public let timesRangeChecksCalled = ResettableValue(0)
public let timesIndexNavigationCalled = ResettableValue(0)
public let timesSubscriptCalled = ResettableValue(0)
public let timesRangeSubscriptCalled = ResettableValue(0)
public init<S: Sequence>(
_ elements: S,
context: TestContext = TestContext.current,
underestimatedCount: UnderestimatedCountBehavior = .value(0)
) where S.Element == Element {
self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount)
}
var _context: TestContext {
_core.context
}
}
extension MinimalRandomAccessCollection: Sequence {
public typealias Iterator = MinimalIterator<Element>
public func makeIterator() -> MinimalIterator<Element> {
timesMakeIteratorCalled.increment()
return MinimalIterator(_core.elements)
}
public var underestimatedCount: Int {
timesUnderestimatedCountCalled.increment()
return _core.underestimatedCount
}
}
extension MinimalRandomAccessCollection: RandomAccessCollection {
public typealias Index = MinimalIndex
public typealias SubSequence = Slice<Self>
public typealias Indices = DefaultIndices<Self>
public var startIndex: MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.startIndex
}
public var endIndex: MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.endIndex
}
public var isEmpty: Bool {
timesIndexNavigationCalled.increment()
return _core.isEmpty
}
public var count: Int {
timesIndexNavigationCalled.increment()
return _core.count
}
public func _failEarlyRangeCheck(
_ index: MinimalIndex,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(
_ range: Range<MinimalIndex>,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(range, bounds: bounds)
}
public func index(after i: MinimalIndex) -> MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.index(after: i)
}
public func index(before i: MinimalIndex) -> MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.index(before: i)
}
public func distance(from start: MinimalIndex, to end: MinimalIndex)
-> Int {
timesIndexNavigationCalled.increment()
return _core.distance(from: start, to: end)
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
timesIndexNavigationCalled.increment()
return _core.index(i, offsetBy: n)
}
public subscript(i: MinimalIndex) -> Element {
timesSubscriptCalled.increment()
return _core[i]
}
public subscript(bounds: Range<MinimalIndex>) -> SubSequence {
timesRangeSubscriptCalled.increment()
_core.assertValid(bounds)
return Slice(base: self, bounds: bounds)
}
}
@@ -0,0 +1,204 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
/// A minimal implementation of `RandomAccessCollection & RangeReplaceableCollection` with extra checks.
public struct MinimalRangeReplaceableRandomAccessCollection<Element> {
internal var _core: _MinimalCollectionCore<Element>
public let timesMakeIteratorCalled = ResettableValue(0)
public let timesUnderestimatedCountCalled = ResettableValue(0)
public let timesRangeChecksCalled = ResettableValue(0)
public let timesIndexNavigationCalled = ResettableValue(0)
public let timesSubscriptGetterCalled = ResettableValue(0)
public let timesSubscriptSetterCalled = ResettableValue(0)
public let timesRangeSubscriptGetterCalled = ResettableValue(0)
public let timesRangeSubscriptSetterCalled = ResettableValue(0)
public let timesSwapCalled = ResettableValue(0)
public let timesPartitionCalled = ResettableValue(0)
public init<S: Sequence>(
_ elements: S,
context: TestContext = TestContext.current,
underestimatedCount: UnderestimatedCountBehavior = .value(0)
) where S.Element == Element {
self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount)
}
var _context: TestContext {
_core.context
}
}
extension MinimalRangeReplaceableRandomAccessCollection: Sequence {
public typealias Iterator = MinimalIterator<Element>
public func makeIterator() -> MinimalIterator<Element> {
timesMakeIteratorCalled.increment()
return MinimalIterator(_core.elements)
}
public var underestimatedCount: Int {
timesUnderestimatedCountCalled.increment()
return _core.underestimatedCount
}
}
extension MinimalRangeReplaceableRandomAccessCollection: RandomAccessCollection {
public typealias Index = MinimalIndex
public typealias SubSequence = Slice<Self>
public typealias Indices = DefaultIndices<Self>
public var startIndex: MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.startIndex
}
public var endIndex: MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.endIndex
}
public var isEmpty: Bool {
timesIndexNavigationCalled.increment()
return _core.isEmpty
}
public var count: Int {
timesIndexNavigationCalled.increment()
return _core.count
}
public func _failEarlyRangeCheck(
_ index: MinimalIndex,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(
_ range: Range<MinimalIndex>,
bounds: Range<MinimalIndex>
) {
timesRangeChecksCalled.increment()
_core._failEarlyRangeCheck(range, bounds: bounds)
}
public func index(after i: MinimalIndex) -> MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.index(after: i)
}
public func index(before i: MinimalIndex) -> MinimalIndex {
timesIndexNavigationCalled.increment()
return _core.index(before: i)
}
public func distance(from start: MinimalIndex, to end: MinimalIndex)
-> Int {
timesIndexNavigationCalled.increment()
return _core.distance(from: start, to: end)
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
timesIndexNavigationCalled.increment()
return _core.index(i, offsetBy: n)
}
public subscript(i: MinimalIndex) -> Element {
timesSubscriptGetterCalled.increment()
return _core[i]
}
public subscript(bounds: Range<MinimalIndex>) -> SubSequence {
timesRangeSubscriptGetterCalled.increment()
_core.assertValid(bounds)
return Slice(base: self, bounds: bounds)
}
static func _coreSlice(from slice: SubSequence) -> ArraySlice<Element> {
slice.base._core.assertValid(slice.startIndex ..< slice.endIndex)
return slice.base._core.elements[slice.startIndex._offset ..< slice.endIndex._offset]
}
}
extension MinimalRangeReplaceableRandomAccessCollection: RangeReplaceableCollection {
public init() {
self.init([])
}
public mutating func replaceSubrange<C: Collection>(
_ subrange: Range<Index>,
with newElements: C
) where C.Element == Element {
_core.replaceSubrange(subrange, with: newElements)
}
public mutating func reserveCapacity(_ n: Int) {
_core.reserveCapacity(minimumCapacity: n)
}
public init<S: Sequence>(_ elements: S) where S.Element == Element {
self.init(elements, context: TestContext.current)
}
public mutating func append(_ newElement: Element) {
_core.append(newElement)
}
public mutating func append<S: Sequence>(
contentsOf newElements: S
) where S.Element == Element {
_core.append(contentsOf: newElements)
}
public mutating func insert(_ newElement: Element, at i: Index) {
_core.insert(newElement, at: i)
}
@discardableResult
public mutating func remove(at i: Index) -> Element {
return _core.remove(at: i)
}
public mutating func removeSubrange(_ bounds: Range<Index>) {
_core.removeSubrange(bounds)
}
public mutating func _customRemoveLast() -> Element? {
return _core._customRemoveLast()
}
public mutating func _customRemoveLast(_ n: Int) -> Bool {
return _core._customRemoveLast(n)
}
@discardableResult
public mutating func removeFirst() -> Element {
return _core.removeFirst()
}
public mutating func removeFirst(_ n: Int) {
_core.removeFirst(n)
}
public mutating func removeAll(keepingCapacity keepCapacity: Bool) {
_core.removeAll(keepingCapacity: keepCapacity)
}
public mutating func removeAll(
where shouldBeRemoved: (Element) throws -> Bool) rethrows {
try _core.removeAll(where: shouldBeRemoved)
}
}
@@ -0,0 +1,96 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
public enum UnderestimatedCountBehavior {
/// Return the actual number of elements.
case precise
/// Return the actual number of elements divided by 2.
case half
/// Return an overestimated count. Useful to test how algorithms reserve
/// memory.
case overestimate
/// Return the provided value.
case value(Int)
func value(forCount count: Int) -> Int {
switch self {
case .precise:
return count
case .half:
return count / 2
case .overestimate:
return count * 3 + 5
case .value(let count):
return count
}
}
}
/// A Sequence that implements the protocol contract in the most
/// narrow way possible.
///
/// This sequence is consumed when its generator is advanced.
public struct MinimalSequence<T>: Sequence, CustomDebugStringConvertible {
public let timesMakeIteratorCalled = ResettableValue(0)
internal let _sharedState: _MinimalIteratorSharedState<T>
internal let _isContiguous: Bool
public init<S: Sequence>(
elements: S,
underestimatedCount: UnderestimatedCountBehavior = .value(0),
isContiguous: Bool = false
) where S.Element == T {
let data = Array(elements)
self._sharedState = _MinimalIteratorSharedState(data)
self._isContiguous = isContiguous
switch underestimatedCount {
case .precise:
self._sharedState.underestimatedCount = data.count
case .half:
self._sharedState.underestimatedCount = data.count / 2
case .overestimate:
self._sharedState.underestimatedCount = data.count * 3 + 5
case .value(let count):
self._sharedState.underestimatedCount = count
}
}
public func makeIterator() -> MinimalIterator<T> {
timesMakeIteratorCalled.value += 1
return MinimalIterator(_sharedState)
}
public var underestimatedCount: Int {
return Swift.max(0, self._sharedState.underestimatedCount - self._sharedState.i)
}
public var debugDescription: String {
return "MinimalSequence(\(_sharedState.data[_sharedState.i...]))"
}
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<T>) throws -> R
) rethrows -> R? {
guard _isContiguous else { return nil }
return try _sharedState.data[_sharedState.i...]
.withContiguousStorageIfAvailable(body)
}
}
@@ -0,0 +1,37 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibUnittest
public class ResettableValue<Value> {
public init(_ value: Value) {
self.defaultValue = value
self.value = value
}
public func reset() {
value = defaultValue
}
public let defaultValue: Value
public var value: Value
}
extension ResettableValue where Value: Strideable {
public func increment(by delta: Value.Stride = 1) {
value = value.advanced(by: delta)
}
}
extension ResettableValue: CustomStringConvertible {
public var description: String { "\(value)" }
}
@@ -0,0 +1,34 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public struct StringConvertibleValue {
public var value: Int
public init(_ value: Int) { self.value = value }
}
extension StringConvertibleValue: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self.init(value)
}
}
extension StringConvertibleValue: CustomStringConvertible {
public var description: String {
"description(\(value))"
}
}
extension StringConvertibleValue: CustomDebugStringConvertible {
public var debugDescription: String {
"debugDescription(\(value))"
}
}
@@ -0,0 +1,241 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibCollectionUnittest
final class _CollectionState {
/// The collection context in which this state belongs.
let context: TestContext
/// The unique identifier of this state within its context.
let id: Int
/// The state from which this instance spawned.
private(set) var parent: _CollectionState?
private(set) var count: Int
private(set) var strategy: IndexInvalidationStrategy
/// The identifier of the state in which each currently valid index first became valid.
/// (Note: the end index is tracked separately, in `endIndexValidity`.
/// The identifier tracked here is guaranteed to match one of the states on the `parent` chain.
private var indexValidity: [Int]
/// The identitifer of the state in which the current endIndex first became valid.
private var endIndexValidity: Int
enum IndexInvalidationStrategy: Hashable {
case allIndices
case afterChange
}
init(
context: TestContext,
parent: _CollectionState?,
count: Int,
strategy: IndexInvalidationStrategy = .allIndices,
indexValidity: [Int],
endIndexValidity: Int
) {
self.context = context
self.id = context.nextStateId()
self.parent = parent
self.count = count
self.strategy = strategy
self.indexValidity = indexValidity
self.endIndexValidity = endIndexValidity
}
init(
context: TestContext,
parent: _CollectionState?,
count: Int,
strategy: IndexInvalidationStrategy = .allIndices
) {
self.context = context
self.parent = parent
self.id = context.nextStateId()
self.count = count
self.strategy = strategy
switch strategy {
case .allIndices:
self.indexValidity = []
self.endIndexValidity = 0
case .afterChange:
self.indexValidity = Array(repeatElement(id, count: count))
self.endIndexValidity = id
}
}
deinit {
// Prevent stack overflow for long parent chains.
var node = self
while isKnownUniquelyReferenced(&node.parent) {
let p = node.parent!
node.parent = nil
node = p
}
}
func spawnChild() -> _CollectionState {
_CollectionState(
context: context,
parent: self,
count: count,
strategy: strategy,
indexValidity: indexValidity,
endIndexValidity: endIndexValidity)
}
}
extension _CollectionState: Equatable {
public static func == (left: _CollectionState, right: _CollectionState) -> Bool {
return left.id == right.id
}
}
extension _CollectionState: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
extension _CollectionState {
func isValidIndex(_ index: MinimalIndex) -> Bool {
if index._state === self { return true }
guard index._state.context == context else { return false }
guard index._offset >= 0 && index._offset <= count else { return false }
switch strategy {
case .allIndices:
guard index._state.id == self.id else { return false }
case .afterChange:
if index._offset < count {
guard index._state.id == indexValidity[index._offset] else { return false }
} else {
guard index._state.id == endIndexValidity else { return false }
}
}
return true
}
}
extension _CollectionState {
internal subscript(validityAt offset: Int) -> Int {
get {
switch strategy {
case .allIndices:
return id
case .afterChange:
precondition(offset >= 0)
if offset > count {
return id
}
if offset == count {
return endIndexValidity
}
return indexValidity[offset]
}
}
set {
precondition(strategy == .allIndices, "Cannot invalidate individual indices")
precondition(offset >= 0 && offset <= count)
if offset == count {
endIndexValidity = newValue
} else {
indexValidity[offset] = newValue
}
}
}
}
extension _CollectionState {
func insert(count: Int, at offset: Int) {
precondition(count >= 0 && offset >= 0 && offset <= self.count)
guard count > 0 else { return }
self.count += count
switch strategy {
case .allIndices:
// Do nothing
break
case .afterChange:
let rest = offset ..< indexValidity.count
self.indexValidity.replaceSubrange(rest, with: repeatElement(id, count: rest.count + count))
self.endIndexValidity = self.id
assert(indexValidity.count == self.count)
}
}
func remove(_ range: Range<MinimalIndex>) {
remove(count: range.upperBound._offset - range.lowerBound._offset,
at: range.lowerBound._offset)
}
func remove(count: Int, at offset: Int) {
precondition(count >= 0 && offset >= 0 && offset + count <= self.count)
guard count > 0 else { return }
switch strategy {
case .allIndices:
self.count -= count
case .afterChange:
let rest = offset ..< self.count
self.indexValidity.replaceSubrange(rest, with: repeatElement(id, count: rest.count - count))
self.endIndexValidity = self.id
self.count -= count
assert(indexValidity.count == self.count)
}
}
func replace(_ range: Range<MinimalIndex>, with newCount: Int) {
replace(oldCount: range.upperBound._offset - range.lowerBound._offset,
at: range.lowerBound._offset,
with: newCount)
}
func replace(oldCount: Int, at offset: Int, with newCount: Int) {
precondition(oldCount >= 0 && offset >= 0 && newCount >= 0)
precondition(offset + oldCount <= self.count)
guard oldCount > 0 || newCount > 0 else { return }
switch strategy {
case .allIndices:
self.count += newCount - oldCount
case .afterChange:
let rest = offset ..< self.count
self.indexValidity.replaceSubrange(
rest,
with: repeatElement(id, count: rest.count + newCount - oldCount))
self.endIndexValidity = self.id
self.count += newCount - oldCount
assert(indexValidity.count == self.count)
}
}
func replaceAll() {
switch strategy {
case .allIndices:
// Do nothing
break
case .afterChange:
self.indexValidity = Array(repeating: id, count: count)
self.endIndexValidity = id
assert(indexValidity.count == self.count)
}
}
func reset(count: Int) {
self.count = count
switch strategy {
case .allIndices:
// Do nothing
break
case .afterChange:
self.indexValidity = Array(repeating: id, count: count)
self.endIndexValidity = id
assert(indexValidity.count == self.count)
}
}
}
@@ -0,0 +1,349 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
struct _MinimalCollectionCore<Element> {
var state: _CollectionState
var elements: [Element]
var underestimatedCount: Int
public init<S: Sequence>(
context: TestContext,
elements: S,
underestimatedCount: UnderestimatedCountBehavior? = nil
) where S.Element == Element {
self.init(context: context, elements: Array(elements), underestimatedCount: underestimatedCount)
}
public init(
context: TestContext,
elements: [Element],
underestimatedCount: UnderestimatedCountBehavior? = nil
) {
self.state = _CollectionState(context: context, parent: nil, count: elements.count)
self.elements = elements
self.underestimatedCount = underestimatedCount?.value(forCount: elements.count) ?? elements.count
}
var context: TestContext { state.context }
}
extension _MinimalCollectionCore {
var startIndex: MinimalIndex {
MinimalIndex(state: state, offset: 0)
}
var endIndex: MinimalIndex {
MinimalIndex(state: state, offset: count)
}
var count: Int {
elements.count
}
var isEmpty: Bool {
elements.isEmpty
}
}
extension _MinimalCollectionCore {
mutating func ensureUniqueState() {
if !isKnownUniquelyReferenced(&state) {
state = state.spawnChild()
}
}
}
// MARK: Index validation
extension _MinimalCollectionCore {
internal func index(at offset: Int) -> MinimalIndex {
return MinimalIndex(state: state, offset: offset)
}
func isValidIndex(_ index: MinimalIndex) -> Bool {
state.isValidIndex(index)
}
func assertValidIndex(
_ index: MinimalIndex,
_ message: @autoclosure () -> String = "Invalid index",
file: StaticString = #file,
line: UInt = #line
) {
expectTrue(isValidIndex(index),
message(), trapping: true,
file: file, line: line)
}
func assertValidIndexBeforeEnd(
_ index: MinimalIndex,
_ message: @autoclosure () -> String = "Invalid index",
file: StaticString = #file,
line: UInt = #line
) {
expectTrue(isValidIndex(index),
message(), trapping: true,
file: file, line: line)
expectTrue(index._offset != elements.count,
message(), trapping: true,
file: file, line: line)
}
func assertValid(
_ range: Range<MinimalIndex>,
message: @autoclosure () -> String = "Invalid index range",
file: StaticString = #file,
line: UInt = #line
) {
assertValidIndex(range.lowerBound, message())
assertValidIndex(range.upperBound, message())
}
}
// MARK: Index navigation
extension _MinimalCollectionCore {
func index(after index: MinimalIndex) -> MinimalIndex {
assertValidIndex(index)
expectTrue(index._offset < count,
"Can't advance beyond endIndex",
trapping: true)
return self.index(at: index._offset + 1)
}
func index(before index: MinimalIndex) -> MinimalIndex {
assertValidIndex(index)
expectTrue(index._offset > 0,
"Can't advance before startIndex",
trapping: true)
return self.index(at: index._offset - 1)
}
func formIndex(after index: inout MinimalIndex) {
assertValidIndex(index)
expectTrue(index._offset < count,
"Can't advance beyond endIndex",
trapping: true)
index._offset += 1
}
func formIndex(before index: inout MinimalIndex) {
assertValidIndex(index)
expectTrue(index._offset > 0,
"Can't advance before startIndex",
trapping: true)
index._offset -= 1
}
public func distance(from start: MinimalIndex, to end: MinimalIndex) -> Int {
assertValidIndex(start)
assertValidIndex(end)
return end._offset - start._offset
}
public func index(
_ index: MinimalIndex,
offsetBy n: Int
) -> MinimalIndex {
assertValidIndex(index)
expectTrue(index._offset + n >= 0,
"Can't advance before startIndex",
trapping: true)
expectTrue(index._offset + n <= count,
"Can't advance after endIndex",
trapping: true)
return self.index(at: index._offset + n)
}
func _failEarlyRangeCheck(
_ index: MinimalIndex,
bounds: Range<MinimalIndex>
) {
assertValidIndex(index)
assertValid(bounds)
expectLessThanOrEqual(
bounds.lowerBound._offset, index._offset,
"Index out of bounds", trapping: true)
expectLessThan(
index._offset, bounds.upperBound._offset,
"Index out of bounds", trapping: true)
}
public func _failEarlyRangeCheck(
_ range: Range<MinimalIndex>,
bounds: Range<MinimalIndex>
) {
assertValid(range)
assertValid(bounds)
expectLessThanOrEqual(
bounds.lowerBound._offset, range.lowerBound._offset,
"Index range out of bounds", trapping: true)
expectLessThanOrEqual(
range.upperBound._offset, bounds.upperBound._offset,
"Index range out of bounds", trapping: true)
}
func _count(of range: Range<MinimalIndex>) -> Int {
range.upperBound._offset - range.lowerBound._offset
}
}
// MARK: Mutations
extension _MinimalCollectionCore {
subscript(index: MinimalIndex) -> Element {
get {
assertValidIndexBeforeEnd(index)
return elements[index._offset]
}
set {
assertValidIndexBeforeEnd(index)
elements[index._offset] = newValue
// MutableCollection requires that the subscript setter
// not invalidate any indices.
}
}
mutating func replaceSubrange<C: Collection>(
_ subrange: Range<MinimalIndex>,
with newElements: C
) where C.Element == Element {
assertValid(subrange)
elements.replaceSubrange(
subrange.lowerBound._offset ..< subrange.upperBound._offset,
with: newElements)
ensureUniqueState()
state.replace(subrange, with: newElements.count)
}
mutating func reserveCapacity(minimumCapacity: Int) {
elements.reserveCapacity(minimumCapacity)
state.replaceAll()
}
mutating func append(_ item: Element) {
elements.append(item)
ensureUniqueState()
state.insert(count: 1, at: state.count)
}
mutating func append<S: Sequence>(
contentsOf newElements: S
) where S.Element == Element {
elements.append(contentsOf: newElements)
ensureUniqueState()
state.insert(count: elements.count - state.count, at: state.count)
}
mutating func insert(
_ newElement: Element,
at index: MinimalIndex
) {
assertValidIndex(index)
elements.insert(newElement, at: index._offset)
ensureUniqueState()
state.insert(count: 1, at: index._offset)
}
mutating func insert<C: Collection>(
contentsOf newElements: C,
at index: MinimalIndex
) where C.Element == Element {
assertValidIndex(index)
elements.insert(contentsOf: newElements, at: index._offset)
ensureUniqueState()
state.insert(count: newElements.count, at: index._offset)
}
mutating func remove(at index: MinimalIndex) -> Element {
assertValidIndexBeforeEnd(index)
ensureUniqueState()
state.remove(count: 1, at: index._offset)
return elements.remove(at: index._offset)
}
mutating func removeSubrange(_ bounds: Range<MinimalIndex>) {
assertValid(bounds)
elements.removeSubrange(bounds.lowerBound._offset ..< bounds.upperBound._offset)
ensureUniqueState()
state.remove(count: _count(of: bounds), at: bounds.lowerBound._offset)
}
mutating func removeFirst() -> Element {
expectTrue(
count > 0,
"Can't remove first element of an empty collection",
trapping: true)
ensureUniqueState()
state.remove(count: 1, at: 0)
return elements.removeFirst()
}
mutating func removeFirst(_ n: Int) {
expectTrue(
n >= 0,
"Can't remove a negative number of elements",
trapping: true)
expectTrue(
n <= count,
"Can't remove more elements than there are in the collection",
trapping: true)
ensureUniqueState()
state.remove(count: n, at: 0)
elements.removeFirst(n)
}
public mutating func _customRemoveLast() -> Element? {
expectTrue(
!isEmpty,
"Can't remove last element of an empty collection",
trapping: true)
ensureUniqueState()
state.remove(count: 1, at: state.count)
return elements.removeLast()
}
public mutating func _customRemoveLast(_ n: Int) -> Bool {
expectTrue(
n >= 0,
"Can't remove a negative number of elements",
trapping: true)
expectTrue(
count >= n,
"Can't remove more elements than there are in the collection",
trapping: true)
elements.removeLast(n)
ensureUniqueState()
state.remove(count: n, at: state.count - n)
return true
}
mutating func removeAll(keepingCapacity keepCapacity: Bool) {
elements.removeAll(keepingCapacity: keepCapacity)
ensureUniqueState()
state.remove(count: state.count, at: 0)
}
mutating func removeAll(
where shouldBeRemoved: (Element) throws -> Bool
) rethrows {
defer {
ensureUniqueState()
state.reset(count: elements.count)
}
try elements.removeAll(where: shouldBeRemoved)
}
}
@@ -0,0 +1,16 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public final class Box<T> {
public init(_ value: T) { self.value = value }
public var value: T
}
@@ -0,0 +1,24 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public final class HashableBox<T: Hashable>: Hashable {
public init(_ value: T) { self.value = value }
public var value: T
public static func ==(left: HashableBox, right: HashableBox) -> Bool {
left.value == right.value
}
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
@@ -0,0 +1,77 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that tracks the number of live instances.
///
/// `LifetimeTracked` conforms to `CustomStringConvertible`, and conditionally
/// conforms to `Equatable`, `Hashable` and `Comparable` when its payload does.
///
/// `LifetimeTracked` is useful to check for leaks in algorithms and data
/// structures. The easiest way to produce instances is to use the
/// `withLifetimeTracking` function:
///
/// class FooTests: XCTestCase {
/// func testFoo() {
/// withLifetimeTracking([1, 2, 3]) { instances in
/// _ = instances.sorted(by: >)
/// }
/// }
/// }
public class LifetimeTracked<Payload> {
public let tracker: LifetimeTracker
internal var serialNumber: Int = 0
public let payload: Payload
public init(_ payload: Payload, for tracker: LifetimeTracker) {
tracker.instances += 1
tracker._nextSerialNumber += 1
self.tracker = tracker
self.serialNumber = tracker._nextSerialNumber
self.payload = payload
}
deinit {
precondition(serialNumber != 0, "Double deinit")
tracker.instances -= 1
serialNumber = -serialNumber
}
}
extension LifetimeTracked: CustomStringConvertible {
public var description: String {
return "\(payload)"
}
}
extension LifetimeTracked: Equatable where Payload: Equatable {
public static func == (left: LifetimeTracked, right: LifetimeTracked) -> Bool {
return left.payload == right.payload
}
}
extension LifetimeTracked: Hashable where Payload: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(payload)
}
}
extension LifetimeTracked: Comparable where Payload: Comparable {
public static func < (left: LifetimeTracked, right: LifetimeTracked) -> Bool {
return left.payload < right.payload
}
}
extension LifetimeTracked: Encodable where Payload: Encodable {
public func encode(to encoder: Encoder) throws {
try payload.encode(to: encoder)
}
}
@@ -0,0 +1,54 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Tracks the life times of `LifetimeTracked` instances, providing a method
/// to validate checkpoints where no instances should exist.
///
/// - Note: `LifetimeTracker` is not designed for multithreaded use. Trying to
/// instantiate or deinitialize instances belonging to the same tracker
/// from multiple concurrent threads (or reentrantly) will lead to
/// exclusivity violations and therefore undefined behavior.
public class LifetimeTracker {
public internal(set) var instances = 0
var _nextSerialNumber = 0
public init() {}
deinit {
check()
}
public func check(file: StaticString = #file, line: UInt = #line) {
expectEqual(instances, 0,
"Potential leak of \(instances) objects",
file: file, line: line)
}
public func instance<Payload>(for payload: Payload) -> LifetimeTracked<Payload> {
LifetimeTracked(payload, for: self)
}
public func instances<S: Sequence>(for items: S) -> [LifetimeTracked<S.Element>] {
return items.map { LifetimeTracked($0, for: self) }
}
}
@inlinable
public func withLifetimeTracking<R>(
file: StaticString = #file,
line: UInt = #line,
_ body: (LifetimeTracker) throws -> R
) rethrows -> R {
let tracker = LifetimeTracker()
defer { tracker.check(file: file, line: line) }
return try body(tracker)
}
@@ -0,0 +1,40 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
public struct RepeatableRandomNumberGenerator: RandomNumberGenerator {
// This uses the same linear congruential generator as rand48.
// FIXME: Replace with something better.
internal static let _m: UInt64 = 1 << 48
internal static let _a: UInt64 = 25214903917
internal static let _c: UInt64 = 11
internal var _state: UInt64
public init(seed: Int) {
self.init(seed: UInt64(truncatingIfNeeded: seed))
}
public init(seed: UInt64) {
// Perturb the seed a little so that the sequence doesn't start with a
// zero value in the common case of seed == 0. (Using a zero seed is a
// rather silly thing to do, but it's the easy thing.)
_state = seed ^ 0x536f52616e646f6d // "SoRandom"
}
private mutating func _next() -> UInt64 {
_state = (Self._a &* _state &+ Self._c) & (Self._m - 1)
return _state &>> 16
}
public mutating func next() -> UInt64 {
return (_next() &<< 32) | _next()
}
}
+49
View File
@@ -0,0 +1,49 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: Encodable where Element: Encodable {
/// Encodes the elements of this deque into the given encoder in an unkeyed
/// container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
@inlinable
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension Deque: Decodable where Element: Decodable {
/// Creates a new deque by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
@inlinable
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
if let count = container.count {
self.reserveCapacity(count)
}
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.append(element)
}
}
}
@@ -0,0 +1,28 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
var result = "Deque<\(Element.self)>(["
var first = true
for item in self {
if first {
first = false
} else {
result += ", "
}
debugPrint(item, terminator: "", to: &result)
}
result += "])"
return result
}
}
@@ -0,0 +1,17 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: CustomReflectable {
/// The custom mirror for this instance.
public var customMirror: Mirror {
Mirror(self, unlabeledChildren: self, displayStyle: .collection)
}
}
@@ -0,0 +1,28 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: CustomStringConvertible {
/// A textual representation of this instance.
public var description: String {
var result = "["
var first = true
for item in self {
if first {
first = false
} else {
result += ", "
}
print(item, terminator: "", to: &result)
}
result += "]"
return result
}
}
+22
View File
@@ -0,0 +1,22 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: Equatable where Element: Equatable {
/// Returns a Boolean value indicating whether two values are equal. Two
/// deques are considered equal if they contain the same elements in the same
/// order.
///
/// - Complexity: O(`min(left.count, right.count)`)
@inlinable
public static func ==(left: Self, right: Self) -> Bool {
return left.elementsEqual(right)
}
}
@@ -0,0 +1,27 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: ExpressibleByArrayLiteral {
/// Creates a new deque from the contents of an array literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use an array literal. Instead, create a new set using an array
/// literal as its value by enclosing a comma-separated list of values in
/// square brackets. You can use an array literal anywhere a set is expected
/// by the type context.
///
/// - Parameter elements: A variadic list of elements of the new set.
@inlinable
@inline(__always)
public init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
+180
View File
@@ -0,0 +1,180 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque {
/// Creates a deque with the specified capacity, then calls the given
/// closure with a buffer covering the array's uninitialized memory.
///
/// Inside the closure, set the `initializedCount` parameter to the number of
/// elements that are initialized by the closure. The memory in the range
/// `buffer[0..<initializedCount]` must be initialized at the end of the
/// closure's execution, and the memory in the range
/// `buffer[initializedCount...]` must be uninitialized. This postcondition
/// must hold even if the `initializer` closure throws an error.
///
/// - Note: While the resulting deque may have a capacity larger than the
/// requested amount, the buffer passed to the closure will cover exactly
/// the requested number of elements.
///
/// - Parameters:
/// - unsafeUninitializedCapacity: The number of elements to allocate
/// space for in the new deque.
/// - initializer: A closure that initializes elements and sets the count
/// of the new deque.
/// - Parameters:
/// - buffer: A buffer covering uninitialized memory with room for the
/// specified number of elements.
/// - initializedCount: The count of initialized elements in the deque,
/// which begins as zero. Set `initializedCount` to the number of
/// elements you initialize.
@inlinable
public init(
unsafeUninitializedCapacity capacity: Int,
initializingWith initializer:
(inout UnsafeMutableBufferPointer<Element>, inout Int) throws -> Void
) rethrows {
self._storage = .init(minimumCapacity: capacity)
try _storage.update { handle in
handle.startSlot = .zero
var count = 0
var buffer = handle.mutableBuffer(for: .zero ..< _Slot(at: capacity))
defer {
precondition(count <= capacity,
"Initialized count set to greater than specified capacity")
let b = handle.mutableBuffer(for: .zero ..< _Slot(at: capacity))
precondition(buffer.baseAddress == b.baseAddress && buffer.count == b.count,
"Initializer relocated Deque storage")
handle.count = count
}
try initializer(&buffer, &count)
}
}
}
extension Deque {
/// Removes and returns the first element of this deque, if it exists.
///
/// - Returns: The first element of the original collection if the collection
/// isn't empty; otherwise, `nil`.
///
/// - Complexity: O(1) when this instance has a unique reference to its
/// underlying storage; O(`count`) otherwise.
@inlinable
public mutating func popFirst() -> Element? {
// FIXME: Add this to the stdlib on BidirectionalCollection
// where Self == Self.SubSequence
guard count > 0 else { return nil }
_storage.ensureUnique()
return _storage.update {
$0.uncheckedRemoveFirst()
}
}
// Note: `popLast` is implemented by the stdlib as a
// `RangeReplaceableCollection` extension, defined in terms of
// `_customRemoveLast`.
/// Adds a new element at the front of the deque.
///
/// Use this method to append a single element to the front of a deque.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.prepend(100)
/// print(numbers)
/// // Prints "[100, 1, 2, 3, 4, 5]"
///
/// Because deques increase their allocated capacity using an exponential
/// strategy, prepending a single element to a deque is an O(1) operation when
/// averaged over many calls to the `prepend(_:)` method. When a deque has
/// additional capacity and is not sharing its storage with another instance,
/// prepending an element is O(1). When a deque needs to reallocate storage
/// before prepending or its storage is shared with another copy, prepending
/// is O(`count`).
///
/// - Parameter newElement: The element to prepend to the deque.
///
/// - Complexity: Amortized O(1).
///
/// - SeeAlso: `append(_:)`
@inlinable
public mutating func prepend(_ newElement: Element) {
_storage.ensureUnique(minimumCapacity: count + 1)
return _storage.update {
$0.uncheckedPrepend(newElement)
}
}
/// Adds the elements of a collection to the front of the deque.
///
/// Use this method to prepend the elements of a collection to the front of
/// this deque. This example prepends the elements of a `Range<Int>` instance
/// to a deque of integers.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.prepend(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5]"
///
/// - Parameter newElements: The elements to prepend to the deque.
///
/// - Complexity: Amortized O(`newElements.count`).
///
/// - SeeAlso: `append(contentsOf:)`
@inlinable
public mutating func prepend<C: Collection>(contentsOf newElements: C) where C.Element == Element {
let done: Void? = newElements.withContiguousStorageIfAvailable { source in
_storage.ensureUnique(minimumCapacity: count + source.count)
_storage.update { $0.uncheckedPrepend(contentsOf: source) }
}
guard done == nil else { return }
let c = newElements.count
guard c > 0 else { return }
_storage.ensureUnique(minimumCapacity: count + c)
_storage.update { target in
let gaps = target.availableSegments().suffix(c)
gaps.initialize(from: newElements)
target.count += c
target.startSlot = target.slot(target.startSlot, offsetBy: -c)
}
}
/// Adds the elements of a sequence to the front of the deque.
///
/// Use this method to prepend the elements of a sequence to the front of this
/// deque. This example prepends the elements of a `Range<Int>` instance to a
/// deque of integers.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.prepend(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5]"
///
/// - Parameter newElements: The elements to prepend to the deque.
///
/// - Complexity: Amortized O(`newElements.count`).
///
/// - SeeAlso: `append(contentsOf:)`
@inlinable
public mutating func prepend<S: Sequence>(contentsOf newElements: S) where S.Element == Element {
let originalCount = self.count
self.append(contentsOf: newElements)
let newCount = self.count
let c = newCount - originalCount
_storage.update { target in
target.startSlot = target.slot(forOffset: originalCount)
target.count = target.capacity
target.closeGap(offsets: c ..< c + (target.capacity - newCount))
assert(target.count == newCount)
}
}
}
+24
View File
@@ -0,0 +1,24 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: Hashable where Element: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Complexity: O(`count`)
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(count) // discriminator
for element in self {
hasher.combine(element)
}
}
}
@@ -0,0 +1,83 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: MutableCollection {
/// Exchanges the values at the specified indices of the collection.
///
/// Both parameters must be valid indices of the collection and not equal to
/// `endIndex`. Passing the same index as both `i` and `j` has no effect.
///
/// - Parameters:
/// - i: The index of the first value to swap.
/// - j: The index of the second value to swap.
///
/// - Complexity: O(1) when this instance has a unique reference to its
/// underlying storage; O(`count`) otherwise.
@inlinable
public mutating func swapAt(_ i: Index, _ j: Index) {
precondition(i >= 0 && i < count, "Index out of bounds")
precondition(j >= 0 && j < count, "Index out of bounds")
_storage.ensureUnique()
_storage.update { handle in
let slot1 = handle.slot(forOffset: i)
let slot2 = handle.slot(forOffset: j)
handle.mutableBuffer.swapAt(slot1.position, slot2.position)
}
}
// FIXME: Implement `partition(by:)` by making storage contiguous,
// and partitioning that.
/// Call `body(b)`, where `b` is an unsafe buffer pointer to the deque's
/// mutable contiguous storage. If the deque's contents aren't stored
/// contiguously, `body` is not called and `nil` is returned. The supplied
/// buffer pointer is only valid for the duration of the call.
///
/// Often, the optimizer can eliminate bounds- and uniqueness-checks within an
/// algorithm, but when that fails, invoking the same algorithm on the unsafe
/// buffer supplied to `body` lets you trade safety for speed.
///
/// - Parameters:
/// - body: The function to invoke.
///
/// - Returns: The value returned by `body`, or `nil` if `body` wasn't called.
///
/// - Complexity: O(1) when this instance has a unique reference to its
/// underlying storage; O(`count`) otherwise. (Not counting the call to
/// `body`.)
@inlinable
public mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
_storage.ensureUnique()
return try _storage.update { handle in
let endSlot = handle.startSlot.advanced(by: handle.count)
guard endSlot.position <= handle.capacity else {
// FIXME: Rotate storage such that it becomes contiguous.
return nil
}
let original = handle.mutableBuffer(for: handle.startSlot ..< endSlot)
var extract = original
defer {
precondition(extract.baseAddress == original.baseAddress && extract.count == original.count,
"Closure must not replace the provided buffer")
}
return try body(&extract)
}
}
@inlinable
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try withContiguousMutableStorageIfAvailable(body)
}
}
@@ -0,0 +1,243 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: RandomAccessCollection {
public typealias Index = Int
public typealias SubSequence = Slice<Self>
/// The number of elements in the deque.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var count: Int { _storage.count }
/// The position of the first element in a nonempty deque.
///
/// For an instance of `Deque`, `startIndex` is always zero. If the deque is
/// empty, `startIndex` is equal to `endIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var startIndex: Index { 0 }
/// The deque’s “past the end” position—that is, the position one greater than
/// the last valid subscript argument.
///
/// For an instance of `Deque`, `endIndex` is always equal to its `count`. If
/// the deque is empty, `endIndex` is equal to `startIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var endIndex: Index { count }
/// Returns the position immediately after the given index.
///
/// - Parameter `i`: A valid index of the deque. `i` must be less than
/// `endIndex`.
///
/// - Returns: The next valid index immediately after `i`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func index(after i: Index) -> Index {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
return i + 1
}
/// Replaces the given index with its successor.
///
/// - Parameter `i`: A valid index of the deque. `i` must be less than
/// `endIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func formIndex(after i: inout Index) {
// Note: Like `Array`, index manipulation methods on deques
// don't trap on invalid indices.
// (Indices are still validated on element access.)
i += 1
}
/// Returns the position immediately before the given index.
///
/// - Parameter `i`: A valid index of the deque. `i` must be greater than
/// `startIndex`.
///
/// - Returns: The preceding valid index immediately before `i`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func index(before i: Index) -> Index {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
return i - 1
}
/// Replaces the given index with its predecessor.
///
/// - Parameter `i`: A valid index of the deque. `i` must be greater than `startIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func formIndex(before i: inout Index) {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
i -= 1
}
/// Returns an index that is the specified distance from the given index.
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection.
///
/// - Parameters:
/// - i: A valid index of the deque.
/// - `distance`: The distance by which to offset `i`.
///
/// - Returns: An index offset by `distance` from the index `i`. If `distance`
/// is positive, this is the same value as the result of `distance` calls
/// to `index(after:)`. If `distance` is negative, this is the same value
/// as the result of `abs(distance)` calls to `index(before:)`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func index(_ i: Index, offsetBy distance: Int) -> Index {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
return i + distance
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the deque to use as a limit.
/// If `distance > 0`, then `limit` has no effect it is less than `i`.
/// Likewise, if `distance < 0`, then `limit` has no effect if it is
/// greater than `i`.
///
/// - Returns: An index offset by `distance` from the index `i`, unless that
/// index would be beyond `limit` in the direction of movement. In that
/// case, the method returns `nil`.
///
/// - Complexity: O(1)
@inlinable
public func index(
_ i: Int,
offsetBy distance: Int,
limitedBy limit: Int
) -> Int? {
// Note: Like `Array`, index manipulation methods on deques
// don't trap on invalid indices.
// (Indices are still validated on element access.)
let l = limit - i
if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l {
return nil
}
return i + distance
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection.
///
/// - Returns: The distance between `start` and `end`. If `end` is equal to
/// `start`, the result is zero. Otherwise the result is positive if `end`
/// is greater than `start`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func distance(from start: Index, to end: Index) -> Int {
// Note: Like `Array`, index manipulation method on deques
// don't trap on invalid indices.
// (Indices are still validated on element access.)
return end - start
}
/// Accesses the element at the specified position.
///
/// - Parameters:
/// - index: The position of the element to access. `index` must be greater
/// than or equal to `startIndex` and less than `endIndex`.
///
/// - Complexity: Reading an element from a deque is O(1). Writing is O(1)
/// unless the deque’s storage is shared with another deque, in which case
/// writing is O(`count`).
@inlinable
public subscript(index: Index) -> Element {
get {
precondition(index >= 0 && index < count, "Index out of bounds")
return _storage.read { $0.ptr(at: $0.slot(forOffset: index)).pointee }
}
set {
precondition(index >= 0 && index < count, "Index out of bounds")
_storage.ensureUnique()
_storage.update { handle in
let slot = handle.slot(forOffset: index)
handle.ptr(at: slot).pointee = newValue
}
}
_modify {
precondition(index >= 0 && index < count, "Index out of bounds")
_storage.ensureUnique()
// We technically aren't supposed to escape storage pointers out of a
// managed buffer, so we escape a `(slot, value)` pair instead, leaving
// the corresponding slot temporarily uninitialized.
var (slot, value) = _storage.update { handle -> (_Slot, Element) in
let slot = handle.slot(forOffset: index)
return (slot, handle.ptr(at: slot).move())
}
defer {
_storage.update { handle in
handle.ptr(at: slot).initialize(to: value)
}
}
yield &value
}
}
/// Accesses a contiguous subrange of the deque's elements.
///
/// - Parameters:
/// - bounds: A range of the deque's indices. The bounds of the range must
/// be valid indices of the deque (including the `endIndex`).
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection.
@inlinable
public subscript(bounds: Range<Index>) -> Slice<Self> {
get {
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
"Invalid bounds")
return Slice(base: self, bounds: bounds)
}
set(source) {
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
"Invalid bounds")
self.replaceSubrange(bounds, with: source)
}
}
}
@@ -0,0 +1,437 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: RangeReplaceableCollection {
/// Creates a new, empty deque.
///
/// This is equivalent to initializing with an empty array literal.
/// For example:
///
/// let deque1 = Deque<Int>()
/// print(deque1.isEmpty) // true
///
/// let deque2: Deque<Int> = []
/// print(deque2.isEmpty) // true
///
/// - Complexity: O(1)
@inlinable
public init() {
_storage = _Storage()
}
/// Replaces a range of elements with the elements in the specified
/// collection.
///
/// This method has the effect of removing the specified range of elements
/// from the deque and inserting the new elements at the same location. The
/// number of new elements need not match the number of elements being
/// removed.
///
/// - Parameters:
/// - subrange: The subrange of the deque to replace. The bounds of the
/// subrange must be valid indices of the deque (including the
/// `endIndex`).
/// - newElements: The new elements to add to the deque.
///
/// - Complexity: O(`self.count + newElements.count`). If the operation needs
/// to change the size of the deque, it minimizes the number of existing
/// items that need to be moved by shifting elements either before or after
/// `subrange`.
@inlinable
public mutating func replaceSubrange<C: Collection>(
_ subrange: Range<Index>,
with newElements: __owned C
) where C.Element == Element {
precondition(subrange.lowerBound >= 0 && subrange.upperBound <= count, "Index range out of bounds")
let removalCount = subrange.count
let insertionCount = newElements.count
let deltaCount = insertionCount - removalCount
_storage.ensureUnique(minimumCapacity: count + deltaCount)
let replacementCount = Swift.min(removalCount, insertionCount)
let targetCut = subrange.lowerBound + replacementCount
let sourceCut = newElements.index(newElements.startIndex, offsetBy: replacementCount)
_storage.update { target in
target.uncheckedReplaceInPlace(
inOffsets: subrange.lowerBound ..< targetCut,
with: newElements[..<sourceCut])
if deltaCount < 0 {
let r = targetCut ..< subrange.upperBound
assert(replacementCount + r.count == removalCount)
target.uncheckedRemove(offsets: r)
} else if deltaCount > 0 {
target.uncheckedInsert(
contentsOf: newElements[sourceCut...],
count: deltaCount,
atOffset: targetCut)
}
}
}
/// Reserves enough space to store the specified number of elements.
///
/// If you are adding a known number of elements to a deque, use this method
/// to avoid multiple reallocations. It ensures that the deque has unique
/// storage, with space allocated for at least the requested number of
/// elements.
///
/// - Parameters:
/// - minimumCapacity: The requested number of elements to store.
///
/// - Complexity: O(`count`)
@inlinable
public mutating func reserveCapacity(_ minimumCapacity: Int) {
_storage.ensureUnique(minimumCapacity: minimumCapacity, linearGrowth: true)
}
/// Creates a new deque containing the specified number of a single, repeated
/// value.
///
/// - Parameters:
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the element. `count` must be zero
/// or greater.
///
/// - Complexity: O(`count`)
@inlinable
public init(repeating repeatedValue: Element, count: Int) {
precondition(count >= 0)
self.init(minimumCapacity: count)
_storage.update { handle in
assert(handle.startSlot == .zero)
if count > 0 {
handle.ptr(at: .zero).initialize(repeating: repeatedValue, count: count)
}
handle.count = count
}
}
/// Creates a deque containing the elements of a sequence.
///
/// - Parameters:
/// - elements: The sequence of elements to turn into a deque.
///
/// - Complexity: O(*n*), where *n* is the number of elements in the sequence.
@inlinable
public init<S: Sequence>(_ elements: S) where S.Element == Element {
self.init()
self.append(contentsOf: elements)
}
/// Creates a deque containing the elements of a collection.
///
/// - Parameters:
/// - elements: The collection of elements to turn into a deque.
///
/// - Complexity: O(`elements.count`)
@inlinable
public init<C: Collection>(_ elements: C) where C.Element == Element {
let c = elements.count
guard c > 0 else { _storage = _Storage(); return }
self._storage = _Storage(minimumCapacity: c)
_storage.update { handle in
assert(handle.startSlot == .zero)
let target = handle.mutableBuffer(for: .zero ..< _Slot(at: c))
let done: Void? = elements.withContiguousStorageIfAvailable { source in
target._initialize(from: source)
}
if done == nil {
target._initialize(from: elements)
}
handle.count = c
}
}
/// Adds a new element at the end of the deque.
///
/// Use this method to append a single element to the end of a deque.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.append(100)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 100]"
///
/// Because deques increase their allocated capacity using an exponential
/// strategy, appending a single element to a deque is an O(1) operation when
/// averaged over many calls to the `append(_:)` method. When a deque has
/// additional capacity and is not sharing its storage with another instance,
/// appending an element is O(1). When a deque needs to reallocate storage
/// before prepending or its storage is shared with another copy, appending is
/// O(`count`).
///
/// - Parameters:
/// - newElement: The element to append to the deque.
///
/// - Complexity: Amortized O(1)
///
/// - SeeAlso: `prepend(_:)`
@inlinable
public mutating func append(_ newElement: Element) {
_storage.ensureUnique(minimumCapacity: count + 1)
_storage.update {
$0.uncheckedAppend(newElement)
}
}
/// Adds the elements of a sequence to the end of the deque.
///
/// Use this method to append the elements of a sequence to the front of this
/// deque. This example appends the elements of a `Range<Int>` instance to a
/// deque of integers.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.append(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameter newElements: The elements to append to the deque.
///
/// - Complexity: Amortized O(`newElements.count`).
@inlinable
public mutating func append<S: Sequence>(contentsOf newElements: S) where S.Element == Element {
let done: Void? = newElements.withContiguousStorageIfAvailable { source in
_storage.ensureUnique(minimumCapacity: count + source.count)
_storage.update { $0.uncheckedAppend(contentsOf: source) }
}
if done != nil {
return
}
let underestimatedCount = newElements.underestimatedCount
reserveCapacity(count + underestimatedCount)
var it: S.Iterator = _storage.update { target in
let gaps = target.availableSegments()
let (it, copied) = gaps.initialize(fromSequencePrefix: newElements)
target.count += copied
return it
}
while let next = it.next() {
_storage.ensureUnique(minimumCapacity: count + 1)
_storage.update { target in
target.uncheckedAppend(next)
let gaps = target.availableSegments()
target.count += gaps.initialize(fromPrefixOf: &it)
}
}
}
/// Adds the elements of a collection to the end of the deque.
///
/// Use this method to append the elements of a collection to the front of
/// this deque. This example appends the elements of a `Range<Int>` instance
/// to a deque of integers.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.append(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameter newElements: The elements to append to the deque.
///
/// - Complexity: Amortized O(`newElements.count`).
@inlinable
public mutating func append<C: Collection>(contentsOf newElements: C) where C.Element == Element {
let done: Void? = newElements.withContiguousStorageIfAvailable { source in
_storage.ensureUnique(minimumCapacity: count + source.count)
_storage.update { $0.uncheckedAppend(contentsOf: source) }
}
guard done == nil else { return }
let c = newElements.count
guard c > 0 else { return }
reserveCapacity(count + c)
_storage.update { target in
let gaps = target.availableSegments().prefix(c)
gaps.initialize(from: newElements)
target.count += c
}
}
/// Inserts a new element at the specified position.
///
/// The new element is inserted before the element currently at the specified
/// index. If you pass the deque’s `endIndex` as the `index` parameter, the
/// new element is appended to the deque.
///
/// - Parameters:
/// - newElement: The new element to insert into the deque.
/// - index: The position at which to insert the new element. `index` must
/// be a valid index of the deque (including `endIndex`).
///
/// - Complexity: O(`count`). The operation shifts existing elements either
/// towards the beginning or the end of the deque to minimize the number of
/// elements that need to be moved. When inserting at the start or the end,
/// this reduces the complexity to amortized O(1).
@inlinable
public mutating func insert(_ newElement: Element, at index: Index) {
precondition(index >= 0 && index <= count,
"Can't insert element at invalid index")
_storage.ensureUnique(minimumCapacity: count + 1)
_storage.update { target in
if index == 0 {
target.uncheckedPrepend(newElement)
return
}
if index == count {
target.uncheckedAppend(newElement)
return
}
let gap = target.openGap(ofSize: 1, atOffset: index)
assert(gap.first.count == 1)
gap.first.baseAddress!.initialize(to: newElement)
}
}
/// Inserts the elements of a collection into the deque at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the deque's `endIndex` property as the
/// `index` parameter, the new elements are appended to the deque.
///
/// - Parameters:
/// - newElements: The new elements to insert into the deque.
/// - index: The position at which to insert the new elements. `index` must
/// be a valid index of the deque (including `endIndex`).
///
/// - Complexity: O(`count + newElements.count`). The operation shifts
/// existing elements either towards the beginning or the end of the deque
/// to minimize the number of elements that need to be moved. When
/// inserting at the start or the end, this reduces the complexity to
/// amortized O(1).
@inlinable
public mutating func insert<C: Collection>(
contentsOf newElements: __owned C, at index: Index
) where C.Element == Element {
precondition(index >= 0 && index <= count,
"Can't insert elements at an invalid index")
let newCount = newElements.count
_storage.ensureUnique(minimumCapacity: count + newCount)
_storage.update { target in
target.uncheckedInsert(contentsOf: newElements, count: newCount, atOffset: index)
}
}
/// Removes and returns the element at the specified position.
///
/// To close the resulting gap, all elements following the specified position
/// are (logically) moved up by one index position. (Internally, the deque may
/// actually decide to shift previous elements forward instead to minimize the
/// number of elements that need to be moved.)
///
/// - Parameters:
/// - index: The position of the element to remove. `index` must be a valid
/// index of the array.
///
/// - Returns: The element originally at the specified index.
///
/// - Complexity: O(`count`). Removing elements from the start or end of the
/// deque costs O(1) if the deque's storage isn't shared.
@inlinable
@discardableResult
public mutating func remove(at index: Index) -> Element {
precondition(index >= 0 && index < self.count, "Index out of bounds")
// FIXME: Implement storage shrinking
_storage.ensureUnique()
return _storage.update { target in
// FIXME: Add direct implementation & see if it makes a difference
let result = self[index]
target.uncheckedRemove(offsets: index ..< index + 1)
return result
}
}
/// Removes the elements in the specified subrange from the deque.
/// All elements following the specified range are (logically) moved up to
/// close the resulting gap. (Internally, the deque may actually decide to
/// shift previous elements forward instead to minimize the number of elements
/// that need to be moved.)
///
/// - Parameters:
/// - bounds: The range of the collection to be removed. The bounds of the
/// range must be valid indices of the collection.
///
/// - Complexity: O(`count`). Removing elements from the start or end of the
/// deque costs O(`bounds.count`) if the deque's storage isn't shared.
@inlinable
public mutating func removeSubrange(_ bounds: Range<Index>) {
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= self.count,
"Index range out of bounds")
_storage.ensureUnique()
_storage.update { $0.uncheckedRemove(offsets: bounds) }
}
@inlinable
public mutating func _customRemoveLast() -> Element? {
precondition(!isEmpty, "Cannot remove last element of an empty Deque")
_storage.ensureUnique()
return _storage.update { $0.uncheckedRemoveLast() }
}
@inlinable
public mutating func _customRemoveLast(_ n: Int) -> Bool {
precondition(n >= 0, "Can't remove a negative number of elements")
precondition(n <= count, "Can't remove more elements than there are in the Collection")
_storage.ensureUnique()
_storage.update { $0.uncheckedRemoveLast(n) }
return true
}
/// Removes and returns the first element of the deque.
///
/// The collection must not be empty.
///
/// - Returns: The removed element.
///
/// - Complexity: O(1) if the underlying storage isn't shared; otherwise
/// O(`count`).
@inlinable
@discardableResult
public mutating func removeFirst() -> Element {
precondition(!isEmpty, "Cannot remove first element of an empty Deque")
_storage.ensureUnique()
return _storage.update { $0.uncheckedRemoveFirst() }
}
/// Removes the specified number of elements from the beginning of the deque.
///
/// - Parameter n: The number of elements to remove from the deque. `n` must
/// be greater than or equal to zero and must not exceed the number of
/// elements in the deque.
///
/// - Complexity: O(`n`) if the underlying storage isn't shared; otherwise
/// O(`count`).
@inlinable
public mutating func removeFirst(_ n: Int) {
precondition(n >= 0, "Can't remove a negative number of elements")
precondition(n <= count, "Can't remove more elements than there are in the Collection")
_storage.ensureUnique()
return _storage.update { $0.uncheckedRemoveFirst(n) }
}
/// Removes all elements from the deque.
///
/// - Parameter keepCapacity: Pass true to keep the existing storage capacity
/// of the deque after removing its elements. The default value is false.
///
/// - Complexity: O(`count`)
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
if keepCapacity {
_storage.ensureUnique()
_storage.update { $0.uncheckedRemoveAll() }
} else {
self = Deque()
}
}
}
+160
View File
@@ -0,0 +1,160 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: Sequence {
// Implementation note: we could also use the default `IndexingIterator` here.
// This custom implementation performs direct storage access to eliminate any
// and all index validation overhead. It also optimizes away repeated
// conversions from indices to storage slots.
/// An iterator over the members of a deque.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _storage: Deque._Storage
@usableFromInline
internal var _nextSlot: _Slot
@usableFromInline
internal var _endSlot: _Slot
@inlinable
internal init(_storage: Deque._Storage, start: _Slot, end: _Slot) {
self._storage = _storage
self._nextSlot = start
self._endSlot = end
}
@inlinable
internal init(_base: Deque) {
self = _base._storage.read { handle in
let start = handle.startSlot
let end = Swift.min(start.advanced(by: handle.count), handle.limSlot)
return Self(_storage: _base._storage, start: start, end: end)
}
}
@inlinable
internal init(_base: Deque, from index: Index) {
assert(index <= _base.count)
self = _base._storage.read { handle in
let start = handle.slot(forOffset: index)
if index == _base.count {
return Self(_storage: _base._storage, start: start, end: start)
}
var end = handle.endSlot
if start >= end { end = handle.limSlot }
return Self(_storage: _base._storage, start: start, end: end)
}
}
@inlinable
@inline(never)
internal mutating func _swapSegment() -> Bool {
assert(_nextSlot == _endSlot)
return _storage.read { handle in
let end = handle.endSlot
if end == .zero || end == _nextSlot {
return false
}
_endSlot = end
_nextSlot = .zero
return true
}
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable
public mutating func next() -> Element? {
if _nextSlot == _endSlot {
guard _swapSegment() else { return nil }
}
assert(_nextSlot < _endSlot)
let slot = _nextSlot
_nextSlot = _nextSlot.advanced(by: 1)
return _storage.read { handle in
return handle.ptr(at: slot).pointee
}
}
}
/// Returns an iterator over the elements of the deque.
///
/// - Complexity: O(1)
@inlinable
public func makeIterator() -> Iterator {
Iterator(_base: self)
}
@inlinable
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
ContiguousArray(unsafeUninitializedCapacity: count) { target, count in
_storage.read { source in
let segments = source.segments()
let c = segments.first.count
target[..<c]._rebased()._initialize(from: segments.first)
count += segments.first.count
if let second = segments.second {
target[c ..< c + second.count]._rebased()._initialize(from: second)
count += second.count
}
assert(count == self.count)
}
}
}
@inlinable
public __consuming func _copyContents(
initializing target: UnsafeMutableBufferPointer<Element>
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
_storage.read { source in
let segments = source.segments()
let c1 = Swift.min(segments.first.count, target.count)
target[..<c1]._rebased()._initialize(from: segments.first.prefix(c1)._rebased())
guard target.count > c1, let second = segments.second else {
return (Iterator(_base: self, from: c1), c1)
}
let c2 = Swift.min(second.count, target.count - c1)
target[c1 ..< c1 + c2]._rebased()._initialize(from: second.prefix(c2)._rebased())
return (Iterator(_base: self, from: c1 + c2), c1 + c2)
}
}
/// Call `body(b)`, where `b` is an unsafe buffer pointer to the deque's
/// contiguous storage, if available. If the deque's contents aren't stored
/// contiguously, `body` is not called and `nil` is returned. The supplied
/// buffer pointer is only valid for the duration of the call.
///
/// Often, the optimizer can eliminate bounds- and uniqueness-checks within an
/// algorithm, but when that fails, invoking the same algorithm on the unsafe
/// buffer supplied to `body` lets you trade safety for speed.
///
/// - Parameters:
/// - body: The function to invoke.
///
/// - Returns: The value returned by `body`, or `nil` if `body` wasn't called.
///
/// - Complexity: O(1) when this instance has a unique reference to its
/// underlying storage; O(`count`) otherwise.
@inlinable
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try _storage.read { handle in
let endSlot = handle.startSlot.advanced(by: handle.count)
guard endSlot.position <= handle.capacity else { return nil }
return try body(handle.buffer(for: handle.startSlot ..< endSlot))
}
}
}
+76
View File
@@ -0,0 +1,76 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// This file contains exported but non-public entry points to support clear box
// testing.
extension Deque {
/// The maximum number of elements this deque is currently able to store
/// without reallocating its storage buffer.
///
/// This information isn't exposed as public, as the returned value isn't
/// guaranteed to be stable, and may even differ between equal deques,
/// violating value semantics.
///
/// This property isn't intended to be used outside of `Deque`'s own test
/// target.
@_spi(Testing)
public var _capacity: Int {
_storage.capacity
}
/// The number of the storage slot in this deque that holds the first element.
/// (Or would hold it after an insertion in case the deque is currently
/// empty.)
///
/// This property isn't intended to be used outside of `Deque`'s own test
/// target.
@_spi(Testing)
public var _startSlot: Int {
_storage.startSlot.position
}
/// Constructs a deque instance of the specified contents and layout. Exposed
/// as public to allow exhaustive input/output tests for `Deque`'s members.
/// This isn't intended to be used outside of `Deque`'s own test target.
@_spi(Testing)
public init<S: Sequence>(
_capacity capacity: Int,
startSlot: Int,
contents: S
) where S.Element == Element {
let contents = ContiguousArray(contents)
precondition(capacity >= 0)
precondition(startSlot >= 0 && (startSlot < capacity || (capacity == 0 && startSlot == 0)))
precondition(contents.count <= capacity)
let startSlot = _Slot(at: startSlot)
let buffer = _DequeBuffer<Element>.create(minimumCapacity: capacity) { _ in
_DequeBufferHeader(capacity: capacity, count: contents.count, startSlot: startSlot)
}
let storage = Deque<Element>._Storage(unsafeDowncast(buffer, to: _DequeBuffer.self))
if contents.count > 0 {
contents.withUnsafeBufferPointer { source in
storage.update { target in
let segments = target.mutableSegments()
let c = segments.first.count
segments.first._initialize(from: source.prefix(c)._rebased())
if let second = segments.second {
second._initialize(from: source.dropFirst(c)._rebased())
}
}
}
}
self.init(_storage: storage)
assert(self._capacity == capacity)
assert(self._startSlot == startSlot.position)
assert(self.count == contents.count)
}
}
+208
View File
@@ -0,0 +1,208 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque {
@usableFromInline
struct _Storage {
@usableFromInline
internal typealias _Buffer = ManagedBufferPointer<_DequeBufferHeader, Element>
@usableFromInline
internal var _buffer: _Buffer
@inlinable
@inline(__always)
internal init(_buffer: _Buffer) {
self._buffer = _buffer
}
}
}
extension Deque._Storage: CustomStringConvertible {
@usableFromInline
internal var description: String {
"Deque<\(Element.self)>._Storage\(_buffer.header)"
}
}
extension Deque._Storage {
@inlinable
internal init() {
self.init(_buffer: _Buffer(unsafeBufferObject: _emptyDequeStorage))
}
@inlinable
internal init(_ object: _DequeBuffer<Element>) {
self.init(_buffer: _Buffer(unsafeBufferObject: object))
}
@inlinable
internal init(minimumCapacity: Int) {
let object = _DequeBuffer<Element>.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: { object in
_DequeBufferHeader(capacity: object.capacity, count: 0, startSlot: .zero)
})
self.init(_buffer: _Buffer(unsafeBufferObject: object))
}
}
extension Deque._Storage {
#if COLLECTIONS_INTERNAL_CHECKS
@usableFromInline @inline(never) @_effects(releasenone)
internal func _checkInvariants() {
_buffer.withUnsafeMutablePointerToHeader { $0.pointee._checkInvariants() }
}
#else
@inlinable @inline(__always)
internal func _checkInvariants() {}
#endif // COLLECTIONS_INTERNAL_CHECKS
}
extension Deque._Storage {
@inlinable
@inline(__always)
internal var identity: AnyObject { _buffer.buffer }
@inlinable
@inline(__always)
internal var capacity: Int {
_buffer.withUnsafeMutablePointerToHeader { $0.pointee.capacity }
}
@inlinable
@inline(__always)
internal var count: Int {
_buffer.withUnsafeMutablePointerToHeader { $0.pointee.count }
}
@inlinable
@inline(__always)
internal var startSlot: _DequeSlot {
_buffer.withUnsafeMutablePointerToHeader { $0.pointee.startSlot
}
}
}
extension Deque._Storage {
@usableFromInline
internal typealias Index = Int
@usableFromInline
internal typealias _UnsafeHandle = Deque._UnsafeHandle
@inlinable
@inline(__always)
internal func read<R>(_ body: (_UnsafeHandle) throws -> R) rethrows -> R {
try _buffer.withUnsafeMutablePointers { header, elements in
let handle = _UnsafeHandle(header: header,
elements: elements,
isMutable: false)
return try body(handle)
}
}
@inlinable
@inline(__always)
internal func update<R>(_ body: (_UnsafeHandle) throws -> R) rethrows -> R {
try _buffer.withUnsafeMutablePointers { header, elements in
let handle = _UnsafeHandle(header: header,
elements: elements,
isMutable: true)
return try body(handle)
}
}
}
extension Deque._Storage {
/// Return a boolean indicating whether this storage instance is known to have
/// a single unique reference. If this method returns true, then it is safe to
/// perform in-place mutations on the deque.
@inlinable
@inline(__always)
internal mutating func isUnique() -> Bool {
_buffer.isUniqueReference()
}
/// Ensure that this storage refers to a uniquely held buffer by copying
/// elements if necessary.
@inlinable
@inline(__always)
internal mutating func ensureUnique() {
if isUnique() { return }
self._makeUniqueCopy()
}
@inlinable
@inline(never)
internal mutating func _makeUniqueCopy() {
self = self.read { $0.copyElements() }
}
/// The growth factor to use to increase storage size to make place for an
/// insertion.
@inlinable
@inline(__always)
internal static var growthFactor: Double { 1.5 }
@usableFromInline
internal func _growCapacity(
to minimumCapacity: Int,
linearly: Bool
) -> Int {
if linearly { return Swift.max(capacity, minimumCapacity) }
return Swift.max(Int((Self.growthFactor * Double(capacity)).rounded(.up)),
minimumCapacity)
}
/// Ensure that we have a uniquely referenced buffer with enough space to
/// store at least `minimumCapacity` elements.
///
/// - Parameter minimumCapacity: The minimum number of elements the buffer
/// needs to be able to hold on return.
///
/// - Parameter linearGrowth: If true, then don't use an exponential growth
/// factor when reallocating the buffer -- just allocate space for the
/// requested number of elements
@inlinable
@inline(__always)
internal mutating func ensureUnique(
minimumCapacity: Int,
linearGrowth: Bool = false
) {
let unique = isUnique()
if _slowPath(capacity < minimumCapacity || !unique) {
_ensureUnique(minimumCapacity: minimumCapacity, linearGrowth: linearGrowth)
}
}
@inlinable
internal mutating func _ensureUnique(
minimumCapacity: Int,
linearGrowth: Bool
) {
if capacity >= minimumCapacity {
assert(!self.isUnique())
self = self.read { $0.copyElements() }
} else if isUnique() {
let minimumCapacity = _growCapacity(to: minimumCapacity, linearly: linearGrowth)
self = self.update { source in
source.moveElements(minimumCapacity: minimumCapacity)
}
} else {
let minimumCapacity = _growCapacity(to: minimumCapacity, linearly: linearGrowth)
self = self.read { source in
source.copyElements(minimumCapacity: minimumCapacity)
}
}
}
}
@@ -0,0 +1,822 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque {
@usableFromInline
internal struct _UnsafeHandle {
@usableFromInline
let _header: UnsafeMutablePointer<_DequeBufferHeader>
@usableFromInline
let _elements: UnsafeMutablePointer<Element>
#if DEBUG
@usableFromInline
let _isMutable: Bool
#endif
@inlinable
@inline(__always)
init(
header: UnsafeMutablePointer<_DequeBufferHeader>,
elements: UnsafeMutablePointer<Element>,
isMutable: Bool
) {
self._header = header
self._elements = elements
#if DEBUG
self._isMutable = isMutable
#endif
}
}
}
extension Deque._UnsafeHandle {
@inlinable
@inline(__always)
func assertMutable() {
#if DEBUG
assert(_isMutable)
#endif
}
}
extension Deque._UnsafeHandle {
@usableFromInline
internal typealias Slot = _DequeSlot
@inlinable
@inline(__always)
var header: _DequeBufferHeader {
_header.pointee
}
@inlinable
@inline(__always)
var capacity: Int {
_header.pointee.capacity
}
@inlinable
@inline(__always)
var count: Int {
get { _header.pointee.count }
nonmutating set { _header.pointee.count = newValue }
}
@inlinable
@inline(__always)
var startSlot: Slot {
get { _header.pointee.startSlot }
nonmutating set { _header.pointee.startSlot = newValue }
}
@inlinable
@inline(__always)
func ptr(at slot: Slot) -> UnsafeMutablePointer<Element> {
assert(slot.position >= 0 && slot.position <= capacity)
return _elements + slot.position
}
}
extension Deque._UnsafeHandle {
@inlinable
@inline(__always)
var mutableBuffer: UnsafeMutableBufferPointer<Element> {
assertMutable()
return .init(start: _elements, count: _header.pointee.capacity)
}
@inlinable
internal func buffer(for range: Range<Slot>) -> UnsafeBufferPointer<Element> {
assert(range.upperBound.position <= capacity)
return .init(start: _elements + range.lowerBound.position, count: range._count)
}
@inlinable
@inline(__always)
internal func mutableBuffer(for range: Range<Slot>) -> UnsafeMutableBufferPointer<Element> {
assertMutable()
return .init(mutating: buffer(for: range))
}
}
extension Deque._UnsafeHandle {
/// The slot immediately following the last valid one. (`endSlot` refers to
/// the valid slot corresponding to `endIndex`, which is a different thing
/// entirely.)
@inlinable
@inline(__always)
internal var limSlot: Slot {
Slot(at: capacity)
}
@inlinable
internal func slot(after slot: Slot) -> Slot {
assert(slot.position < capacity)
let position = slot.position + 1
if position >= capacity {
return Slot(at: 0)
}
return Slot(at: position)
}
@inlinable
internal func slot(before slot: Slot) -> Slot {
assert(slot.position < capacity)
if slot.position == 0 { return Slot(at: capacity - 1) }
return Slot(at: slot.position - 1)
}
@inlinable
internal func slot(_ slot: Slot, offsetBy delta: Int) -> Slot {
assert(slot.position <= capacity)
let position = slot.position + delta
if delta >= 0 {
if position >= capacity { return Slot(at: position - capacity) }
} else {
if position < 0 { return Slot(at: position + capacity) }
}
return Slot(at: position)
}
@inlinable
@inline(__always)
internal var endSlot: Slot {
slot(startSlot, offsetBy: count)
}
/// Return the storage slot corresponding to the specified offset, which may
/// or may not address an existing element.
@inlinable
internal func slot(forOffset offset: Int) -> Slot {
assert(offset >= 0)
assert(offset <= capacity) // Not `count`!
// Note: The use of wrapping addition/subscription is justified here by the
// fact that `offset` is guaranteed to fall in the range `0 ..< capacity`.
// Eliminating the overflow checks leads to a measurable speedup for
// random-access subscript operations. (Up to 2x on some microbenchmarks.)
let position = startSlot.position &+ offset
guard position < capacity else { return Slot(at: position &- capacity) }
return Slot(at: position)
}
}
extension Deque._UnsafeHandle {
@inlinable
internal func segments() -> _UnsafeWrappedBuffer<Element> {
let wrap = capacity - startSlot.position
if count <= wrap {
return .init(start: ptr(at: startSlot), count: count)
}
return .init(first: ptr(at: startSlot), count: wrap,
second: ptr(at: .zero), count: count - wrap)
}
@inlinable
internal func segments(
forOffsets offsets: Range<Int>
) -> _UnsafeWrappedBuffer<Element> {
assert(offsets.lowerBound >= 0 && offsets.upperBound <= count)
let lower = slot(forOffset: offsets.lowerBound)
let upper = slot(forOffset: offsets.upperBound)
if offsets.count == 0 || lower < upper {
return .init(start: ptr(at: lower), count: offsets.count)
}
return .init(first: ptr(at: lower), count: capacity - lower.position,
second: ptr(at: .zero), count: upper.position)
}
@inlinable
@inline(__always)
internal func mutableSegments() -> _UnsafeMutableWrappedBuffer<Element> {
assertMutable()
return .init(mutating: segments())
}
@inlinable
@inline(__always)
internal func mutableSegments(
forOffsets range: Range<Int>
) -> _UnsafeMutableWrappedBuffer<Element> {
assertMutable()
return .init(mutating: segments(forOffsets: range))
}
}
extension Deque._UnsafeHandle {
@inlinable
internal func availableSegments() -> _UnsafeMutableWrappedBuffer<Element> {
assertMutable()
let endSlot = self.endSlot
guard count < capacity else { return .init(start: ptr(at: endSlot), count: 0) }
if endSlot < startSlot { return .init(mutableBuffer(for: endSlot ..< startSlot)) }
return .init(mutableBuffer(for: endSlot ..< limSlot),
mutableBuffer(for: .zero ..< startSlot))
}
}
extension Deque._UnsafeHandle {
@inlinable
@discardableResult
func initialize(
at start: Slot,
from source: UnsafeBufferPointer<Element>
) -> Slot {
assert(start.position + source.count <= capacity)
guard source.count > 0 else { return start }
ptr(at: start).initialize(from: source.baseAddress!, count: source.count)
return Slot(at: start.position + source.count)
}
@inlinable
@inline(__always)
@discardableResult
func moveInitialize(
at start: Slot,
from source: UnsafeMutableBufferPointer<Element>
) -> Slot {
assert(start.position + source.count <= capacity)
guard source.count > 0 else { return start }
ptr(at: start).moveInitialize(from: source.baseAddress!, count: source.count)
return Slot(at: start.position + source.count)
}
@inlinable
@inline(__always)
@discardableResult
public func move(
from source: Slot,
to target: Slot,
count: Int
) -> (source: Slot, target: Slot) {
assert(count >= 0)
assert(source.position + count <= self.capacity)
assert(target.position + count <= self.capacity)
guard count > 0 else { return (source, target) }
ptr(at: target).moveInitialize(from: ptr(at: source), count: count)
return (slot(source, offsetBy: count), slot(target, offsetBy: count))
}
}
extension Deque._UnsafeHandle {
/// Copy elements into a new storage instance without changing capacity or
/// layout.
@inlinable
internal func copyElements() -> Deque._Storage {
let object = _DequeBuffer<Element>.create(
minimumCapacity: capacity,
makingHeaderWith: { _ in header })
let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object))
guard self.count > 0 else { return result }
result.update { target in
let source = self.segments()
target.initialize(at: startSlot, from: source.first)
if let second = source.second {
target.initialize(at: .zero, from: second)
}
}
return result
}
/// Copy elements into a new storage instance with the specified minimum
/// capacity.
@inlinable
internal func copyElements(minimumCapacity: Int) -> Deque._Storage {
assert(minimumCapacity >= count)
let object = _DequeBuffer<Element>.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: {
_DequeBufferHeader(
capacity: $0.capacity,
count: count,
startSlot: .zero)
})
let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object))
guard count > 0 else { return result }
result.update { target in
assert(target.count == count && target.startSlot.position == 0)
let source = self.segments()
let next = target.initialize(at: .zero, from: source.first)
if let second = source.second {
target.initialize(at: next, from: second)
}
}
return result
}
/// Move elements into a new storage instance with the specified minimum
/// capacity. Existing indices in `self` won't necessarily be valid in the
/// result. `self` is left empty.
@inlinable
internal func moveElements(minimumCapacity: Int) -> Deque._Storage {
assertMutable()
let count = self.count
assert(minimumCapacity >= count)
let object = _DequeBuffer<Element>.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: {
_DequeBufferHeader(
capacity: $0.capacity,
count: count,
startSlot: .zero)
})
let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object))
guard count > 0 else { return result }
result.update { target in
let source = self.mutableSegments()
let next = target.moveInitialize(at: .zero, from: source.first)
if let second = source.second {
target.moveInitialize(at: next, from: second)
}
}
self.count = 0
return result
}
}
extension Deque._UnsafeHandle {
@inlinable
internal func withUnsafeSegment<R>(
startingAt start: Int,
maximumCount: Int?,
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> (end: Int, result: R) {
assert(start <= count)
guard start < count else {
return try (count, body(UnsafeBufferPointer(start: nil, count: 0)))
}
let endSlot = self.endSlot
let segmentStart = self.slot(forOffset: start)
let segmentEnd = segmentStart < endSlot ? endSlot : limSlot
let count = Swift.min(maximumCount ?? Int.max, segmentEnd.position - segmentStart.position)
let result = try body(UnsafeBufferPointer(start: ptr(at: segmentStart), count: count))
return (start + count, result)
}
}
// MARK: Replacement
extension Deque._UnsafeHandle {
/// Replace the elements in `range` with `newElements`. The deque's count must
/// not change as a result of calling this function.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func uncheckedReplaceInPlace<C: Collection>(
inOffsets range: Range<Int>,
with newElements: C
) where C.Element == Element {
assertMutable()
assert(range.upperBound <= count)
assert(newElements.count == range.count)
guard !range.isEmpty else { return }
let target = mutableSegments(forOffsets: range)
target.assign(from: newElements)
}
}
// MARK: Appending
extension Deque._UnsafeHandle {
/// Append `element` to this buffer. The buffer must have enough free capacity
/// to insert one new element.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func uncheckedAppend(_ element: Element) {
assertMutable()
assert(count < capacity)
ptr(at: endSlot).initialize(to: element)
count += 1
}
/// Append the contents of `source` to this buffer. The buffer must have
/// enough free capacity to insert the new elements.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func uncheckedAppend(contentsOf source: UnsafeBufferPointer<Element>) {
assertMutable()
assert(count + source.count <= capacity)
guard source.count > 0 else { return }
let c = self.count
count += source.count
let gap = mutableSegments(forOffsets: c ..< count)
gap.initialize(from: source)
}
}
// MARK: Prepending
extension Deque._UnsafeHandle {
@inlinable
internal func uncheckedPrepend(_ element: Element) {
assertMutable()
assert(count < capacity)
let slot = self.slot(before: startSlot)
ptr(at: slot).initialize(to: element)
startSlot = slot
count += 1
}
/// Prepend the contents of `source` to this buffer. The buffer must have
/// enough free capacity to insert the new elements.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func uncheckedPrepend(contentsOf source: UnsafeBufferPointer<Element>) {
assertMutable()
assert(count + source.count <= capacity)
guard source.count > 0 else { return }
let oldStart = startSlot
let newStart = self.slot(startSlot, offsetBy: -source.count)
startSlot = newStart
count += source.count
let gap = mutableWrappedBuffer(between: newStart, and: oldStart)
gap.initialize(from: source)
}
}
// MARK: Insertion
extension Deque._UnsafeHandle {
/// Insert all elements from `newElements` into this deque, starting at
/// `offset`.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
///
/// - Parameter newElements: The elements to insert.
/// - Parameter newCount: Must be equal to `newElements.count`. Used to
/// prevent calling `count` more than once.
/// - Parameter offset: The desired offset from the start at which to place
/// the first element.
@inlinable
internal func uncheckedInsert<C: Collection>(
contentsOf newElements: __owned C,
count newCount: Int,
atOffset offset: Int
) where C.Element == Element {
assertMutable()
assert(offset <= count)
assert(newElements.count == newCount)
guard newCount > 0 else { return }
let gap = openGap(ofSize: newCount, atOffset: offset)
gap.initialize(from: newElements)
}
@inlinable
internal func mutableWrappedBuffer(
between start: Slot,
and end: Slot
) -> _UnsafeMutableWrappedBuffer<Element> {
assert(start.position <= capacity)
assert(end.position <= capacity)
if start < end {
return .init(start: ptr(at: start), count: end.position - start.position)
}
return .init(
first: ptr(at: start), count: capacity - start.position,
second: ptr(at: .zero), count: end.position)
}
/// Slide elements around so that there is a gap of uninitialized slots of
/// size `gapSize` starting at `offset`, and return a (potentially wrapped)
/// buffer holding the newly inserted slots.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
///
/// - Parameter gapSize: The number of uninitialized slots to create.
/// - Parameter offset: The offset from the start at which the uninitialized
/// slots should start.
@inlinable
internal func openGap(
ofSize gapSize: Int,
atOffset offset: Int
) -> _UnsafeMutableWrappedBuffer<Element> {
assertMutable()
assert(offset >= 0 && offset <= self.count)
assert(self.count + gapSize <= capacity)
assert(gapSize > 0)
let headCount = offset
let tailCount = count - offset
if tailCount <= headCount {
// Open the gap by sliding elements to the right.
let originalEnd = self.slot(startSlot, offsetBy: count)
let newEnd = self.slot(startSlot, offsetBy: count + gapSize)
let gapStart = self.slot(forOffset: offset)
let gapEnd = self.slot(gapStart, offsetBy: gapSize)
let sourceIsContiguous = gapStart <= originalEnd.orIfZero(capacity)
let targetIsContiguous = gapEnd <= newEnd.orIfZero(capacity)
if sourceIsContiguous && targetIsContiguous {
// No need to deal with wrapping; we just need to slide
// elements after the gap.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) ....ABCDE̲F̲G̲H..... EFG̲H̲.̲........ABCD .̲.......ABCDEFGH̲.̲
// 1) ....ABCD.̲.̲.̲EFGH.. EF.̲.̲.̲GH......ABCD .̲H......ABCDEFG.̲.̲
move(from: gapStart, to: gapEnd, count: tailCount)
} else if targetIsContiguous {
// The gap itself will be wrapped.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) E̲FGH.........ABC̲D̲
// 1) .̲..EFGH......ABC̲D̲
// 2) .̲CDEFGH......AB.̲.̲
assert(startSlot > originalEnd.orIfZero(capacity))
move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position)
move(from: gapStart, to: gapEnd, count: capacity - gapStart.position)
} else if sourceIsContiguous {
// Opening the gap pushes subsequent elements across the wrap.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) ........ABC̲D̲E̲FGH.
// 1) GH......ABC̲D̲E̲F...
// 2) GH......AB.̲.̲.̲CDEF
move(from: limSlot.advanced(by: -gapSize), to: .zero, count: newEnd.position)
move(from: gapStart, to: gapEnd, count: tailCount - newEnd.position)
} else {
// The rest of the items are wrapped, and will remain so.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) GH.........AB̲C̲D̲EF
// 1) ...GH......AB̲C̲D̲EF
// 2) DEFGH......AB̲C̲.̲..
// 3) DEFGH......A.̲.̲.̲BC
move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position)
move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize)
move(from: gapStart, to: gapEnd, count: tailCount - gapSize - originalEnd.position)
}
count += gapSize
return mutableWrappedBuffer(between: gapStart, and: gapEnd.orIfZero(capacity))
}
// Open the gap by sliding elements to the left.
let originalStart = self.startSlot
let newStart = self.slot(originalStart, offsetBy: -gapSize)
let gapEnd = self.slot(forOffset: offset)
let gapStart = self.slot(gapEnd, offsetBy: -gapSize)
let sourceIsContiguous = originalStart <= gapEnd.orIfZero(capacity)
let targetIsContiguous = newStart <= gapStart.orIfZero(capacity)
if sourceIsContiguous && targetIsContiguous {
// No need to deal with any wrapping.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) ....A̲B̲C̲DEFGH... GH.........̲A̲B̲CDEF .̲A̲B̲CDEFGH.......̲.̲
// 1) .ABC.̲.̲.̲DEFGH... GH......AB.̲.̲.̲CDEF .̲.̲.̲CDEFGH....AB.̲.̲
move(from: originalStart, to: newStart, count: headCount)
} else if targetIsContiguous {
// The gap itself will be wrapped.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) C̲D̲EFGH.........A̲B̲
// 1) C̲D̲EFGH.....AB...̲.̲
// 2) .̲.̲EFGH.....ABCD.̲.̲
assert(originalStart >= newStart)
move(from: originalStart, to: newStart, count: capacity - originalStart.position)
move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapEnd.position)
} else if sourceIsContiguous {
// Opening the gap pushes preceding elements across the wrap.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) .AB̲C̲D̲EFGH.........
// 1) ...̲C̲D̲EFGH.......AB
// 2) CD.̲.̲.̲EFGH.......AB
move(from: originalStart, to: newStart, count: capacity - newStart.position)
move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position)
} else {
// The preceding of the items are wrapped, and will remain so.
// Illustrated steps: (underscores mark eventual gap position)
// 0) CD̲E̲F̲GHIJKL.........AB
// 1) CD̲E̲F̲GHIJKL......AB...
// 2) ..̲.̲F̲GHIJKL......ABCDE
// 3) F.̲.̲.̲GHIJKL......ABCDE
move(from: originalStart, to: newStart, count: capacity - originalStart.position)
move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapSize)
move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position)
}
startSlot = newStart
count += gapSize
return mutableWrappedBuffer(between: gapStart, and: gapEnd.orIfZero(capacity))
}
}
// MARK: Removal
extension Deque._UnsafeHandle {
@inlinable
internal func uncheckedRemoveFirst() -> Element {
assertMutable()
assert(count > 0)
let result = ptr(at: startSlot).move()
startSlot = slot(after: startSlot)
count -= 1
return result
}
@inlinable
internal func uncheckedRemoveLast() -> Element {
assertMutable()
assert(count > 0)
let slot = self.slot(forOffset: count - 1)
let result = ptr(at: slot).move()
count -= 1
return result
}
@inlinable
internal func uncheckedRemoveFirst(_ n: Int) {
assertMutable()
assert(count >= n)
guard n > 0 else { return }
let target = mutableSegments(forOffsets: 0 ..< n)
target.deinitialize()
startSlot = slot(startSlot, offsetBy: n)
count -= n
}
@inlinable
internal func uncheckedRemoveLast(_ n: Int) {
assertMutable()
assert(count >= n)
guard n > 0 else { return }
let target = mutableSegments(forOffsets: count - n ..< count)
target.deinitialize()
count -= n
}
/// Remove all elements stored in this instance, deinitializing their storage.
///
/// This method does not ensure that the storage buffer is uniquely
/// referenced.
@inlinable
internal func uncheckedRemoveAll() {
assertMutable()
guard count > 0 else { return }
let target = mutableSegments()
target.deinitialize()
count = 0
startSlot = .zero
}
/// Remove all elements in `bounds`, deinitializing their storage and sliding
/// remaining elements to close the resulting gap.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func uncheckedRemove(offsets bounds: Range<Int>) {
assertMutable()
assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count)
// Deinitialize elements in `bounds`.
mutableSegments(forOffsets: bounds).deinitialize()
closeGap(offsets: bounds)
}
/// Close the gap of already uninitialized elements in `bounds`, sliding
/// elements outside of the gap to eliminate it.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func closeGap(offsets bounds: Range<Int>) {
assertMutable()
assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count)
let gapSize = bounds.count
guard gapSize > 0 else { return }
let gapStart = self.slot(forOffset: bounds.lowerBound)
let gapEnd = self.slot(forOffset: bounds.upperBound)
let headCount = bounds.lowerBound
let tailCount = count - bounds.upperBound
if headCount >= tailCount {
// Close the gap by sliding elements to the left.
let originalEnd = endSlot
let newEnd = self.slot(forOffset: count - gapSize)
let sourceIsContiguous = gapEnd < originalEnd.orIfZero(capacity)
let targetIsContiguous = gapStart <= newEnd.orIfZero(capacity)
if tailCount == 0 {
// No need to move any elements.
} else if sourceIsContiguous && targetIsContiguous {
// No need to deal with wrapping.
// 0) ....ABCD.̲.̲.̲EFGH.. EF.̲.̲.̲GH........ABCD .̲.̲.̲E..........ABCD.̲.̲ .̲.̲.̲EF........ABCD .̲.̲.̲DE.......ABC
// 1) ....ABCDE̲F̲G̲H..... EFG̲H̲.̲..........ABCD .̲.̲.̲...........ABCDE̲.̲ E̲F̲.̲..........ABCD D̲E̲.̲.........ABC
move(from: gapEnd, to: gapStart, count: tailCount)
} else if sourceIsContiguous {
// The gap lies across the wrap from the subsequent elements.
// 0) .̲.̲.̲EFGH.......ABCD.̲.̲ EFGH.......ABCD.̲.̲.̲
// 1) .̲.̲.̲..GH.......ABCDE̲F̲ ..GH.......ABCDE̲F̲G̲
// 2) G̲H̲.̲...........ABCDE̲F̲ GH.........ABCDE̲F̲G̲
let c = capacity - gapStart.position
assert(tailCount > c)
let next = move(from: gapEnd, to: gapStart, count: c)
move(from: next.source, to: .zero, count: tailCount - c)
} else if targetIsContiguous {
// We need to move elements across a wrap, but the wrap will
// disappear when we're done.
// 0) HI....ABCDE.̲.̲.̲FG
// 1) HI....ABCDEF̲G̲.̲..
// 2) ......ABCDEF̲G̲H̲I.
let next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position)
move(from: .zero, to: next.target, count: originalEnd.position)
} else {
// We need to move elements across a wrap that won't go away.
// 0) HIJKL....ABCDE.̲.̲.̲FG
// 1) HIJKL....ABCDEF̲G̲.̲..
// 2) ...KL....ABCDEF̲G̲H̲IJ
// 3) KL.......ABCDEF̲G̲H̲IJ
var next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position)
next = move(from: .zero, to: next.target, count: gapSize)
move(from: next.source, to: .zero, count: newEnd.position)
}
count -= gapSize
} else {
// Close the gap by sliding elements to the right.
let originalStart = startSlot
let newStart = slot(startSlot, offsetBy: gapSize)
let sourceIsContiguous = originalStart < gapStart.orIfZero(capacity)
let targetIsContiguous = newStart <= gapEnd.orIfZero(capacity)
if headCount == 0 {
// No need to move any elements.
} else if sourceIsContiguous && targetIsContiguous {
// No need to deal with wrapping.
// 0) ....ABCD.̲.̲.̲EFGH..... EFGH........AB.̲.̲.̲CD .̲.̲.̲CDEFGH.......AB.̲.̲ DEFGH.......ABC.̲.̲
// 1) .......AB̲C̲D̲EFGH..... EFGH...........̲A̲B̲CD .̲A̲B̲CDEFGH..........̲.̲ DEFGH.........AB̲C̲ ABCDEFGH........̲.̲.̲
move(from: originalStart, to: newStart, count: headCount)
} else if sourceIsContiguous {
// The gap lies across the wrap from the preceding elements.
// 0) .̲.̲DEFGH.......ABC.̲.̲ .̲.̲.̲EFGH.......ABCD
// 1) B̲C̲DEFGH.......A...̲.̲ B̲C̲D̲DEFGH......A...
// 2) B̲C̲DEFGH...........̲A̲ B̲C̲D̲DEFGH.........A
move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapEnd.position)
move(from: startSlot, to: newStart, count: headCount - gapEnd.position)
} else if targetIsContiguous {
// We need to move elements across a wrap, but the wrap will
// disappear when we're done.
// 0) CD.̲.̲.̲EFGHI.....AB
// 1) ...̲C̲D̲EFGHI.....AB
// 1) .AB̲C̲D̲EFGHI.......
move(from: .zero, to: gapEnd.advanced(by: -gapStart.position), count: gapStart.position)
move(from: startSlot, to: newStart, count: headCount - gapStart.position)
} else {
// We need to move elements across a wrap that won't go away.
// 0) FG.̲.̲.̲HIJKLMNO....ABCDE
// 1) ...̲F̲G̲HIJKLMNO....ABCDE
// 2) CDE̲F̲G̲HIJKLMNO....AB...
// 3) CDE̲F̲G̲HIJKLMNO.......AB
move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: gapStart.position)
move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize)
move(from: startSlot, to: newStart, count: headCount - gapEnd.position)
}
startSlot = newStart
count -= gapSize
}
}
}
+105
View File
@@ -0,0 +1,105 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A collection implementing a double-ended queue. `Deque` (pronounced "deck")
/// implements an ordered random-access collection that supports efficient
/// insertions and removals from both ends.
///
/// var colors: Deque = ["red", "yellow", "blue"]
///
/// Deques implement the same indexing semantics as arrays: they use integer
/// indices, and the first element of a nonempty deque is always at index zero.
/// Like arrays, deques conform to `RangeReplaceableCollection`,
/// `MutableCollection` and `RandomAccessCollection`, providing a familiar
/// interface for manipulating their contents:
///
/// print(colors[1]) // "yellow"
/// print(colors[3]) // Runtime error: Index out of range
///
/// colors.insert("green", at: 1)
/// // ["red", "green", "yellow", "blue"]
///
/// colors.remove(at: 2) // "yellow"
/// // ["red", "green", "blue"]
///
/// Like all variable-size collections on the standard library, `Deque`
/// implements value semantics: each deque has an independent value that
/// includes the values of its elements. Modifying one deque does not affect any
/// others:
///
/// var copy = deque
/// copy[1] = "violet"
/// print(copy) // ["red", "violet", "blue"]
/// print(deque) // ["red", "green", "blue"]
///
/// This is implemented with the copy-on-write optimization. Multiple copies of
/// a deque share the same underlying storage until you modify one of the
/// copies. When that happens, the deque being modified replaces its storage
/// with a uniquely owned copy of itself, which is then modified in place.
///
/// `Deque` stores its elements in a circular buffer, which allows efficient
/// insertions and removals at both ends of the collection; however, this comes
/// at the cost of potentially discontiguous storage. In contrast, `Array` is
/// (usually) backed by a contiguous buffer, where new data can be efficiently
/// appended to the end, but inserting at the front is relatively slow, as
/// existing elements need to be shifted to make room.
///
/// This difference in implementation means that while the interface of a deque
/// is very similar to an array, the operations have different performance
/// characteristics. Mutations near the front are expected to be significantly
/// faster in deques, but arrays may measure slightly faster for general
/// random-access lookups.
///
/// Deques provide a handful of additional operations that make it easier to
/// insert and remove elements at the front. This includes queue operations such
/// as `popFirst` and `prepend`, including the ability to directly prepend a
/// sequence of elements:
///
/// colors.append("green")
/// colors.prepend("orange")
/// // colors: ["orange", "red", "blue", "yellow", "green"]
///
/// colors.popLast() // "green"
/// colors.popFirst() // "orange"
/// // colors: ["red", "blue", "yellow"]
///
/// colors.prepend(contentsOf: ["purple", "teal"])
/// // colors: ["purple", "teal", "red", "blue", "yellow"]
///
/// Unlike arrays, deques do not currently provide direct unsafe access to their
/// underlying storage. They also lack a `capacity` property -- the size of the
/// storage buffer at any given point is an unstable implementation detail that
/// should not affect application logic. (However, deques do provide a
/// `reserveCapacity` method.)
@frozen
public struct Deque<Element> {
@usableFromInline
internal typealias _Slot = _DequeSlot
@usableFromInline
internal var _storage: _Storage
@inlinable
internal init(_storage: _Storage) {
self._storage = _storage
}
/// Creates and empty deque with preallocated space for at least the specified
/// number of elements.
///
/// - Parameter minimumCapacity: The minimum number of elements that the
/// newly created deque should be able to store without reallocating its
/// storage buffer.
@inlinable
public init(minimumCapacity: Int) {
self._storage = _Storage(minimumCapacity: minimumCapacity)
}
}
@@ -0,0 +1,65 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Collection {
@inlinable
@inline(__always)
internal func _rebased<Element>() -> UnsafeBufferPointer<Element>
where Self == UnsafeBufferPointer<Element>.SubSequence {
.init(rebasing: self)
}
}
extension Collection {
@inlinable
@inline(__always)
internal func _rebased<Element>() -> UnsafeMutableBufferPointer<Element>
where Self == UnsafeMutableBufferPointer<Element>.SubSequence {
.init(rebasing: self)
}
}
extension UnsafeMutableBufferPointer {
@inlinable
@inline(__always)
internal func _initialize(from source: UnsafeBufferPointer<Element>) {
assert(source.count == count)
guard source.count > 0 else { return }
baseAddress!.initialize(from: source.baseAddress!, count: source.count)
}
@inlinable
@inline(__always)
internal func _initialize<C: Collection>(
from elements: C
) where C.Element == Element {
assert(elements.count == count)
var (it, copied) = elements._copyContents(initializing: self)
precondition(copied == count)
precondition(it.next() == nil)
}
@inlinable
@inline(__always)
internal func _deinitializeAll() {
guard count > 0 else { return }
baseAddress!.deinitialize(count: count)
}
@inlinable
internal func _assign<C: Collection>(
from replacement: C
) where C.Element == Element {
guard self.count > 0 else { return }
self[0 ..< count]._rebased()._deinitializeAll()
_initialize(from: replacement)
}
}
+51
View File
@@ -0,0 +1,51 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@usableFromInline
internal class _DequeBuffer<Element>: ManagedBuffer<_DequeBufferHeader, Element> {
@inlinable
deinit {
let storage = Deque<Element>._Storage(self)
storage.update { handle in
}
self.withUnsafeMutablePointers { header, elements in
header.pointee._checkInvariants()
let capacity = header.pointee.capacity
let count = header.pointee.count
let startSlot = header.pointee.startSlot
if startSlot.position + count <= capacity {
(elements + startSlot.position).deinitialize(count: count)
} else {
let firstRegion = capacity - startSlot.position
(elements + startSlot.position).deinitialize(count: firstRegion)
elements.deinitialize(count: count - firstRegion)
}
}
}
}
extension _DequeBuffer: CustomStringConvertible {
@usableFromInline
internal var description: String {
withUnsafeMutablePointerToHeader { "_DequeStorage<\(Element.self)>\($0.pointee)" }
}
}
/// The type-punned empty singleton storage instance.
@usableFromInline
internal let _emptyDequeStorage = _DequeBuffer<Void>.create(
minimumCapacity: 0,
makingHeaderWith: { _ in
_DequeBufferHeader(capacity: 0, count: 0, startSlot: .init(at: 0))
})
@@ -0,0 +1,49 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@usableFromInline
internal struct _DequeBufferHeader {
@usableFromInline
var capacity: Int
@usableFromInline
var count: Int
@usableFromInline
var startSlot: _DequeSlot
@usableFromInline
init(capacity: Int, count: Int, startSlot: _DequeSlot) {
self.capacity = capacity
self.count = count
self.startSlot = startSlot
_checkInvariants()
}
#if COLLECTIONS_INTERNAL_CHECKS
@usableFromInline @inline(never) @_effects(releasenone)
internal func _checkInvariants() {
precondition(capacity >= 0)
precondition(count >= 0 && count <= capacity)
precondition(startSlot.position >= 0 && startSlot.position <= capacity)
}
#else
@inlinable @inline(__always)
internal func _checkInvariants() {}
#endif // COLLECTIONS_INTERNAL_CHECKS
}
extension _DequeBufferHeader: CustomStringConvertible {
@usableFromInline
internal var description: String {
"(capacity: \(capacity), count: \(count), startSlot: \(startSlot))"
}
}
+72
View File
@@ -0,0 +1,72 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@usableFromInline
@frozen
internal struct _DequeSlot {
@usableFromInline
internal var position: Int
@inlinable
@inline(__always)
init(at position: Int) {
assert(position >= 0)
self.position = position
}
}
extension _DequeSlot {
@inlinable
@inline(__always)
internal static var zero: Self { Self(at: 0) }
@inlinable
@inline(__always)
internal func advanced(by delta: Int) -> Self {
Self(at: position &+ delta)
}
@inlinable
@inline(__always)
internal func orIfZero(_ value: Int) -> Self {
guard position > 0 else { return Self(at: value) }
return self
}
}
extension _DequeSlot: CustomStringConvertible {
@usableFromInline
internal var description: String {
"@\(position)"
}
}
extension _DequeSlot: Equatable {
@inlinable
@inline(__always)
static func ==(left: Self, right: Self) -> Bool {
left.position == right.position
}
}
extension _DequeSlot: Comparable {
@inlinable
@inline(__always)
static func <(left: Self, right: Self) -> Bool {
left.position < right.position
}
}
extension Range where Bound == _DequeSlot {
@inlinable
@inline(__always)
internal var _count: Int { upperBound.position - lowerBound.position }
}
@@ -0,0 +1,215 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@usableFromInline
internal struct _UnsafeWrappedBuffer<Element> {
@usableFromInline
internal let first: UnsafeBufferPointer<Element>
@usableFromInline
internal let second: UnsafeBufferPointer<Element>?
@inlinable
@inline(__always)
internal init(
_ first: UnsafeBufferPointer<Element>,
_ second: UnsafeBufferPointer<Element>? = nil
) {
self.first = first
self.second = second
assert(first.count > 0 || second == nil)
}
@inlinable
internal init(
start: UnsafePointer<Element>,
count: Int
) {
self.init(UnsafeBufferPointer(start: start, count: count))
}
@inlinable
internal init(
first start1: UnsafePointer<Element>,
count count1: Int,
second start2: UnsafePointer<Element>,
count count2: Int
) {
self.init(UnsafeBufferPointer(start: start1, count: count1),
UnsafeBufferPointer(start: start2, count: count2))
}
@inlinable
internal var count: Int { first.count + (second?.count ?? 0) }
}
@usableFromInline
internal struct _UnsafeMutableWrappedBuffer<Element> {
@usableFromInline
internal let first: UnsafeMutableBufferPointer<Element>
@usableFromInline
internal let second: UnsafeMutableBufferPointer<Element>?
@inlinable
@inline(__always)
internal init(
_ first: UnsafeMutableBufferPointer<Element>,
_ second: UnsafeMutableBufferPointer<Element>? = nil
) {
self.first = first
self.second = second?.count == 0 ? nil : second
assert(first.count > 0 || second == nil)
}
@inlinable
@inline(__always)
internal init(
start: UnsafeMutablePointer<Element>,
count: Int
) {
self.init(UnsafeMutableBufferPointer(start: start, count: count))
}
@inlinable
@inline(__always)
internal init(
first start1: UnsafeMutablePointer<Element>,
count count1: Int,
second start2: UnsafeMutablePointer<Element>,
count count2: Int
) {
self.init(UnsafeMutableBufferPointer(start: start1, count: count1),
UnsafeMutableBufferPointer(start: start2, count: count2))
}
@inlinable
@inline(__always)
internal init(mutating buffer: _UnsafeWrappedBuffer<Element>) {
self.init(.init(mutating: buffer.first),
buffer.second.map { .init(mutating: $0) })
}
}
extension _UnsafeMutableWrappedBuffer {
@inlinable
@inline(__always)
internal var count: Int { first.count + (second?.count ?? 0) }
@inlinable
internal func prefix(_ n: Int) -> Self {
assert(n >= 0)
if n >= self.count {
return self
}
if n <= first.count {
return Self(first.prefix(n)._rebased())
}
return Self(first, second!.prefix(n - first.count)._rebased())
}
@inlinable
internal func suffix(_ n: Int) -> Self {
assert(n >= 0)
if n >= self.count {
return self
}
guard let second = second else {
return Self(first.suffix(n)._rebased())
}
if n <= second.count {
return Self(second.suffix(n)._rebased())
}
return Self(first.suffix(n - second.count)._rebased(), second)
}
}
extension _UnsafeMutableWrappedBuffer {
@inlinable
internal func deinitialize() {
first._deinitializeAll()
second?._deinitializeAll()
}
@inlinable
@discardableResult
internal func initialize<I: IteratorProtocol>(
fromPrefixOf iterator: inout I
) -> Int
where I.Element == Element {
var copied = 0
var gap = first
var wrapped = false
while true {
if copied == gap.count {
guard !wrapped, let second = second, second.count > 0 else { break }
gap = second
copied = 0
wrapped = true
}
guard let next = iterator.next() else { break }
(gap.baseAddress! + copied).initialize(to: next)
copied += 1
}
return wrapped ? first.count + copied : copied
}
@inlinable
internal func initialize<S: Sequence>(
fromSequencePrefix elements: __owned S
) -> (iterator: S.Iterator, count: Int)
where S.Element == Element {
guard second == nil || first.count >= elements.underestimatedCount else {
var it = elements.makeIterator()
let copied = initialize(fromPrefixOf: &it)
return (it, copied)
}
// Note: Array._copyContents traps when not given enough space, so we
// need to check if we have enough contiguous space available above.
//
// FIXME: Add suppport for segmented (a.k.a. piecewise contiguous)
// collections to the stdlib.
var (it, copied) = elements._copyContents(initializing: first)
if copied == first.count, let second = second {
var i = 0
while i < second.count {
guard let next = it.next() else { break }
(second.baseAddress! + i).initialize(to: next)
i += 1
}
copied += i
}
return (it, copied)
}
@inlinable
internal func initialize<C: Collection>(
from elements: __owned C
) where C.Element == Element {
assert(self.count == elements.count)
if let second = second {
let wrap = elements.index(elements.startIndex, offsetBy: first.count)
first._initialize(from: elements[..<wrap])
second._initialize(from: elements[wrap...])
} else {
first._initialize(from: elements)
}
}
@inlinable
internal func assign<C: Collection>(
from elements: C
) where C.Element == Element {
assert(elements.count == self.count)
deinitialize()
initialize(from: elements)
}
}
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff. Show more