Vendor dependencies for 0.3.0 release

This commit is contained in:
2025-09-27 10:29:08 -05:00
parent 0c8d39d483
commit 82ab7f317b
26803 changed files with 16134934 additions and 0 deletions

1
vendor/rangemap/.cargo-checksum.json vendored Normal file
View File

@@ -0,0 +1 @@
{"files":{"CHANGELOG.md":"0c22f36d46e423eb4ff8218995e7605176542c31731a310c77a2259a39074c78","Cargo.lock":"e85965e3c4a21de6c22d20530f5457ca9374f80a85b6fe7fcfa41678f4180984","Cargo.toml":"d0840e2743d7eb1ef748c6524495af0be0ff58d63cbc63c0f7aaf3e6eb9aa4fd","LICENSE-APACHE":"1c7745cc26c7294bc9dbc883bcd50700b99a8c0f4859bfce84ec555098ce1ab5","LICENSE-MIT":"29a4c3823ee29ee5a97c145574a1bac20629fd5e6708be1df0d25bab563e093c","README.fuzz.md":"43396a2d0ee5243adb2790de8d8d52f8790e60a73167280154439b9873658221","README.md":"913d6a3e512ecb3ea1f446127b16875ef34d370a03bf8c7b03f201955d4455ba","benches/benches.rs":"2209cd1b5ed18ff296dc0ae96eaf488d6ff284f02ef1f7c76cecac89e6f61e91","bors.toml":"0f1068aff39c2cf9048b413575122b78ba8875f2e54beb4906c3cf2c852e1d06","examples/roster.rs":"f896e2bd1e528bfaae8422d78d9babf9e9507bb830c95b73fcf91da33822bb2e","pre_commit.sh":"84fbe9d246965119ca8a8850919dcc4c8395946d432b70528c3b76e189469d70","src/dense.rs":"33fa39c373054c80e5e743fe48dc4e96ff5ba7b9b0731a716abdf9cf392b1d88","src/inclusive_map.rs":"852736a9f91eb0ee2ef24e57cbdab5a9df126607d65bb666969a9c1c63c56b63","src/inclusive_set.rs":"1278b5f67d786a85106e7f7cdf005e953f847c30ef5cae435f3e232a75d5372d","src/lib.rs":"92b1d65426b93ec9489d6e8172f179175d38e5c57b0ddbf199fc425ea51728b7","src/map.rs":"303d5c2eb98a7543b60929648722549f1852e9f627fa1499a861e35808b599c7","src/operations.rs":"3de117027ebee26ff1150602a0245a7ee71e4fee72dfd8b190dda417fcb7b811","src/range_wrapper.rs":"224061af79ed9b5660cc1103c84d01ba15590eef2209ef1d49c7a1148e21112d","src/readme.rs":"89bed5bbb369d37e265d86acd9ee9cca492981a376cd0ca84804cdc70f5ff827","src/set.rs":"d6743d0bb6f3edbeb371a03d51b2e65f3126e9569cc0a56601108dea0e46a2b5","src/std_ext.rs":"98478984a77e0f1acc797bc357f85cd7ba6ce493a0f8453104531f11651d6730"},"package":"f93e7e49bb0bf967717f7bd674458b3d6b0c5f48ec7e3038166026a69fc22223"}

153
vendor/rangemap/CHANGELOG.md vendored Normal file
View File

@@ -0,0 +1,153 @@
### v1.6.0 (2025-07-26)
- **Features**:
- Add quickcheck support, gated behind the `quickcheck` feature.
- Improve performance of `RangeMap::gaps` by efficiently seeking to the start of the query range.
### v1.5.1 (2024-02-27)
- **Fixes**:
- Relax bounds on `Default` implementation for all map and set types. Requiring `K: Default` and `V: Default` was accidentally introduced in v1.5.0.
### v1.5.0 (2024-02-09) "xfbs rampage edition"
Huge thanks to [xfbs](https://github.com/xfbs), who did pretty much all the work you see in the changelog below! 💖
- **Features**:
- Add `union` and `intersection` methods to iterate over the union or intersection of two sets.
- Add `first_range_value` and `last_range_value` methods to map types and `first` and `last` methods to set types.
- Add literal macros for all collection types — e.g. `range_set![0..100, 200..300, 400..500]`.
- Implement `Default` and `Hash` for all collection types.
- Implement `DoubleEndedIterator` for all iterators.
- Implement `From<[_; N]>` (e.g. `From<[Range<T>; N]> for RangeSet<T>`) for all collections. (Previously you could build a collection from an iterator, but not directly from an array.)
- Implement `BitOr` and `BitAnd` for set types. (Convenience wrapper around the `union` and `intersection` methods mentioned above.)
- Accept any `R: Borrow<Range<K>>` as argument to `overlapping` methods, allowing it to take ranges by value.
- **Changes**:
- Bump minimum supported Rust version to 1.66.0 (released 2022-12-15). This is to gain access to `BTreeMap::first_key_value` and `BTreeMap::last_key_value`, and for compatibility with new versions of some of rangemap's test dependencies.
- **Internal**:
- New benchmarks and improved test coverage.
### v1.4.0 (2023-09-19)
- **Changes**:
- Bump minimum supported Rust version to 1.61.0 (released 2022-05-19). This is for compatibility with new versions of some of rangemap's test dependencies.
### v1.3.1 (2023-09-19)
- **Fixes**:
- Fix `PartialEq`, `PartialOrd`, and `Ord` implementations for `RangeMap` (and `RangeSet`). These previously only compared the starts of ranges instead of the entire range. Thanks to https://github.com/hecrj for finding and fixing this!
- **Changes**:
- Minimum supported Rust version for running this crate's tests has increased to 1.61.0 due to a corresponding MSRV bump in a test dependency. This is causing CI builds to fail against rustc 1.56.1, but should not affect consumers of the crate. The next minor release (1.4.0) will bump the minimum supported Rust version of rangemap itself.
### v1.3.0 (2023-01-03)
- **Features**:
- Add `overlapping` method to all collection types, which returns an iterator over all stored entries that completely or partially overlap a given range.
- Add `overlaps` convenience method to all collection types, which returns whether any stored range completely or partially overlaps a given range.
- Credit to [Rua](https://github.com/Rua) for the original implementation of these new methods. (Unfortunately I couldn't use their code directly because I made other incompatible changes.) Thanks also to [rumpuslabs](https://github.com/rumpuslabs) for their engagement.
### v1.2.0 (2022-12-27)
- **Features**:
- Add `clear`, `len`, and `is_empty` methods for all map and set types.
- **Fixes**:
- Make `const_fn` feature work again. (Previous release accidentally broke the const versions of `RangeMap::new` and `RangeSet::new`.)
### v1.1.0 (2022-11-12)
- **Features**:
- Implement `PartialEq`, `Eq`, `PartialOrd`, and `Ord` for all map and set types.
- Make `new` functions for all map and set types `const` when `const_fn` feature is enabled.
- **Changes**:
- Bump minimum supported Rust version to 1.56.1. (Released a year ago.) This is for compatibility with new versions of some of rangemap's development dependencies.
### v1.0.3 (2022-06-11)
- **Fixes**:
- Fix `Gaps` iterator for `RangeMap` yielding an empty gap for an empty outer range. Simplified gaps logic and expanded fuzz testing to better cover this and similar cases.
### v1.0.2 (2022-05-17)
- **Fixes**:
- Fix empty gaps returned by `Gaps` iterator for `RangeInclusiveMap`. Added fuzz tests for `Gaps` iterators.
### v1.0.1 (2022-01-29)
- **Fixes**:
- Fix empty gaps returned by `Gaps` iterator for `RangeMap`, and incorrect gaps returned by `Gaps` iterator for `RangeInclusiveMap`.
### v1.0.0 (2022-01-28)
It's time. (No functional change.)
### v0.1.14 (2021-11-16)
- **Features**:
- Expose nameable types for iterators: `Iterator`, `IntoIterator`, `Gaps` (for each collection type).
- **Changes**:
- Document overflow behaviour required by implementors of `StepLite` and `StepFns`.
### v0.1.13 (2021-08-25)
- **Features**:
- Add serde support.
### v0.1.12 (2021-08-23)
- **Features**:
- Implement more traits for all map and set types: `IntoIter`, `FromIter`, and `Extend`.
- **Changes**:
- Bump minimum supported Rust version to 1.46.
### v0.1.11 (2021-06-30) "EOFY edition"
- **Features**:
- Support `no_std` environments.
- **Changes**:
- Update all dev-dependencies to latest versions.
### v0.1.10 (2021-02-23)
- **Fixes**:
- Fix performance regression introduced in v0.1.9, which made inserts extremely slow for large maps.
### v0.1.9 (2021-02-23)
- **Fixes**:
- Fix coalescing of contiguous ranges. In some cases `RangeMap` and `RangeInclusiveMap` would leave two separate contiguous ranges with the same value instead of combining them into one.
### v0.1.8 (2020-11-22)
- **Features**:
- Implement `Debug` for all map and set types.
### v0.1.7 (2020-09-07)
- **Features**:
- Add `gaps` method to all map and set types for iterating over sub-ranges of a given outer range that are not covered by any stored range.
### v0.1.6 (2020-07-15)
- **Features**:
- Add `RangeInclusiveMap` and `RangeInclusiveSet` types for storing closed ranges.

1044
vendor/rangemap/Cargo.lock generated vendored Normal file

File diff suppressed because it is too large Load Diff

85
vendor/rangemap/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,85 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
rust-version = "1.66.0"
name = "rangemap"
version = "1.6.0"
authors = ["Jeff Parsons <jeff@parsons.io>"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = """
Map and set data structures whose keys are stored as ranges.
Contiguous and overlapping ranges that map to the same value are coalesced into a single range.
"""
homepage = "https://github.com/jeffparsons/rangemap"
documentation = "https://docs.rs/rangemap"
readme = "README.md"
categories = ["data-structures"]
license = "MIT/Apache-2.0"
repository = "https://github.com/jeffparsons/rangemap"
[features]
const_fn = []
nightly = []
quickcheck = ["dep:quickcheck"]
serde1 = ["serde"]
[lib]
name = "rangemap"
path = "src/lib.rs"
[[example]]
name = "roster"
path = "examples/roster.rs"
[[bench]]
name = "benches"
path = "benches/benches.rs"
harness = false
[dependencies.quickcheck]
version = "1.0.3"
optional = true
[dependencies.serde]
version = "1"
optional = true
[dev-dependencies.chrono]
version = "0.4"
[dev-dependencies.criterion]
version = "= 0.3.5"
[dev-dependencies.permutator]
version = "0.4"
[dev-dependencies.proptest]
version = "1.4.0"
[dev-dependencies.rand]
version = "0.8"
[dev-dependencies.rustc_version]
version = "0.4"
[dev-dependencies.serde_json]
version = "1"
[dev-dependencies.test-strategy]
version = "0.3.1"

191
vendor/rangemap/LICENSE-APACHE vendored Normal file
View File

@@ -0,0 +1,191 @@
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
Copyright 2019-2022 Jeff Parsons, and [contributors](https://github.com/jeffparsons/rangemap/contributors)
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.

7
vendor/rangemap/LICENSE-MIT vendored Normal file
View File

@@ -0,0 +1,7 @@
Copyright 2019 Jeffrey Parsons
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

12
vendor/rangemap/README.fuzz.md vendored Normal file
View File

@@ -0,0 +1,12 @@
# rangemap fuzz tests
These fuzz tests use the [cargo-fuzz](https://github.com/rust-fuzz/cargo-fuzz) tool.
Run one of these:
```
cargo +nightly fuzz run rangemap_coalesce
cargo +nightly fuzz run rangemap_inclusive_coalesce
cargo +nightly fuzz run rangemap_gaps
cargo +nightly fuzz run rangemap_inclusive_gaps
```

137
vendor/rangemap/README.md vendored Normal file
View File

@@ -0,0 +1,137 @@
# rangemap
[![Crate](https://img.shields.io/crates/v/rangemap.svg)](https://crates.io/crates/rangemap)
[![Docs](https://docs.rs/rangemap/badge.svg)](https://docs.rs/rangemap)
[![Build status](https://github.com/jeffparsons/rangemap/workflows/CI/badge.svg)](https://github.com/jeffparsons/rangemap/actions)
[![Rust](https://img.shields.io/badge/rust-1.66.0%2B-blue.svg?maxAge=3600)](https://github.com/jeffparsons/rangemap) <!-- Don't forget to update the GitHub actions config when bumping minimum Rust version. -->
[`RangeMap`] and [`RangeInclusiveMap`] are map data structures whose keys
are stored as ranges. Contiguous and overlapping ranges that map to the same
value are coalesced into a single range.
Corresponding [`RangeSet`] and [`RangeInclusiveSet`] structures are also provided.
## Different kinds of ranges
`RangeMap` and `RangeInclusiveMap` correspond to the [`Range`]
and [`RangeInclusive`] types from the standard library respectively.
For some applications the choice of range type may be obvious,
or even be dictated by pre-existing design decisions. For other applications
the choice may seem arbitrary, and be guided instead by convenience or
aesthetic preference.
If the choice is not obvious in your case, consider these differences:
- If your key type `K` represents points on a continuum (e.g. `f64`),
and the choice of which of two adjacent ranges "owns" the value
where they touch is largely arbitrary, then it may be more natural
to work with half-open `Range`s like `0.0..1.0` and `1.0..2.0`. If you
were to use closed `RangeInclusive`s here instead, then to represent two such adjacent
ranges you would need to subtract some infinitesimal (which may depend,
as it does in the case of `f64`, on the specific value of `K`)
from the end of the earlier range. (See the last point below for more
on this problem.)
- If you need to represent ranges that _include_ the maximum
value in the key domain (e.g. `255u8`) then you will
probably want to use `RangeInclusive`s like `128u8..=255u8`. Sometimes
it may be possible to instead work around this by using a wider key
type than the values you are actually trying to represent (`K=u16`
even though you are only trying to represent ranges covering `u8`)
but in these cases the key domain often represents discrete objects
rather than points on a continuum, and so `RangeInclusive` may
be a more natural way to express these ranges anyway.
- If you are using `RangeInclusive`, then it must be possible to define
_successor_ and _predecessor_ functions for your key type `K`,
because adjacent ranges can not be detected (and thereby coalesced)
simply by testing their ends for equality. For key types that represent
points on a continuum, defining these functions may be awkward and error-prone.
For key types that represent discrete objects, this is usually much
more straightforward.
## Example: use with Chrono
```rust
use chrono::offset::TimeZone;
use chrono::{Duration, Utc};
use rangemap::RangeMap;
fn main() {
let people = ["Alice", "Bob", "Carol"];
let mut roster = RangeMap::new();
// Set up initial roster.
let start_of_roster = Utc.ymd(2019, 1, 7);
let mut week_start = start_of_roster;
for _ in 0..3 {
for person in &people {
let next_week = week_start + Duration::weeks(1);
roster.insert(week_start..next_week, person);
week_start = next_week;
}
}
// Bob is covering Alice's second shift (the fourth shift overall).
let fourth_shift_start = start_of_roster + Duration::weeks(3);
let fourth_shift_end = fourth_shift_start + Duration::weeks(1);
roster.insert(fourth_shift_start..fourth_shift_end, &"Bob");
for (range, person) in roster.iter() {
println!("{} ({}): {}", range.start, range.end - range.start, person);
}
// Output:
// 2019-01-07UTC (P7D): Alice
// 2019-01-14UTC (P7D): Bob
// 2019-01-21UTC (P7D): Carol
// 2019-01-28UTC (P14D): Bob
// 2019-02-11UTC (P7D): Carol
// 2019-02-18UTC (P7D): Alice
// 2019-02-25UTC (P7D): Bob
// 2019-03-04UTC (P7D): Carol
}
```
## Crate features
By default this crate has no dependencies on other crates.
If you enable the **serde1** feature it will introduce a dependency on
the _serde_ crate and provide `Serialize` and `Deserialize`
implementations for all map and set types in this crate.
You can enable the **serde1** feature in your _Cargo.toml_ file like so:
```toml
[dependencies]
rangemap = { version = "1", features = ["serde1"] }
```
You can similarly enable support for _quickcheck_ by enabling
the **quickcheck** feature.
## Building without the Rust standard library
This crate can work without the full standard library available
(e.g. when running on bare metal without an operating system)
but relies on the presence of a global allocator &mdash;
i.e. it links the `core` and `alloc` crates, but not `std`.
Presently there is no functionality in the crate that require
the standard library. Such functionality will likely be
introduced in the future, and will be gated behind a default-on
`std` feature.
See [The Rust Programming Language](https://doc.rust-lang.org/1.7.0/book/no-stdlib.html)
book for general information about operating without the standard library.
[`RangeMap`]: https://docs.rs/rangemap/latest/rangemap/map/struct.RangeMap.html
[`RangeInclusiveMap`]: https://docs.rs/rangemap/latest/rangemap/inclusive_map/struct.RangeInclusiveMap.html
[`RangeSet`]: https://docs.rs/rangemap/latest/rangemap/set/struct.RangeSet.html
[`RangeInclusiveSet`]: https://docs.rs/rangemap/latest/rangemap/inclusive_set/struct.RangeInclusiveSet.html
[`Range`]: https://doc.rust-lang.org/stable/std/ops/struct.Range.html
[`RangeInclusive`]: https://doc.rust-lang.org/stable/std/ops/struct.RangeInclusive.html

166
vendor/rangemap/benches/benches.rs vendored Normal file
View File

@@ -0,0 +1,166 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput};
use proptest::{prelude::*, strategy::ValueTree, test_runner::TestRunner};
use rangemap::*;
use std::{any::type_name, fmt::Debug, ops::*};
use test_strategy::Arbitrary;
type Key = i64;
type Value = i64;
const COUNT: usize = 100000;
const OPERATIONS: usize = 100000;
const LOOKUPS: usize = 1000000;
#[derive(Debug, Clone, Arbitrary)]
enum Operation<K, V> {
Insert(K, V),
Delete(K),
}
fn range_inclusive_map<K: Ord + StepLite + Debug + Clone, V: Eq + Clone + Debug>(
values: impl Strategy<Value = (RangeInclusive<K>, V)>,
size: usize,
) -> impl Strategy<Value = RangeInclusiveMap<K, V>> {
prop::collection::vec(values, size)
.prop_map(|ranges| ranges.into_iter().collect::<RangeInclusiveMap<K, V>>())
}
fn range_map<K: Ord + StepLite + Debug + Clone, V: Eq + Clone + Debug>(
values: impl Strategy<Value = (Range<K>, V)>,
size: usize,
) -> impl Strategy<Value = RangeMap<K, V>> {
prop::collection::vec(values, size)
.prop_map(|ranges| ranges.into_iter().collect::<RangeMap<K, V>>())
}
fn criterion_benchmark(c: &mut Criterion) {
let mut runner = TestRunner::deterministic();
let mut group = c.benchmark_group(format!(
"RangeMap<{}, {}>",
type_name::<Key>(),
type_name::<Value>()
));
group.throughput(Throughput::Elements(COUNT as u64));
group.bench_function("insert", |b| {
let entries = prop::collection::vec(any::<(Range<Key>, Value)>(), COUNT)
.new_tree(&mut runner)
.unwrap()
.current();
b.iter_with_large_drop(|| {
let mut map = RangeMap::new();
for (range, value) in entries.clone().into_iter() {
map.insert(range, value);
}
map
})
});
group.throughput(Throughput::Elements(OPERATIONS as u64));
group.bench_function("operations", |b| {
let map = range_map(any::<(Range<Key>, Value)>(), COUNT)
.new_tree(&mut runner)
.unwrap()
.current();
let operations = prop::collection::vec(any::<Operation<Range<Key>, Value>>(), OPERATIONS)
.new_tree(&mut runner)
.unwrap()
.current();
b.iter_with_large_drop(|| {
let mut map = map.clone();
for operation in operations.clone().into_iter() {
match operation {
Operation::Insert(key, value) => map.insert(key, value),
Operation::Delete(key) => map.remove(key),
}
}
map
})
});
group.throughput(Throughput::Elements(LOOKUPS as u64));
group.bench_function("lookups", |b| {
let map = range_map(any::<(Range<Key>, Value)>(), COUNT)
.new_tree(&mut runner)
.unwrap()
.current();
let lookups = prop::collection::vec(any::<Key>(), LOOKUPS)
.new_tree(&mut runner)
.unwrap()
.current();
b.iter(|| {
for lookup in lookups.iter() {
black_box(map.get(lookup));
}
})
});
group.finish();
let mut group = c.benchmark_group(format!(
"RangeInclusiveMap<{}, {}>",
type_name::<Key>(),
type_name::<Value>()
));
group.throughput(Throughput::Elements(COUNT as u64));
group.bench_function("insert", |b| {
let entries = prop::collection::vec(any::<(RangeInclusive<Key>, Value)>(), COUNT)
.new_tree(&mut runner)
.unwrap()
.current();
b.iter_with_large_drop(|| {
let mut map = RangeInclusiveMap::new();
for (range, value) in entries.clone().into_iter() {
map.insert(range, value);
}
map
})
});
group.throughput(Throughput::Elements(OPERATIONS as u64));
group.bench_function("operations", |b| {
let map = range_inclusive_map(any::<(RangeInclusive<Key>, Value)>(), COUNT)
.new_tree(&mut runner)
.unwrap()
.current();
let operations =
prop::collection::vec(any::<Operation<RangeInclusive<Key>, Value>>(), OPERATIONS)
.new_tree(&mut runner)
.unwrap()
.current();
b.iter_with_large_drop(|| {
let mut map = map.clone();
for operation in operations.clone().into_iter() {
match operation {
Operation::Insert(key, value) => map.insert(key, value),
Operation::Delete(key) => map.remove(key),
}
}
map
})
});
group.throughput(Throughput::Elements(LOOKUPS as u64));
group.bench_function("lookups", |b| {
let map = range_inclusive_map(any::<(RangeInclusive<Key>, Value)>(), COUNT)
.new_tree(&mut runner)
.unwrap()
.current();
let lookups = prop::collection::vec(any::<Key>(), LOOKUPS)
.new_tree(&mut runner)
.unwrap()
.current();
b.iter(|| {
for lookup in lookups.iter() {
black_box(map.get(lookup));
}
})
});
group.finish();
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

2
vendor/rangemap/bors.toml vendored Normal file
View File

@@ -0,0 +1,2 @@
status = [ "ci" ]
timeout_sec = 3600 # One hour

31
vendor/rangemap/examples/roster.rs vendored Normal file
View File

@@ -0,0 +1,31 @@
use chrono::offset::TimeZone;
use chrono::{Duration, Utc};
use rangemap::RangeMap;
fn main() {
let people = ["Alice", "Bob", "Carol"];
let mut roster = RangeMap::new();
// Set up initial roster.
let start_of_roster = Utc.with_ymd_and_hms(2019, 1, 7, 0, 0, 0).unwrap();
let mut week_start = start_of_roster;
for _ in 0..3 {
for person in &people {
let next_week = week_start + Duration::weeks(1);
roster.insert(week_start..next_week, person);
week_start = next_week;
}
}
// Bob is covering Alice's second shift (the fourth shift overall).
let fourth_shift_start = start_of_roster + Duration::weeks(3);
let fourth_shift_end = fourth_shift_start + Duration::weeks(1);
roster.insert(fourth_shift_start..fourth_shift_end, &"Bob");
// Print out the roster, and observe that
// the fourth and fifth shifts have been coalesced
// into one range.
for (range, person) in roster.iter() {
println!("{} ({}): {}", range.start, range.end - range.start, person);
}
}

14
vendor/rangemap/pre_commit.sh vendored Executable file
View File

@@ -0,0 +1,14 @@
#!/bin/bash
set -ex
cargo test
# For doc tests in "README.md".
cargo +nightly test --features nightly
# And just with serde1.
cargo test --features serde1
# And with const functions.
cargo +nightly test --features const_fn
cargo run --example roster
cargo fmt
cargo clippy --bins --examples --tests --benches -- -D warnings

158
vendor/rangemap/src/dense.rs vendored Normal file
View File

@@ -0,0 +1,158 @@
use alloc::{collections::BTreeMap, vec::Vec};
use core::ops::{Range, RangeInclusive};
use super::{RangeInclusiveMap, RangeMap};
// A simple but infeasibly slow and memory-hungry
// version of `RangeInclusiveMap` for testing.
//
// Only understands `u32` keys, so that we don't
// have to be generic over `step`. This is just for
// testing, so it's fine.
//
// Note that even though this mirrors the semantics
// of `RangeInclusiveMap`, it can also be used to
// test `RangeMap` just fine.
#[derive(Eq, PartialEq, Debug)]
pub struct DenseU32RangeMap<V> {
// Inner B-Tree map. Stores values and their keys
// directly rather than as ranges.
btm: BTreeMap<u32, V>,
}
impl<V> DenseU32RangeMap<V>
where
V: Eq + Clone,
{
pub fn new() -> DenseU32RangeMap<V> {
DenseU32RangeMap {
btm: BTreeMap::new(),
}
}
pub fn insert(&mut self, range: RangeInclusive<u32>, value: V) {
for k in range {
self.btm.insert(k, value.clone());
}
}
pub fn iter(&self) -> Iter<'_, V> {
Iter {
inner: self.btm.iter(),
current: None,
}
}
pub fn end_exclusive_iter(&self) -> EndExclusiveIter<'_, V> {
EndExclusiveIter { inner: self.iter() }
}
// Vecs are easier to use for assertions than iterators,
// because you don't have to consume them to compare them.
pub fn to_vec(&self) -> Vec<(RangeInclusive<u32>, V)> {
self.iter()
.map(|(range, value)| (range, value.clone()))
.collect()
}
pub fn to_end_exclusive_vec(&self) -> Vec<(Range<u32>, V)> {
self.end_exclusive_iter()
.map(|(range, value)| (range, value.clone()))
.collect()
}
}
impl<V> From<RangeMap<u32, V>> for DenseU32RangeMap<V>
where
V: Eq + Clone,
{
fn from(range_map: RangeMap<u32, V>) -> Self {
let mut dense = Self::new();
for (range, value) in range_map.iter() {
// Convert to inclusive end.
// (This is only valid because u32 has
// the "successor function".)
//
// NOTE: Clippy's `range_minus_one` lint is a bit overzealous here,
// because we _can't_ pass an open-ended range to `insert`.
#[allow(clippy::range_minus_one)]
dense.insert(range.start..=(range.end - 1), value.clone());
}
dense
}
}
impl<V> From<RangeInclusiveMap<u32, V>> for DenseU32RangeMap<V>
where
V: Eq + Clone,
{
fn from(range_inclusive_map: RangeInclusiveMap<u32, V, u32>) -> Self {
let mut dense = Self::new();
for (range, value) in range_inclusive_map.iter() {
dense.insert(range.clone(), value.clone());
}
dense
}
}
pub struct Iter<'a, V> {
inner: alloc::collections::btree_map::Iter<'a, u32, V>,
// Current range being built for output.
// We modify it as we iterate through the underlying
// dense map.
current: Option<(RangeInclusive<u32>, &'a V)>,
}
// Coalesce items from the underlying dense map as we go.
impl<'a, V> Iterator for Iter<'a, V>
where
V: 'a + Eq,
{
type Item = (RangeInclusive<u32>, &'a V);
fn next(&mut self) -> Option<(RangeInclusive<u32>, &'a V)> {
if let Some(next_dense) = self.inner.next() {
if let Some(current) = &mut self.current {
// We're already building a range. Can we extend it?
if current.0.end() + 1 == *next_dense.0 && *current.1 == *next_dense.1 {
// This immediately follows the last item and the value is the same;
// we can extend it.
*current = (*current.0.start()..=*next_dense.0, current.1);
// Recurse until we find a way to flush it.
self.next()
} else {
// There's a gap or the value differs; flush the one we were working on and start a new one.
let item_to_yield = current.clone();
*current = (*next_dense.0..=*next_dense.0, next_dense.1);
Some(item_to_yield)
}
} else {
// We're not building a range yet; start a new one.
self.current = Some((*next_dense.0..=*next_dense.0, next_dense.1));
// Recurse until we find a way to flush it.
self.next()
}
} else {
// We reached the end of the underlying dense map.
// Flush the item we were building, if any.
self.current.take()
}
}
}
pub struct EndExclusiveIter<'a, V> {
inner: Iter<'a, V>,
}
impl<'a, V> Iterator for EndExclusiveIter<'a, V>
where
V: 'a + Eq,
{
type Item = (Range<u32>, &'a V);
fn next(&mut self) -> Option<(Range<u32>, &'a V)> {
self.inner
.next()
.map(|(range, value)| ((*range.start())..(*range.end() + 1), value))
}
}

1944
vendor/rangemap/src/inclusive_map.rs vendored Normal file

File diff suppressed because it is too large Load Diff

849
vendor/rangemap/src/inclusive_set.rs vendored Normal file
View File

@@ -0,0 +1,849 @@
use core::borrow::Borrow;
use core::fmt::{self, Debug};
use core::iter::{DoubleEndedIterator, FromIterator};
use core::ops::{BitAnd, BitOr, RangeInclusive};
#[cfg(feature = "serde1")]
use core::marker::PhantomData;
#[cfg(feature = "serde1")]
use serde::{
de::{Deserialize, Deserializer, SeqAccess, Visitor},
ser::{Serialize, Serializer},
};
use crate::std_ext::*;
use crate::RangeInclusiveMap;
/// Intersection iterator over two [`RangeInclusiveSet`].
pub type Intersection<'a, T> = crate::operations::Intersection<'a, RangeInclusive<T>, Iter<'a, T>>;
/// Union iterator over two [`RangeInclusiveSet`].
pub type Union<'a, T> = crate::operations::Union<'a, RangeInclusive<T>, Iter<'a, T>>;
#[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Ord)]
/// A set whose items are stored as ranges bounded
/// inclusively below and above `(start..=end)`.
///
/// See [`RangeInclusiveMap`]'s documentation for more details.
///
/// [`RangeInclusiveMap`]: crate::RangeInclusiveMap
pub struct RangeInclusiveSet<T, StepFnsT = T> {
rm: RangeInclusiveMap<T, (), StepFnsT>,
}
impl<T, StepFnsT> Default for RangeInclusiveSet<T, StepFnsT> {
fn default() -> Self {
Self {
rm: RangeInclusiveMap::default(),
}
}
}
#[cfg(feature = "quickcheck")]
impl<K> quickcheck::Arbitrary for RangeInclusiveSet<K>
where
K: quickcheck::Arbitrary + Ord + StepLite,
{
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
Self {
rm: RangeInclusiveMap::arbitrary(g),
}
}
}
impl<T> RangeInclusiveSet<T, T>
where
T: Ord + Clone + StepLite,
{
/// Makes a new empty `RangeInclusiveSet`.
#[cfg(feature = "const_fn")]
pub const fn new() -> Self {
Self::new_with_step_fns()
}
/// Makes a new empty `RangeInclusiveSet`.
#[cfg(not(feature = "const_fn"))]
pub fn new() -> Self {
Self::new_with_step_fns()
}
}
impl<T, StepFnsT> RangeInclusiveSet<T, StepFnsT>
where
T: Ord + Clone,
StepFnsT: StepFns<T>,
{
/// Makes a new empty `RangeInclusiveSet`, specifying successor and
/// predecessor functions defined separately from `T` itself.
///
/// This is useful as a workaround for Rust's "orphan rules",
/// which prevent you from implementing `StepLite` for `T` if `T`
/// is a foreign type.
///
/// **NOTE:** This will likely be deprecated and then eventually
/// removed once the standard library's [Step](core::iter::Step)
/// trait is stabilised, as most crates will then likely implement [Step](core::iter::Step)
/// for their types where appropriate.
///
/// See [this issue](https://github.com/rust-lang/rust/issues/42168)
/// for details about that stabilization process.
#[cfg(not(feature = "const_fn"))]
pub fn new_with_step_fns() -> Self {
Self {
rm: RangeInclusiveMap::new_with_step_fns(),
}
}
#[cfg(feature = "const_fn")]
pub const fn new_with_step_fns() -> Self {
Self {
rm: RangeInclusiveMap::new_with_step_fns(),
}
}
/// Returns a reference to the range covering the given key, if any.
pub fn get(&self, value: &T) -> Option<&RangeInclusive<T>> {
self.rm.get_key_value(value).map(|(range, _)| range)
}
/// Returns `true` if any range in the set covers the specified value.
pub fn contains(&self, value: &T) -> bool {
self.rm.contains_key(value)
}
/// Gets an ordered iterator over all ranges,
/// ordered by range.
pub fn iter(&self) -> Iter<'_, T> {
Iter {
inner: self.rm.iter(),
}
}
/// Clears the set, removing all elements.
pub fn clear(&mut self) {
self.rm.clear();
}
/// Returns the number of elements in the set.
pub fn len(&self) -> usize {
self.rm.len()
}
/// Returns true if the set contains no elements.
pub fn is_empty(&self) -> bool {
self.rm.is_empty()
}
/// Insert a range into the set.
///
/// If the inserted range either overlaps or is immediately adjacent
/// any existing range, then the ranges will be coalesced into
/// a single contiguous range.
///
/// # Panics
///
/// Panics if range `start > end`.
pub fn insert(&mut self, range: RangeInclusive<T>) {
self.rm.insert(range, ());
}
/// Removes a range from the set, if all or any of it was present.
///
/// If the range to be removed _partially_ overlaps any ranges
/// in the set, then those ranges will be contracted to no
/// longer cover the removed range.
///
/// # Panics
///
/// Panics if range `start > end`.
pub fn remove(&mut self, range: RangeInclusive<T>) {
self.rm.remove(range);
}
/// Gets an iterator over all the maximally-sized ranges
/// contained in `outer_range` that are not covered by
/// any range stored in the set.
///
/// The iterator element type is `RangeInclusive<T>`.
pub fn gaps<'a>(&'a self, outer_range: &'a RangeInclusive<T>) -> Gaps<'a, T, StepFnsT> {
Gaps {
inner: self.rm.gaps(outer_range),
}
}
/// Gets an iterator over all the stored ranges that are
/// either partially or completely overlapped by the given range.
///
/// The iterator element type is `RangeInclusive<T>`.
pub fn overlapping<R: Borrow<RangeInclusive<T>>>(&self, range: R) -> Overlapping<T, R> {
Overlapping {
inner: self.rm.overlapping(range),
}
}
/// Returns `true` if any range in the set completely or partially
/// overlaps the given range.
pub fn overlaps(&self, range: &RangeInclusive<T>) -> bool {
self.overlapping(range).next().is_some()
}
/// Returns the first range in the set, if one exists. The range is the minimum range in this
/// set.
pub fn first(&self) -> Option<&RangeInclusive<T>> {
self.rm.first_range_value().map(|(range, _)| range)
}
/// Returns the last range in the set, if one exists. The range is the maximum range in this
/// set.
pub fn last(&self) -> Option<&RangeInclusive<T>> {
self.rm.last_range_value().map(|(range, _)| range)
}
/// Return an iterator over the union of two range sets.
pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T> {
Union::new(self.iter(), other.iter())
}
/// Return an iterator over the intersection of two range sets.
pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T> {
Intersection::new(self.iter(), other.iter())
}
}
/// An iterator over the ranges of a `RangeInclusiveSet`.
///
/// This `struct` is created by the [`iter`] method on [`RangeInclusiveSet`]. See its
/// documentation for more.
///
/// [`iter`]: RangeInclusiveSet::iter
pub struct Iter<'a, T> {
inner: super::inclusive_map::Iter<'a, T, ()>,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a RangeInclusive<T>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(range, _)| range)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<'a, K> DoubleEndedIterator for Iter<'a, K>
where
K: 'a,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back().map(|(range, _)| range)
}
}
/// An owning iterator over the ranges of a `RangeInclusiveSet`.
///
/// This `struct` is created by the [`into_iter`] method on [`RangeInclusiveSet`]
/// (provided by the `IntoIterator` trait). See its documentation for more.
///
/// [`into_iter`]: IntoIterator::into_iter
pub struct IntoIter<T> {
inner: super::inclusive_map::IntoIter<T, ()>,
}
impl<T> IntoIterator for RangeInclusiveSet<T> {
type Item = RangeInclusive<T>;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
inner: self.rm.into_iter(),
}
}
}
impl<T> Iterator for IntoIter<T> {
type Item = RangeInclusive<T>;
fn next(&mut self) -> Option<RangeInclusive<T>> {
self.inner.next().map(|(range, _)| range)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K> DoubleEndedIterator for IntoIter<K> {
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back().map(|(range, _)| range)
}
}
// We can't just derive this automatically, because that would
// expose irrelevant (and private) implementation details.
// Instead implement it in the same way that the underlying BTreeSet does.
impl<T: Debug> Debug for RangeInclusiveSet<T>
where
T: Ord + Clone + StepLite,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
impl<T> FromIterator<RangeInclusive<T>> for RangeInclusiveSet<T>
where
T: Ord + Clone + StepLite,
{
fn from_iter<I: IntoIterator<Item = RangeInclusive<T>>>(iter: I) -> Self {
let mut range_set = RangeInclusiveSet::new();
range_set.extend(iter);
range_set
}
}
impl<T> Extend<RangeInclusive<T>> for RangeInclusiveSet<T>
where
T: Ord + Clone + StepLite,
{
fn extend<I: IntoIterator<Item = RangeInclusive<T>>>(&mut self, iter: I) {
iter.into_iter().for_each(move |range| {
self.insert(range);
})
}
}
#[cfg(feature = "serde1")]
impl<T> Serialize for RangeInclusiveSet<T>
where
T: Ord + Clone + StepLite + Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use serde::ser::SerializeSeq;
let mut seq = serializer.serialize_seq(Some(self.rm.btm.len()))?;
for range in self.iter() {
seq.serialize_element(&(&range.start(), &range.end()))?;
}
seq.end()
}
}
#[cfg(feature = "serde1")]
impl<'de, T> Deserialize<'de> for RangeInclusiveSet<T>
where
T: Ord + Clone + StepLite + Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_seq(RangeInclusiveSetVisitor::new())
}
}
#[cfg(feature = "serde1")]
struct RangeInclusiveSetVisitor<T> {
marker: PhantomData<fn() -> RangeInclusiveSet<T>>,
}
#[cfg(feature = "serde1")]
impl<T> RangeInclusiveSetVisitor<T> {
fn new() -> Self {
RangeInclusiveSetVisitor {
marker: PhantomData,
}
}
}
#[cfg(feature = "serde1")]
impl<'de, T> Visitor<'de> for RangeInclusiveSetVisitor<T>
where
T: Ord + Clone + StepLite + Deserialize<'de>,
{
type Value = RangeInclusiveSet<T>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("RangeInclusiveSet")
}
fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut range_inclusive_set = RangeInclusiveSet::new();
while let Some((start, end)) = access.next_element()? {
range_inclusive_set.insert(start..=end);
}
Ok(range_inclusive_set)
}
}
/// An iterator over all ranges not covered by a `RangeInclusiveSet`.
///
/// This `struct` is created by the [`gaps`] method on [`RangeInclusiveSet`]. See its
/// documentation for more.
///
/// [`gaps`]: RangeInclusiveSet::gaps
pub struct Gaps<'a, T, StepFnsT> {
inner: crate::inclusive_map::Gaps<'a, T, (), StepFnsT>,
}
// `Gaps` is always fused. (See definition of `next` below.)
impl<'a, T, StepFnsT> core::iter::FusedIterator for Gaps<'a, T, StepFnsT>
where
T: Ord + Clone,
StepFnsT: StepFns<T>,
{
}
impl<'a, T, StepFnsT> Iterator for Gaps<'a, T, StepFnsT>
where
T: Ord + Clone,
StepFnsT: StepFns<T>,
{
type Item = RangeInclusive<T>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
/// An iterator over all stored ranges partially or completely
/// overlapped by a given range.
///
/// This `struct` is created by the [`overlapping`] method on [`RangeInclusiveSet`]. See its
/// documentation for more.
///
/// [`overlapping`]: RangeInclusiveSet::overlapping
pub struct Overlapping<'a, T, R: Borrow<RangeInclusive<T>> = &'a RangeInclusive<T>> {
inner: crate::inclusive_map::Overlapping<'a, T, (), R>,
}
// `Overlapping` is always fused. (See definition of `next` below.)
impl<'a, T, R: Borrow<RangeInclusive<T>>> core::iter::FusedIterator for Overlapping<'a, T, R> where
T: Ord + Clone
{
}
impl<'a, T, R: Borrow<RangeInclusive<T>>> Iterator for Overlapping<'a, T, R>
where
T: Ord + Clone,
{
type Item = &'a RangeInclusive<T>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(k, _v)| k)
}
}
impl<'a, T, R: Borrow<RangeInclusive<T>>> DoubleEndedIterator for Overlapping<'a, T, R>
where
T: Ord + Clone,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back().map(|(k, _v)| k)
}
}
impl<T: Ord + Clone + StepLite, const N: usize> From<[RangeInclusive<T>; N]>
for RangeInclusiveSet<T>
{
fn from(value: [RangeInclusive<T>; N]) -> Self {
let mut set = Self::new();
for value in IntoIterator::into_iter(value) {
set.insert(value);
}
set
}
}
/// Create a [`RangeInclusiveSet`] from a list of ranges.
///
/// # Example
///
/// ```rust
/// # use rangemap::range_inclusive_set;
/// let set = range_inclusive_set![0..=100, 200..=300, 400..=500];
/// ```
#[macro_export]
macro_rules! range_inclusive_set {
($($range:expr),* $(,)?) => {{
$crate::RangeInclusiveSet::from([$($range),*])
}};
}
impl<T: Ord + Clone + StepLite> BitAnd for &RangeInclusiveSet<T> {
type Output = RangeInclusiveSet<T>;
fn bitand(self, other: Self) -> Self::Output {
self.intersection(other).collect()
}
}
impl<T: Ord + Clone + StepLite> BitOr for &RangeInclusiveSet<T> {
type Output = RangeInclusiveSet<T>;
fn bitor(self, other: Self) -> Self::Output {
self.union(other).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc as std;
use alloc::{format, vec, vec::Vec};
use proptest::prelude::*;
use test_strategy::proptest;
impl<T> Arbitrary for RangeInclusiveSet<T>
where
T: Ord + Clone + StepLite + Debug + Arbitrary + 'static,
{
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(_parameters: Self::Parameters) -> Self::Strategy {
any::<Vec<RangeInclusive<T>>>()
.prop_map(|ranges| ranges.into_iter().collect::<RangeInclusiveSet<T>>())
.boxed()
}
}
#[proptest]
fn test_first(set: RangeInclusiveSet<u64>) {
assert_eq!(set.first(), set.iter().min_by_key(|range| range.start()));
}
#[proptest]
#[allow(clippy::len_zero)]
fn test_len(mut map: RangeInclusiveSet<u64>) {
assert_eq!(map.len(), map.iter().count());
assert_eq!(map.is_empty(), map.len() == 0);
map.clear();
assert_eq!(map.len(), 0);
assert!(map.is_empty());
assert_eq!(map.iter().count(), 0);
}
#[proptest]
fn test_last(set: RangeInclusiveSet<u64>) {
assert_eq!(set.last(), set.iter().max_by_key(|range| range.end()));
}
#[proptest]
fn test_iter_reversible(set: RangeInclusiveSet<u64>) {
let forward: Vec<_> = set.iter().collect();
let mut backward: Vec<_> = set.iter().rev().collect();
backward.reverse();
assert_eq!(forward, backward);
}
#[proptest]
fn test_into_iter_reversible(set: RangeInclusiveSet<u64>) {
let forward: Vec<_> = set.clone().into_iter().collect();
let mut backward: Vec<_> = set.into_iter().rev().collect();
backward.reverse();
assert_eq!(forward, backward);
}
#[proptest]
fn test_overlapping_reversible(set: RangeInclusiveSet<u64>, range: RangeInclusive<u64>) {
let forward: Vec<_> = set.overlapping(&range).collect();
let mut backward: Vec<_> = set.overlapping(&range).rev().collect();
backward.reverse();
assert_eq!(forward, backward);
}
// neccessary due to assertion on empty ranges
fn filter_ranges<T: Ord>(ranges: Vec<RangeInclusive<T>>) -> Vec<RangeInclusive<T>> {
ranges
.into_iter()
.filter(|range| range.start() != range.end())
.collect()
}
#[proptest]
fn test_arbitrary_set_u8(ranges: Vec<RangeInclusive<u8>>) {
let ranges: Vec<_> = filter_ranges(ranges);
let set = ranges
.iter()
.fold(RangeInclusiveSet::new(), |mut set, range| {
set.insert(range.clone());
set
});
for value in 0..u8::MAX {
assert_eq!(
set.contains(&value),
ranges.iter().any(|range| range.contains(&value))
);
}
}
#[proptest]
#[allow(deprecated)]
fn test_hash(left: RangeInclusiveSet<u64>, right: RangeInclusiveSet<u64>) {
use core::hash::{Hash, Hasher, SipHasher};
let hash = |set: &RangeInclusiveSet<_>| {
let mut hasher = SipHasher::new();
set.hash(&mut hasher);
hasher.finish()
};
if left == right {
assert!(
hash(&left) == hash(&right),
"if two values are equal, their hash must be equal"
);
}
// if the hashes are equal the values might not be the same (collision)
if hash(&left) != hash(&right) {
assert!(
left != right,
"if two value's hashes are not equal, they must not be equal"
);
}
}
#[proptest]
fn test_ord(left: RangeInclusiveSet<u64>, right: RangeInclusiveSet<u64>) {
assert_eq!(
left == right,
left.cmp(&right).is_eq(),
"ordering and equality must match"
);
assert_eq!(
left.cmp(&right),
left.partial_cmp(&right).unwrap(),
"ordering is total for ordered parameters"
);
}
#[test]
fn test_from_array() {
let mut set = RangeInclusiveSet::new();
set.insert(0..=100);
set.insert(200..=300);
assert_eq!(set, RangeInclusiveSet::from([0..=100, 200..=300]));
}
#[test]
fn test_macro() {
assert_eq!(range_inclusive_set![], RangeInclusiveSet::<i64>::default());
assert_eq!(
range_inclusive_set![0..=100, 200..=300, 400..=500],
[0..=100, 200..=300, 400..=500].iter().cloned().collect(),
);
}
#[proptest]
fn test_union_overlaps_u8(left: RangeInclusiveSet<u8>, right: RangeInclusiveSet<u8>) {
let mut union = RangeInclusiveSet::new();
for range in left.union(&right) {
// there should not be any overlaps in the ranges returned by the union
assert!(union.overlapping(&range).next().is_none());
union.insert(range);
}
}
#[proptest]
fn test_union_contains_u8(left: RangeInclusiveSet<u8>, right: RangeInclusiveSet<u8>) {
let union = (&left) | (&right);
// value should be in the union if and only if it is in either set
for value in 0..u8::MAX {
assert_eq!(
union.contains(&value),
left.contains(&value) || right.contains(&value)
);
}
}
#[proptest]
fn test_intersection_contains_u8(left: RangeInclusiveSet<u8>, right: RangeInclusiveSet<u8>) {
let intersection = (&left) & (&right);
// value should be in the intersection if and only if it is in both sets
for value in 0..u8::MAX {
assert_eq!(
intersection.contains(&value),
left.contains(&value) && right.contains(&value)
);
}
}
#[proptest]
fn test_intersection_overlaps_u8(left: RangeInclusiveSet<u8>, right: RangeInclusiveSet<u8>) {
let mut union = RangeInclusiveSet::new();
for range in left.intersection(&right) {
// there should not be any overlaps in the ranges returned by the
// intersection
assert!(union.overlapping(&range).next().is_none());
union.insert(range);
}
}
trait RangeInclusiveSetExt<T> {
fn to_vec(&self) -> Vec<RangeInclusive<T>>;
}
impl<T> RangeInclusiveSetExt<T> for RangeInclusiveSet<T>
where
T: Ord + Clone + StepLite,
{
fn to_vec(&self) -> Vec<RangeInclusive<T>> {
self.iter().cloned().collect()
}
}
#[test]
fn empty_set_is_empty() {
let range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
assert_eq!(range_set.to_vec(), vec![]);
}
#[test]
fn insert_into_empty_map() {
let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
range_set.insert(0..=50);
assert_eq!(range_set.to_vec(), vec![0..=50]);
}
#[test]
fn remove_partially_overlapping() {
let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
range_set.insert(0..=50);
range_set.remove(25..=75);
assert_eq!(range_set.to_vec(), vec![0..=24]);
}
#[test]
fn gaps_between_items_floating_inside_outer_range() {
let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌ ◌
range_set.insert(5..=6);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◌ ●-● ◌ ◌ ◌ ◌ ◌ ◌
range_set.insert(2..=3);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◆-------------◆ ◌
let outer_range = 1..=8;
let mut gaps = range_set.gaps(&outer_range);
// Should yield gaps at start, between items,
// and at end.
assert_eq!(gaps.next(), Some(1..=1));
assert_eq!(gaps.next(), Some(4..=4));
assert_eq!(gaps.next(), Some(7..=8));
assert_eq!(gaps.next(), None);
// Gaps iterator should be fused.
assert_eq!(gaps.next(), None);
assert_eq!(gaps.next(), None);
}
#[test]
fn overlapping_partial_edges_complete_middle() {
let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
// 0 1 2 3 4 5 6 7 8 9
// ●-● ◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
range_set.insert(0..=1);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◌ ◌ ●-● ◌ ◌ ◌ ◌ ◌
range_set.insert(3..=4);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌
range_set.insert(6..=7);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◆---------◆ ◌ ◌ ◌
let query_range = 1..=6;
let mut overlapping = range_set.overlapping(&query_range);
// Should yield partially overlapped range at start.
assert_eq!(overlapping.next(), Some(&(0..=1)));
// Should yield completely overlapped range in middle.
assert_eq!(overlapping.next(), Some(&(3..=4)));
// Should yield partially overlapped range at end.
assert_eq!(overlapping.next(), Some(&(6..=7)));
// Gaps iterator should be fused.
assert_eq!(overlapping.next(), None);
assert_eq!(overlapping.next(), None);
}
///
/// impl Debug
///
#[test]
fn set_debug_repr_looks_right() {
let mut set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
// Empty
assert_eq!(format!("{:?}", set), "{}");
// One entry
set.insert(2..=5);
assert_eq!(format!("{:?}", set), "{2..=5}");
// Many entries
set.insert(7..=8);
set.insert(10..=11);
assert_eq!(format!("{:?}", set), "{2..=5, 7..=8, 10..=11}");
}
// impl Default where T: ?Default
#[test]
fn always_default() {
struct NoDefault;
RangeInclusiveSet::<NoDefault>::default();
}
// impl Serialize
#[cfg(feature = "serde1")]
#[test]
fn serialization() {
let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◆---◆ ◌ ◌ ◌ ◌ ◌ ◌
range_set.insert(1..=3);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◌ ◌ ◌ ◌ ◆---◆ ◌ ◌
range_set.insert(5..=7);
let output = serde_json::to_string(&range_set).expect("Failed to serialize");
assert_eq!(output, "[[1,3],[5,7]]");
}
// impl Deserialize
#[cfg(feature = "serde1")]
#[test]
fn deserialization() {
let input = "[[1,3],[5,7]]";
let range_set: RangeInclusiveSet<u32> =
serde_json::from_str(input).expect("Failed to deserialize");
let reserialized = serde_json::to_string(&range_set).expect("Failed to re-serialize");
assert_eq!(reserialized, input);
}
// const fn
#[cfg(feature = "const_fn")]
const _SET: RangeInclusiveSet<u32> = RangeInclusiveSet::new();
#[cfg(feature = "const_fn")]
const _SET2: RangeInclusiveSet<u32> = RangeInclusiveSet::new_with_step_fns();
#[cfg(feature = "quickcheck")]
quickcheck::quickcheck! {
fn prop(xs: RangeInclusiveSet<usize, usize>) -> bool {
xs == xs
}
}
}

156
vendor/rangemap/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,156 @@
/*!
[`RangeMap`] and [`RangeInclusiveMap`] are map data structures whose keys
are stored as ranges. Contiguous and overlapping ranges that map to the same
value are coalesced into a single range.
Corresponding [`RangeSet`] and [`RangeInclusiveSet`] structures are also provided.
# Different kinds of ranges
`RangeMap` and `RangeInclusiveMap` correspond to the [`Range`]
and [`RangeInclusive`] types from the standard library respectively.
For some applications the choice of range type may be obvious,
or even be dictated by pre-existing design decisions. For other applications
the choice may seem arbitrary, and be guided instead by convenience or
aesthetic preference.
If the choice is not obvious in your case, consider these differences:
- If your key type `K` represents points on a continuum (e.g. `f64`),
and the choice of which of two adjacent ranges "owns" the value
where they touch is largely arbitrary, then it may be more natural
to work with half-open `Range`s like `0.0..1.0` and `1.0..2.0`. If you
were to use closed `RangeInclusive`s here instead, then to represent two such adjacent
ranges you would need to subtract some infinitesimal (which may depend,
as it does in the case of `f64`, on the specific value of `K`)
from the end of the earlier range. (See the last point below for more
on this problem.)
- If you need to represent ranges that _include_ the maximum
value in the key domain (e.g. `255u8`) then you will
probably want to use `RangeInclusive`s like `128u8..=255u8`. Sometimes
it may be possible to instead work around this by using a wider key
type than the values you are actually trying to represent (`K=u16`
even though you are only trying to represent ranges covering `u8`)
but in these cases the key domain often represents discrete objects
rather than points on a continuum, and so `RangeInclusive` may
be a more natural way to express these ranges anyway.
- If you are using `RangeInclusive`, then it must be possible to define
_successor_ and _predecessor_ functions for your key type `K`,
because adjacent ranges can not be detected (and thereby coalesced)
simply by testing their ends for equality. For key types that represent
points on a continuum, defining these functions may be awkward and error-prone.
For key types that represent discrete objects, this is usually much
more straightforward.
# Example: use with Chrono
```rust
use chrono::offset::TimeZone;
use chrono::{Duration, Utc};
use rangemap::RangeMap;
let people = ["Alice", "Bob", "Carol"];
let mut roster = RangeMap::new();
// Set up initial roster.
let start_of_roster = Utc.ymd(2019, 1, 7);
let mut week_start = start_of_roster;
for _ in 0..3 {
for person in &people {
let next_week = week_start + Duration::weeks(1);
roster.insert(week_start..next_week, person);
week_start = next_week;
}
}
// Bob is covering Alice's second shift (the fourth shift overall).
let fourth_shift_start = start_of_roster + Duration::weeks(3);
let fourth_shift_end = fourth_shift_start + Duration::weeks(1);
roster.insert(fourth_shift_start..fourth_shift_end, &"Bob");
for (range, person) in roster.iter() {
println!("{} ({}): {}", range.start, range.end - range.start, person);
}
// Output:
// 2019-01-07UTC (P7D): Alice
// 2019-01-14UTC (P7D): Bob
// 2019-01-21UTC (P7D): Carol
// 2019-01-28UTC (P14D): Bob
// 2019-02-11UTC (P7D): Carol
// 2019-02-18UTC (P7D): Alice
// 2019-02-25UTC (P7D): Bob
// 2019-03-04UTC (P7D): Carol
```
## Crate features
By default this crate has no dependencies on other crates.
If you enable the **serde1** feature it will introduce a dependency on
the _serde_ crate and provide `Serialize` and `Deserialize`
implementations for all map and set types in this crate.
You can enable the **serde1** feature in your _Cargo.toml_ file like so:
```toml
[dependencies]
rangemap = { version = "1", features = ["serde1"] }
```
You can similarly enable support for _quickcheck_ by enabling
the **quickcheck** feature.
## Building without the Rust standard library
This crate can work without the full standard library available
(e.g. when running on bare metal without an operating system)
but relies on the presence of a global allocator &mdash;
i.e. it links the `core` and `alloc` crates, but not `std`.
Presently there is no functionality in the crate that require
the standard library. Such functionality will likely be
introduced in the future, and will be gated behind a default-on
`std` feature.
See [The Rust Programming Language](https://doc.rust-lang.org/1.7.0/book/no-stdlib.html)
book for general information about operating without the standard library.
[`RangeMap`]: crate::RangeMap
[`RangeInclusiveMap`]: crate::RangeInclusiveMap
[`RangeSet`]: crate::RangeSet
[`RangeInclusiveSet`]: crate::RangeInclusiveSet
[`Range`]: core::ops::Range
[`RangeInclusive`]: core::ops::RangeInclusive
*/
#![no_std]
extern crate alloc;
pub mod inclusive_map;
pub mod inclusive_set;
pub mod map;
pub(crate) mod operations;
pub mod set;
#[cfg(test)]
mod dense;
mod range_wrapper;
mod std_ext;
pub use inclusive_map::RangeInclusiveMap;
pub use inclusive_set::RangeInclusiveSet;
pub use map::RangeMap;
pub use set::RangeSet;
pub use std_ext::{StepFns, StepLite};
// Doc tests for README.
#[cfg(feature = "nightly")]
mod readme;

1845
vendor/rangemap/src/map.rs vendored Normal file

File diff suppressed because it is too large Load Diff

246
vendor/rangemap/src/operations.rs vendored Normal file
View File

@@ -0,0 +1,246 @@
use core::cmp::Ordering;
use core::iter::{FusedIterator, Peekable};
use core::ops::{Range, RangeInclusive};
/// Trait to determine the ordering of the start and end of a range.
trait RangeOrder {
/// Ordering of start value
fn order_start(&self, other: &Self) -> Ordering;
/// Ordering of end value
fn order_end(&self, other: &Self) -> Ordering;
}
impl<T: Ord> RangeOrder for Range<T> {
fn order_start(&self, other: &Self) -> Ordering {
self.start.cmp(&other.start)
}
fn order_end(&self, other: &Self) -> Ordering {
self.end.cmp(&other.end)
}
}
impl<T: Ord> RangeOrder for RangeInclusive<T> {
fn order_start(&self, other: &Self) -> Ordering {
self.start().cmp(other.start())
}
fn order_end(&self, other: &Self) -> Ordering {
self.end().cmp(other.end())
}
}
/// Range which can be merged with a next range if they overlap.
trait RangeMerge: Sized {
/// Merges this range and the next range, if they overlap.
fn merge(&mut self, next: &Self) -> bool;
}
impl<T: Ord + Clone> RangeMerge for Range<T> {
fn merge(&mut self, other: &Self) -> bool {
if !self.contains(&other.start) {
return false;
}
if other.end > self.end {
self.end = other.end.clone();
}
true
}
}
impl<T: Ord + Clone> RangeMerge for RangeInclusive<T> {
fn merge(&mut self, other: &Self) -> bool {
if !self.contains(other.start()) {
return false;
}
if other.end() > self.end() {
*self = RangeInclusive::new(self.start().clone(), other.end().clone());
}
true
}
}
/// Range which can be merged with a next range if they overlap.
trait RangeIntersect: Sized {
/// Attempt to merge the next range into the current range, if they overlap.
fn intersect(&self, next: &Self) -> Option<Self>;
}
impl<T: Ord + Clone> RangeIntersect for Range<T> {
fn intersect(&self, other: &Self) -> Option<Self> {
let start = (&self.start).max(&other.start);
let end = (&self.end).min(&other.end);
if start >= end {
return None;
}
Some(start.clone()..end.clone())
}
}
impl<T: Ord + Clone> RangeIntersect for RangeInclusive<T> {
fn intersect(&self, other: &Self) -> Option<Self> {
let start = self.start().max(other.start());
let end = self.end().min(other.end());
if start > end {
return None;
}
Some(start.clone()..=end.clone())
}
}
#[test]
fn test_intersect() {
assert_eq!((0..5).intersect(&(0..3)), Some(0..3));
assert_eq!((0..3).intersect(&(0..5)), Some(0..3));
assert_eq!((0..3).intersect(&(3..3)), None);
}
/// Iterator that produces the union of two iterators of sorted ranges.
pub struct Union<'a, T, L, R = L>
where
T: 'a,
L: Iterator<Item = &'a T>,
R: Iterator<Item = &'a T>,
{
left: Peekable<L>,
right: Peekable<R>,
}
impl<'a, T, L, R> Union<'a, T, L, R>
where
T: 'a,
L: Iterator<Item = &'a T>,
R: Iterator<Item = &'a T>,
{
/// Create new Union iterator.
///
/// Requires that the two iterators produce sorted ranges.
pub fn new(left: L, right: R) -> Self {
Self {
left: left.peekable(),
right: right.peekable(),
}
}
}
impl<'a, R, I> Iterator for Union<'a, R, I>
where
R: RangeOrder + RangeMerge + Clone,
I: Iterator<Item = &'a R>,
{
type Item = R;
fn next(&mut self) -> Option<Self::Item> {
// get start range
let mut range = match (self.left.peek(), self.right.peek()) {
// if there is only one possible range, pick that
(Some(_), None) => self.left.next().unwrap(),
(None, Some(_)) => self.right.next().unwrap(),
// when there are two ranges, pick the one with the earlier start
(Some(left), Some(right)) => {
if left.order_start(right).is_lt() {
self.left.next().unwrap()
} else {
self.right.next().unwrap()
}
}
// otherwise we are done
(None, None) => return None,
}
.clone();
// peek into next value of iterator and merge if it is contiguous
let mut join = |iter: &mut Peekable<I>| {
if let Some(next) = iter.peek() {
if range.merge(next) {
iter.next().unwrap();
return true;
}
}
false
};
// keep merging ranges as long as we can
loop {
if !(join(&mut self.left) || join(&mut self.right)) {
break;
}
}
Some(range)
}
}
impl<'a, R, I> FusedIterator for Union<'a, R, I>
where
R: RangeOrder + RangeMerge + Clone,
I: Iterator<Item = &'a R>,
{
}
/// Iterator that produces the union of two iterators of sorted ranges.
pub struct Intersection<'a, T, L, R = L>
where
T: 'a,
L: Iterator<Item = &'a T>,
R: Iterator<Item = &'a T>,
{
left: Peekable<L>,
right: Peekable<R>,
}
impl<'a, T, L, R> Intersection<'a, T, L, R>
where
T: 'a,
L: Iterator<Item = &'a T>,
R: Iterator<Item = &'a T>,
{
/// Create new Intersection iterator.
///
/// Requires that the two iterators produce sorted ranges.
pub fn new(left: L, right: R) -> Self {
Self {
left: left.peekable(),
right: right.peekable(),
}
}
}
impl<'a, R, I> Iterator for Intersection<'a, R, I>
where
R: RangeOrder + RangeIntersect + Clone,
I: Iterator<Item = &'a R>,
{
type Item = R;
fn next(&mut self) -> Option<Self::Item> {
loop {
// if we don't have at least two ranges, there cannot be an intersection
let (Some(left), Some(right)) = (self.left.peek(), self.right.peek()) else {
return None;
};
let intersection = left.intersect(right);
// pop the range that ends earlier
if left.order_end(right).is_lt() {
self.left.next();
} else {
self.right.next();
}
if let Some(intersection) = intersection {
return Some(intersection);
}
}
}
}

257
vendor/rangemap/src/range_wrapper.rs vendored Normal file
View File

@@ -0,0 +1,257 @@
// Wrappers to allow storing (and sorting/searching)
// ranges as the keys of a `BTreeMap`.
//
// This wraps the range in two layers: one that lets us
// order ranges by their start (`RangeStartWrapper`),
// and then within that, one that lets us order them by
// their end (`RangeEndWrapper`). Ordinarily we'll use
// the former, but there are a couple of cases where we
// want to be able to do the latter for performance/convenience.
//
// This is made possible by a sneaky `Borrow` implementation
// which skirts the law about the borrowed representation
// having identical implementations of `Ord` etc., but shouldn't
// be a problem in practice because users of the crate can't
// access these special wrappers, and we are careful to uphold
// invariants that prevent observing any states where the
// differing implementations would produce different results.
//
// Specifically, we maintain the invariants
// that the order of range starts is the same as the order
// of range ends, and that no two stored ranges have the
// same start or end as each other.
//
// NOTE: Be very careful not to accidentally use these
// if you really do want to compare equality of the
// inner range!
use core::cmp::Ordering;
use core::ops::{Deref, Range, RangeInclusive};
//
// Range start wrapper
//
#[derive(Debug, Clone)]
pub struct RangeStartWrapper<T> {
pub end_wrapper: RangeEndWrapper<T>,
}
impl<T> RangeStartWrapper<T> {
pub fn new(range: Range<T>) -> RangeStartWrapper<T> {
RangeStartWrapper {
end_wrapper: RangeEndWrapper::new(range),
}
}
}
impl<T> PartialEq for RangeStartWrapper<T>
where
T: PartialEq,
{
fn eq(&self, other: &RangeStartWrapper<T>) -> bool {
self.start == other.start
}
}
impl<T> Eq for RangeStartWrapper<T> where T: Eq {}
impl<T> Ord for RangeStartWrapper<T>
where
T: Ord,
{
fn cmp(&self, other: &RangeStartWrapper<T>) -> Ordering {
self.start.cmp(&other.start)
}
}
impl<T> PartialOrd for RangeStartWrapper<T>
where
T: PartialOrd,
{
fn partial_cmp(&self, other: &RangeStartWrapper<T>) -> Option<Ordering> {
self.start.partial_cmp(&other.start)
}
}
impl<T> core::borrow::Borrow<RangeEndWrapper<T>> for RangeStartWrapper<T> {
fn borrow(&self) -> &RangeEndWrapper<T> {
&self.end_wrapper
}
}
// Avoid the need to tediously plumb through the layers of wrapper structs
// when you're just trying to access members of the inner range itself.
impl<T> Deref for RangeStartWrapper<T> {
type Target = RangeEndWrapper<T>;
fn deref(&self) -> &Self::Target {
&self.end_wrapper
}
}
//
// Range end wrapper
//
#[derive(Debug, Clone)]
pub struct RangeEndWrapper<T> {
pub range: Range<T>,
}
impl<T> RangeEndWrapper<T> {
pub fn new(range: Range<T>) -> RangeEndWrapper<T> {
RangeEndWrapper { range }
}
}
impl<T> PartialEq for RangeEndWrapper<T>
where
T: PartialEq,
{
fn eq(&self, other: &RangeEndWrapper<T>) -> bool {
self.end == other.end
}
}
impl<T> Eq for RangeEndWrapper<T> where T: Eq {}
impl<T> Ord for RangeEndWrapper<T>
where
T: Ord,
{
fn cmp(&self, other: &RangeEndWrapper<T>) -> Ordering {
self.end.cmp(&other.end)
}
}
impl<T> PartialOrd for RangeEndWrapper<T>
where
T: PartialOrd,
{
fn partial_cmp(&self, other: &RangeEndWrapper<T>) -> Option<Ordering> {
self.end.partial_cmp(&other.end)
}
}
// Avoid the need to tediously plumb through the layers of wrapper structs
// when you're just trying to access members of the inner range itself.
impl<T> Deref for RangeEndWrapper<T> {
type Target = Range<T>;
fn deref(&self) -> &Self::Target {
&self.range
}
}
//
// RangeInclusive start wrapper
//
#[derive(Eq, Debug, Clone)]
pub struct RangeInclusiveStartWrapper<T> {
pub end_wrapper: RangeInclusiveEndWrapper<T>,
}
impl<T> RangeInclusiveStartWrapper<T> {
pub fn new(range: RangeInclusive<T>) -> RangeInclusiveStartWrapper<T> {
RangeInclusiveStartWrapper {
end_wrapper: RangeInclusiveEndWrapper::new(range),
}
}
}
impl<T> PartialEq for RangeInclusiveStartWrapper<T>
where
T: PartialEq,
{
fn eq(&self, other: &RangeInclusiveStartWrapper<T>) -> bool {
self.start() == other.start()
}
}
impl<T> Ord for RangeInclusiveStartWrapper<T>
where
T: Ord,
{
fn cmp(&self, other: &RangeInclusiveStartWrapper<T>) -> Ordering {
self.start().cmp(other.start())
}
}
impl<T> PartialOrd for RangeInclusiveStartWrapper<T>
where
T: PartialOrd,
{
fn partial_cmp(&self, other: &RangeInclusiveStartWrapper<T>) -> Option<Ordering> {
self.start().partial_cmp(other.start())
}
}
impl<T> core::borrow::Borrow<RangeInclusiveEndWrapper<T>> for RangeInclusiveStartWrapper<T> {
fn borrow(&self) -> &RangeInclusiveEndWrapper<T> {
&self.end_wrapper
}
}
// Avoid the need to tediously plumb through the layers of wrapper structs
// when you're just trying to access members of the inner range itself.
impl<T> Deref for RangeInclusiveStartWrapper<T> {
type Target = RangeInclusiveEndWrapper<T>;
fn deref(&self) -> &Self::Target {
&self.end_wrapper
}
}
//
// RangeInclusive end wrapper
//
#[derive(Eq, Debug, Clone)]
pub struct RangeInclusiveEndWrapper<T> {
pub range: RangeInclusive<T>,
}
impl<T> RangeInclusiveEndWrapper<T> {
pub fn new(range: RangeInclusive<T>) -> RangeInclusiveEndWrapper<T> {
RangeInclusiveEndWrapper { range }
}
}
impl<T> PartialEq for RangeInclusiveEndWrapper<T>
where
T: PartialEq,
{
fn eq(&self, other: &RangeInclusiveEndWrapper<T>) -> bool {
self.end() == other.end()
}
}
impl<T> Ord for RangeInclusiveEndWrapper<T>
where
T: Ord,
{
fn cmp(&self, other: &RangeInclusiveEndWrapper<T>) -> Ordering {
self.end().cmp(other.end())
}
}
impl<T> PartialOrd for RangeInclusiveEndWrapper<T>
where
T: PartialOrd,
{
fn partial_cmp(&self, other: &RangeInclusiveEndWrapper<T>) -> Option<Ordering> {
self.end().partial_cmp(other.end())
}
}
// Avoid the need to tediously plumb through the layers of wrapper structs
// when you're just trying to access members of the inner range itself.
impl<T> Deref for RangeInclusiveEndWrapper<T> {
type Target = RangeInclusive<T>;
fn deref(&self) -> &Self::Target {
&self.range
}
}

2
vendor/rangemap/src/readme.rs vendored Normal file
View File

@@ -0,0 +1,2 @@
#[doc = include_str!("../README.md")]
struct _Readme {}

815
vendor/rangemap/src/set.rs vendored Normal file
View File

@@ -0,0 +1,815 @@
use core::borrow::Borrow;
use core::fmt::{self, Debug};
use core::iter::FromIterator;
use core::ops::{BitAnd, BitOr, Range};
use core::prelude::v1::*;
#[cfg(feature = "serde1")]
use core::marker::PhantomData;
#[cfg(feature = "serde1")]
use serde::{
de::{Deserialize, Deserializer, SeqAccess, Visitor},
ser::{Serialize, Serializer},
};
use crate::RangeMap;
/// Intersection iterator over two [`RangeSet`].
pub type Intersection<'a, T> = crate::operations::Intersection<'a, Range<T>, Iter<'a, T>>;
/// Union iterator over two [`RangeSet`].
pub type Union<'a, T> = crate::operations::Union<'a, Range<T>, Iter<'a, T>>;
#[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Ord)]
/// A set whose items are stored as (half-open) ranges bounded
/// inclusively below and exclusively above `(start..end)`.
///
/// See [`RangeMap`]'s documentation for more details.
///
/// [`RangeMap`]: crate::RangeMap
pub struct RangeSet<T> {
rm: RangeMap<T, ()>,
}
impl<T> Default for RangeSet<T> {
fn default() -> Self {
Self {
rm: RangeMap::default(),
}
}
}
#[cfg(feature = "quickcheck")]
impl<K> quickcheck::Arbitrary for RangeSet<K>
where
K: quickcheck::Arbitrary + Ord,
{
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
Self {
rm: RangeMap::arbitrary(g),
}
}
}
impl<T> RangeSet<T>
where
T: Ord + Clone,
{
/// Makes a new empty `RangeSet`.
#[cfg(feature = "const_fn")]
pub const fn new() -> Self {
RangeSet {
rm: RangeMap::new(),
}
}
/// Makes a new empty `RangeSet`.
#[cfg(not(feature = "const_fn"))]
pub fn new() -> Self {
RangeSet {
rm: RangeMap::new(),
}
}
/// Returns a reference to the range covering the given key, if any.
pub fn get(&self, value: &T) -> Option<&Range<T>> {
self.rm.get_key_value(value).map(|(range, _)| range)
}
/// Returns `true` if any range in the set covers the specified value.
pub fn contains(&self, value: &T) -> bool {
self.rm.contains_key(value)
}
/// Gets an ordered iterator over all ranges,
/// ordered by range.
pub fn iter(&self) -> Iter<'_, T> {
Iter {
inner: self.rm.iter(),
}
}
/// Clears the set, removing all elements.
pub fn clear(&mut self) {
self.rm.clear();
}
/// Returns the number of elements in the set.
pub fn len(&self) -> usize {
self.rm.len()
}
/// Returns true if the set contains no elements.
pub fn is_empty(&self) -> bool {
self.rm.is_empty()
}
/// Return an iterator over the intersection of two range sets.
pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T> {
Intersection::new(self.iter(), other.iter())
}
/// Return an iterator over the union of two range sets.
pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T> {
Union::new(self.iter(), other.iter())
}
/// Insert a range into the set.
///
/// If the inserted range either overlaps or is immediately adjacent
/// any existing range, then the ranges will be coalesced into
/// a single contiguous range.
///
/// # Panics
///
/// Panics if range `start >= end`.
pub fn insert(&mut self, range: Range<T>) {
self.rm.insert(range, ());
}
/// Removes a range from the set, if all or any of it was present.
///
/// If the range to be removed _partially_ overlaps any ranges
/// in the set, then those ranges will be contracted to no
/// longer cover the removed range.
///
/// # Panics
///
/// Panics if range `start >= end`.
pub fn remove(&mut self, range: Range<T>) {
self.rm.remove(range);
}
/// Gets an iterator over all the maximally-sized ranges
/// contained in `outer_range` that are not covered by
/// any range stored in the set.
///
/// If the start and end of the outer range are the same
/// and it does not overlap any stored range, then a single
/// empty gap will be returned.
///
/// The iterator element type is `Range<T>`.
pub fn gaps<'a>(&'a self, outer_range: &'a Range<T>) -> Gaps<'a, T> {
Gaps {
inner: self.rm.gaps(outer_range),
}
}
/// Gets an iterator over all the stored ranges that are
/// either partially or completely overlapped by the given range.
///
/// The iterator element type is `&Range<T>`.
pub fn overlapping<R: Borrow<Range<T>>>(&self, range: R) -> Overlapping<T, R> {
Overlapping {
inner: self.rm.overlapping(range),
}
}
/// Returns `true` if any range in the set completely or partially
/// overlaps the given range.
pub fn overlaps(&self, range: &Range<T>) -> bool {
self.overlapping(range).next().is_some()
}
/// Returns the first range in the set, if one exists. The range is the minimum range in this
/// set.
pub fn first(&self) -> Option<&Range<T>> {
self.rm.first_range_value().map(|(range, _)| range)
}
/// Returns the last range in the set, if one exists. The range is the maximum range in this
/// set.
pub fn last(&self) -> Option<&Range<T>> {
self.rm.last_range_value().map(|(range, _)| range)
}
}
/// An iterator over the ranges of a `RangeSet`.
///
/// This `struct` is created by the [`iter`] method on [`RangeSet`]. See its
/// documentation for more.
///
/// [`iter`]: RangeSet::iter
pub struct Iter<'a, T> {
inner: super::map::Iter<'a, T, ()>,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a Range<T>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(range, _)| range)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<'a, K> DoubleEndedIterator for Iter<'a, K>
where
K: 'a,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back().map(|(range, _)| range)
}
}
/// An owning iterator over the ranges of a `RangeSet`.
///
/// This `struct` is created by the [`into_iter`] method on [`RangeSet`]
/// (provided by the `IntoIterator` trait). See its documentation for more.
///
/// [`into_iter`]: IntoIterator::into_iter
pub struct IntoIter<T> {
inner: super::map::IntoIter<T, ()>,
}
impl<T> IntoIterator for RangeSet<T> {
type Item = Range<T>;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
inner: self.rm.into_iter(),
}
}
}
impl<T> Iterator for IntoIter<T> {
type Item = Range<T>;
fn next(&mut self) -> Option<Range<T>> {
self.inner.next().map(|(range, _)| range)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K> DoubleEndedIterator for IntoIter<K> {
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back().map(|(range, _)| range)
}
}
// We can't just derive this automatically, because that would
// expose irrelevant (and private) implementation details.
// Instead implement it in the same way that the underlying BTreeSet does.
impl<T: Debug> Debug for RangeSet<T>
where
T: Ord + Clone,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
impl<T> FromIterator<Range<T>> for RangeSet<T>
where
T: Ord + Clone,
{
fn from_iter<I: IntoIterator<Item = Range<T>>>(iter: I) -> Self {
let mut range_set = RangeSet::new();
range_set.extend(iter);
range_set
}
}
impl<T> Extend<Range<T>> for RangeSet<T>
where
T: Ord + Clone,
{
fn extend<I: IntoIterator<Item = Range<T>>>(&mut self, iter: I) {
iter.into_iter().for_each(move |range| {
self.insert(range);
})
}
}
#[cfg(feature = "serde1")]
impl<T> Serialize for RangeSet<T>
where
T: Ord + Clone + Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use serde::ser::SerializeSeq;
let mut seq = serializer.serialize_seq(Some(self.rm.btm.len()))?;
for range in self.iter() {
seq.serialize_element(&(&range.start, &range.end))?;
}
seq.end()
}
}
#[cfg(feature = "serde1")]
impl<'de, T> Deserialize<'de> for RangeSet<T>
where
T: Ord + Clone + Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_seq(RangeSetVisitor::new())
}
}
#[cfg(feature = "serde1")]
struct RangeSetVisitor<T> {
marker: PhantomData<fn() -> RangeSet<T>>,
}
#[cfg(feature = "serde1")]
impl<T> RangeSetVisitor<T> {
fn new() -> Self {
RangeSetVisitor {
marker: PhantomData,
}
}
}
#[cfg(feature = "serde1")]
impl<'de, T> Visitor<'de> for RangeSetVisitor<T>
where
T: Ord + Clone + Deserialize<'de>,
{
type Value = RangeSet<T>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("RangeSet")
}
fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut range_set = RangeSet::new();
while let Some((start, end)) = access.next_element()? {
range_set.insert(start..end);
}
Ok(range_set)
}
}
/// An iterator over all ranges not covered by a `RangeSet`.
///
/// This `struct` is created by the [`gaps`] method on [`RangeSet`]. See its
/// documentation for more.
///
/// [`gaps`]: RangeSet::gaps
pub struct Gaps<'a, T> {
inner: crate::map::Gaps<'a, T, ()>,
}
// `Gaps` is always fused. (See definition of `next` below.)
impl<'a, T> core::iter::FusedIterator for Gaps<'a, T> where T: Ord + Clone {}
impl<'a, T> Iterator for Gaps<'a, T>
where
T: Ord + Clone,
{
type Item = Range<T>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
/// An iterator over all stored ranges partially or completely
/// overlapped by a given range.
///
/// This `struct` is created by the [`overlapping`] method on [`RangeSet`]. See its
/// documentation for more.
///
/// [`overlapping`]: RangeSet::overlapping
pub struct Overlapping<'a, T, R: Borrow<Range<T>> = &'a Range<T>> {
inner: crate::map::Overlapping<'a, T, (), R>,
}
// `Overlapping` is always fused. (See definition of `next` below.)
impl<'a, T, R: Borrow<Range<T>>> core::iter::FusedIterator for Overlapping<'a, T, R> where
T: Ord + Clone
{
}
impl<'a, T, R: Borrow<Range<T>>> Iterator for Overlapping<'a, T, R>
where
T: Ord + Clone,
{
type Item = &'a Range<T>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(k, _v)| k)
}
}
impl<'a, T, R: Borrow<Range<T>>> DoubleEndedIterator for Overlapping<'a, T, R>
where
T: Ord + Clone,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back().map(|(k, _v)| k)
}
}
impl<T: Ord + Clone> BitAnd for &RangeSet<T> {
type Output = RangeSet<T>;
fn bitand(self, other: Self) -> Self::Output {
self.intersection(other).collect()
}
}
impl<T: Ord + Clone> BitOr for &RangeSet<T> {
type Output = RangeSet<T>;
fn bitor(self, other: Self) -> Self::Output {
self.union(other).collect()
}
}
impl<T: Ord + Clone, const N: usize> From<[Range<T>; N]> for RangeSet<T> {
fn from(value: [Range<T>; N]) -> Self {
let mut set = Self::new();
for value in IntoIterator::into_iter(value) {
set.insert(value);
}
set
}
}
/// Create a [`RangeSet`] from a list of ranges.
///
/// # Example
///
/// ```rust
/// # use rangemap::range_set;
/// let set = range_set![0..100, 200..300, 400..500];
/// ```
#[macro_export]
macro_rules! range_set {
($($range:expr),* $(,)?) => {{
$crate::RangeSet::from([$($range),*])
}};
}
#[cfg(test)]
mod tests {
use super::*;
use alloc as std;
use alloc::{format, vec, vec::Vec};
use proptest::prelude::*;
use test_strategy::proptest;
impl<T> Arbitrary for RangeSet<T>
where
T: Ord + Clone + Debug + Arbitrary + 'static,
{
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(_parameters: Self::Parameters) -> Self::Strategy {
any::<Vec<Range<T>>>()
.prop_map(|ranges| {
ranges
.into_iter()
.filter(|range| range.start != range.end)
.collect::<RangeSet<T>>()
})
.boxed()
}
}
#[proptest]
fn test_first(set: RangeSet<u64>) {
assert_eq!(set.first(), set.iter().min_by_key(|range| range.start));
}
#[proptest]
#[allow(clippy::len_zero)]
fn test_len(mut map: RangeSet<u64>) {
assert_eq!(map.len(), map.iter().count());
assert_eq!(map.is_empty(), map.len() == 0);
map.clear();
assert_eq!(map.len(), 0);
assert!(map.is_empty());
assert_eq!(map.iter().count(), 0);
}
#[proptest]
fn test_last(set: RangeSet<u64>) {
assert_eq!(set.last(), set.iter().max_by_key(|range| range.end));
}
#[proptest]
fn test_iter_reversible(set: RangeSet<u64>) {
let forward: Vec<_> = set.iter().collect();
let mut backward: Vec<_> = set.iter().rev().collect();
backward.reverse();
assert_eq!(forward, backward);
}
#[proptest]
fn test_into_iter_reversible(set: RangeSet<u64>) {
let forward: Vec<_> = set.clone().into_iter().collect();
let mut backward: Vec<_> = set.into_iter().rev().collect();
backward.reverse();
assert_eq!(forward, backward);
}
#[proptest]
fn test_overlapping_reversible(set: RangeSet<u64>, range: Range<u64>) {
let forward: Vec<_> = set.overlapping(&range).collect();
let mut backward: Vec<_> = set.overlapping(&range).rev().collect();
backward.reverse();
assert_eq!(forward, backward);
}
// neccessary due to assertion on empty ranges
fn filter_ranges<T: Ord>(ranges: Vec<Range<T>>) -> Vec<Range<T>> {
ranges
.into_iter()
.filter(|range| range.start != range.end)
.collect()
}
#[proptest]
fn test_arbitrary_set_u8(ranges: Vec<Range<u8>>) {
let ranges = filter_ranges(ranges);
let set = ranges.iter().fold(RangeSet::new(), |mut set, range| {
set.insert(range.clone());
set
});
for value in 0..u8::MAX {
assert_eq!(
set.contains(&value),
ranges.iter().any(|range| range.contains(&value))
);
}
}
#[proptest]
#[allow(deprecated)]
fn test_hash(left: RangeSet<u64>, right: RangeSet<u64>) {
use core::hash::{Hash, Hasher, SipHasher};
let hash = |set: &RangeSet<_>| {
let mut hasher = SipHasher::new();
set.hash(&mut hasher);
hasher.finish()
};
if left == right {
assert!(
hash(&left) == hash(&right),
"if two values are equal, their hash must be equal"
);
}
// if the hashes are equal the values might not be the same (collision)
if hash(&left) != hash(&right) {
assert!(
left != right,
"if two value's hashes are not equal, they must not be equal"
);
}
}
#[proptest]
fn test_ord(left: RangeSet<u64>, right: RangeSet<u64>) {
assert_eq!(
left == right,
left.cmp(&right).is_eq(),
"ordering and equality must match"
);
assert_eq!(
left.cmp(&right),
left.partial_cmp(&right).unwrap(),
"ordering is total for ordered parameters"
);
}
#[test]
fn test_from_array() {
let mut set = RangeSet::new();
set.insert(0..100);
set.insert(200..300);
assert_eq!(set, RangeSet::from([0..100, 200..300]));
}
#[test]
fn test_macro() {
assert_eq!(range_set![], RangeSet::<i64>::new());
assert_eq!(
range_set![0..100, 200..300, 400..500],
[0..100, 200..300, 400..500].iter().cloned().collect(),
);
}
#[proptest]
fn test_union_overlaps_u8(left: RangeSet<u8>, right: RangeSet<u8>) {
let mut union = RangeSet::new();
for range in left.union(&right) {
// there should not be any overlaps in the ranges returned by the union
assert!(union.overlapping(&range).next().is_none());
union.insert(range);
}
}
#[proptest]
fn test_union_contains_u8(left: RangeSet<u8>, right: RangeSet<u8>) {
let union = (&left) | (&right);
// value should be in the union if and only if it is in either set
for value in 0..u8::MAX {
assert_eq!(
union.contains(&value),
left.contains(&value) || right.contains(&value)
);
}
}
#[proptest]
fn test_intersection_contains_u8(left: RangeSet<u8>, right: RangeSet<u8>) {
let intersection = (&left) & (&right);
// value should be in the intersection if and only if it is in both sets
for value in 0..u8::MAX {
assert_eq!(
intersection.contains(&value),
left.contains(&value) && right.contains(&value)
);
}
}
#[proptest]
fn test_intersection_overlaps_u8(left: RangeSet<u8>, right: RangeSet<u8>) {
let mut union = RangeSet::new();
for range in left.intersection(&right) {
// there should not be any overlaps in the ranges returned by the
// intersection
assert!(union.overlapping(&range).next().is_none());
union.insert(range);
}
}
trait RangeSetExt<T> {
fn to_vec(&self) -> Vec<Range<T>>;
}
impl<T> RangeSetExt<T> for RangeSet<T>
where
T: Ord + Clone,
{
fn to_vec(&self) -> Vec<Range<T>> {
self.iter().cloned().collect()
}
}
#[test]
fn empty_set_is_empty() {
let range_set: RangeSet<u32> = RangeSet::new();
assert_eq!(range_set.to_vec(), vec![]);
}
#[test]
fn insert_into_empty_map() {
let mut range_set: RangeSet<u32> = RangeSet::new();
range_set.insert(0..50);
assert_eq!(range_set.to_vec(), vec![0..50]);
}
#[test]
fn remove_partially_overlapping() {
let mut range_set: RangeSet<u32> = RangeSet::new();
range_set.insert(0..50);
range_set.remove(25..75);
assert_eq!(range_set.to_vec(), vec![0..25]);
}
#[test]
fn gaps_between_items_floating_inside_outer_range() {
let mut range_set: RangeSet<u32> = RangeSet::new();
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◌ ◌ ◌ ◌ ●-◌ ◌ ◌ ◌
range_set.insert(5..6);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◌ ◌ ●-◌ ◌ ◌ ◌ ◌ ◌
range_set.insert(3..4);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◆-------------◇ ◌
let outer_range = 1..8;
let mut gaps = range_set.gaps(&outer_range);
// Should yield gaps at start, between items,
// and at end.
assert_eq!(gaps.next(), Some(1..3));
assert_eq!(gaps.next(), Some(4..5));
assert_eq!(gaps.next(), Some(6..8));
assert_eq!(gaps.next(), None);
// Gaps iterator should be fused.
assert_eq!(gaps.next(), None);
assert_eq!(gaps.next(), None);
}
#[test]
fn overlapping_partial_edges_complete_middle() {
let mut range_map: RangeSet<u32> = RangeSet::new();
// 0 1 2 3 4 5 6 7 8 9
// ●---◌ ◌ ◌ ◌ ◌ ◌ ◌ ◌
range_map.insert(0..2);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◌ ◌ ●-◌ ◌ ◌ ◌ ◌ ◌
range_map.insert(3..4);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◌ ◌ ◌ ◌ ●---◌ ◌ ◌
range_map.insert(5..7);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◆---------◇ ◌ ◌ ◌
let query_range = 1..6;
let mut overlapping = range_map.overlapping(&query_range);
// Should yield partially overlapped range at start.
assert_eq!(overlapping.next(), Some(&(0..2)));
// Should yield completely overlapped range in middle.
assert_eq!(overlapping.next(), Some(&(3..4)));
// Should yield partially overlapped range at end.
assert_eq!(overlapping.next(), Some(&(5..7)));
// Gaps iterator should be fused.
assert_eq!(overlapping.next(), None);
assert_eq!(overlapping.next(), None);
}
///
/// impl Debug
///
#[test]
fn set_debug_repr_looks_right() {
let mut set: RangeSet<u32> = RangeSet::new();
// Empty
assert_eq!(format!("{:?}", set), "{}");
// One entry
set.insert(2..5);
assert_eq!(format!("{:?}", set), "{2..5}");
// Many entries
set.insert(7..8);
set.insert(10..11);
assert_eq!(format!("{:?}", set), "{2..5, 7..8, 10..11}");
}
// impl Default where T: ?Default
#[test]
fn always_default() {
struct NoDefault;
RangeSet::<NoDefault>::default();
}
// impl Serialize
#[cfg(feature = "serde1")]
#[test]
fn serialization() {
let mut range_set: RangeSet<u32> = RangeSet::new();
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◆---◇ ◌ ◌ ◌ ◌ ◌ ◌
range_set.insert(1..3);
// 0 1 2 3 4 5 6 7 8 9
// ◌ ◌ ◌ ◌ ◌ ◆---◇ ◌ ◌
range_set.insert(5..7);
let output = serde_json::to_string(&range_set).expect("Failed to serialize");
assert_eq!(output, "[[1,3],[5,7]]");
}
// impl Deserialize
#[cfg(feature = "serde1")]
#[test]
fn deserialization() {
let input = "[[1,3],[5,7]]";
let range_set: RangeSet<u32> = serde_json::from_str(input).expect("Failed to deserialize");
let reserialized = serde_json::to_string(&range_set).expect("Failed to re-serialize");
assert_eq!(reserialized, input);
}
// const fn
#[cfg(feature = "const_fn")]
const _SET: RangeSet<u32> = RangeSet::new();
#[cfg(feature = "quickcheck")]
quickcheck::quickcheck! {
fn prop(xs: RangeSet<usize>) -> bool {
xs == xs
}
}
}

176
vendor/rangemap/src/std_ext.rs vendored Normal file
View File

@@ -0,0 +1,176 @@
use core::ops::{Add, Range, RangeInclusive, Sub};
pub trait RangeExt<T> {
fn overlaps(&self, other: &Self) -> bool;
fn touches(&self, other: &Self) -> bool;
}
impl<T> RangeExt<T> for Range<T>
where
T: Ord,
{
fn overlaps(&self, other: &Self) -> bool {
use core::cmp::{max, min};
// Strictly less than, because ends are excluded.
max(&self.start, &other.start) < min(&self.end, &other.end)
}
fn touches(&self, other: &Self) -> bool {
use core::cmp::{max, min};
// Less-than-or-equal-to because if one end is excluded, the other is included.
// I.e. the two could be joined into a single range, because they're overlapping
// or immediately adjacent.
max(&self.start, &other.start) <= min(&self.end, &other.end)
}
}
pub trait RangeInclusiveExt<T> {
fn overlaps(&self, other: &Self) -> bool;
fn touches<StepFnsT>(&self, other: &Self) -> bool
where
StepFnsT: StepFns<T>;
}
impl<T> RangeInclusiveExt<T> for RangeInclusive<T>
where
T: Ord + Clone,
{
fn overlaps(&self, other: &Self) -> bool {
use core::cmp::{max, min};
// Less than or equal, because ends are included.
max(self.start(), other.start()) <= min(self.end(), other.end())
}
fn touches<StepFnsT>(&self, other: &Self) -> bool
where
StepFnsT: StepFns<T>,
{
use core::cmp::{max, min};
// Touching for end-inclusive ranges is equivalent to touching of
// slightly longer end-inclusive ranges.
//
// We need to do a small dance to avoid arithmetic overflow
// at the extremes of the key space. And to do this without
// needing to bound our key type on something like `num::Bounded`
// (https://docs.rs/num/0.3.0/num/trait.Bounded.html),
// we'll just extend the end of the _earlier_ range iff
// its end is already earlier than the latter range's start.
let max_start = max(self.start(), other.start());
let min_range_end = min(self.end(), other.end());
let min_range_end_extended = if min_range_end < max_start {
StepFnsT::add_one(min_range_end)
} else {
min_range_end.clone()
};
*max_start <= min_range_end_extended
}
}
/// Minimal version of unstable [`Step`](core::iter::Step) trait
/// from the Rust standard library.
///
/// This is needed for [`RangeInclusiveMap`](crate::RangeInclusiveMap)
/// because ranges stored as its keys interact with each other
/// when the start of one is _adjacent_ the end of another.
/// I.e. we need a concept of successor values rather than just
/// equality, and that is what `Step` will
/// eventually provide once it is stabilized.
///
/// **NOTE:** This will likely be deprecated and then eventually
/// removed once the standard library's `Step`
/// trait is stabilised, as most crates will then likely implement `Step`
/// for their types where appropriate.
///
/// See [this issue](https://github.com/rust-lang/rust/issues/42168)
/// for details about that stabilization process.
pub trait StepLite {
/// Returns the _successor_ of `self`.
///
/// If this would overflow the range of values supported by `Self`,
/// this function is allowed to panic, wrap, or saturate.
/// The suggested behavior is to panic when debug assertions are enabled,
/// and to wrap or saturate otherwise.
fn add_one(&self) -> Self;
/// Returns the _predecessor_ of `self`.
///
/// If this would overflow the range of values supported by `Self`,
/// this function is allowed to panic, wrap, or saturate.
/// The suggested behavior is to panic when debug assertions are enabled,
/// and to wrap or saturate otherwise.
fn sub_one(&self) -> Self;
}
// Implement for all common integer types.
macro_rules! impl_step_lite {
($($t:ty)*) => ($(
impl StepLite for $t {
#[inline]
fn add_one(&self) -> Self {
Add::add(*self, 1)
}
#[inline]
fn sub_one(&self) -> Self {
Sub::sub(*self, 1)
}
}
)*)
}
impl_step_lite!(usize u8 u16 u32 u64 u128 i8 i16 i32 i64 i128);
// TODO: When on nightly, a blanket implementation for
// all types that implement `core::iter::Step` instead
// of the auto-impl above.
/// Successor and predecessor functions defined for `T`,
/// but as free functions rather than methods on `T` itself.
///
/// This is useful as a workaround for Rust's "orphan rules",
/// which prevent you from implementing [`StepLite`](crate::StepLite) for `T` if `T`
/// is a foreign type.
///
/// **NOTE:** This will likely be deprecated and then eventually
/// removed once the standard library's [`Step`](core::iter::Step)
/// trait is stabilised, as most crates will then likely implement `Step`
/// for their types where appropriate.
///
/// See [this issue](https://github.com/rust-lang/rust/issues/42168)
/// for details about that stabilization process.
///
/// There is also a blanket implementation of `StepFns` for all
/// types implementing `StepLite`. Consumers of this crate should
/// prefer to implement `StepLite` for their own types, and only
/// fall back to `StepFns` when dealing with foreign types.
pub trait StepFns<T> {
/// Returns the _successor_ of value `start`.
///
/// If this would overflow the range of values supported by `Self`,
/// this function is allowed to panic, wrap, or saturate.
/// The suggested behavior is to panic when debug assertions are enabled,
/// and to wrap or saturate otherwise.
fn add_one(start: &T) -> T;
/// Returns the _predecessor_ of value `start`.
///
/// If this would overflow the range of values supported by `Self`,
/// this function is allowed to panic, wrap, or saturate.
/// The suggested behavior is to panic when debug assertions are enabled,
/// and to wrap or saturate otherwise.
fn sub_one(start: &T) -> T;
}
impl<T> StepFns<T> for T
where
T: StepLite,
{
fn add_one(start: &T) -> T {
start.add_one()
}
fn sub_one(start: &T) -> T {
start.sub_one()
}
}