Bug 1675639 - Update indexmap. r=boris

New versions have shrink_to_fit(). This also explicitly requests the
"std" feature, because otherwise autocfg fails to pass the panic=abort
flag to rustc and it chokes.

Depends on D96130

Differential Revision: https://phabricator.services.mozilla.com/D96131
This commit is contained in:
Emilio Cobos Álvarez 2020-11-06 12:46:13 +00:00
Родитель b8d518c220
Коммит e4d9bac157
47 изменённых файлов: 4222 добавлений и 2266 удалений

26
Cargo.lock сгенерированный
Просмотреть файл

@ -210,6 +210,12 @@ version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b671c8fb71b457dd4ae18c4ba1e59aa81793daacc361d82fcd410cef0d491875"
[[package]]
name = "autocfg"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "baldrdash"
version = "0.1.0"
@ -868,7 +874,7 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5064ebdbf05ce3cb95e45c8b086f72263f4166b29b97f6baff7ef7fe047b55ac"
dependencies = [
"autocfg",
"autocfg 0.1.6",
"cfg-if 0.1.10",
"crossbeam-utils 0.7.0",
"lazy_static",
@ -901,7 +907,7 @@ version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce446db02cdc3165b94ae73111e570793400d0794e46125cc4056c81cbb039f4"
dependencies = [
"autocfg",
"autocfg 0.1.6",
"cfg-if 0.1.10",
"lazy_static",
]
@ -2377,9 +2383,13 @@ dependencies = [
[[package]]
name = "indexmap"
version = "1.1.0"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4d6d89e0948bf10c08b9ecc8ac5b83f07f857ebe2c0cbe38de15b4e4f510356"
checksum = "55e2e4c765aa53a0424761bf9f41aa7a6ac1efa87238f59560640e27fca028f2"
dependencies = [
"autocfg 1.0.1",
"hashbrown",
]
[[package]]
name = "inflate"
@ -3445,7 +3455,7 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9c3f34cdd24f334cb265d9bf8bfa8a241920d026916785747a92f0e55541a1a"
dependencies = [
"autocfg",
"autocfg 0.1.6",
"num-integer",
"num-traits",
]
@ -3467,7 +3477,7 @@ version = "0.1.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b85e541ef8255f6cf42bbfe4ef361305c6c135d10919ecc26126c4e5ae94bc09"
dependencies = [
"autocfg",
"autocfg 0.1.6",
"num-traits",
]
@ -3477,7 +3487,7 @@ version = "0.1.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76bd5272412d173d6bf9afdf98db8612bbabc9a7a830b7bfc9c188911716132e"
dependencies = [
"autocfg",
"autocfg 0.1.6",
"num-integer",
"num-traits",
]
@ -3498,7 +3508,7 @@ version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4c81ffc11c212fa327657cb19dd85eb7419e163b5b076bede2bdb5c974c07e4"
dependencies = [
"autocfg",
"autocfg 0.1.6",
]
[[package]]

Просмотреть файл

@ -43,7 +43,7 @@ fxhash = "0.2"
hashbrown = "0.9"
hashglobe = { path = "../hashglobe" }
html5ever = {version = "0.24", optional = true}
indexmap = "1.0"
indexmap = {version = "1.0", features = ["std"]}
itertools = "0.8"
itoa = "0.4"
lazy_static = "1"

1
third_party/rust/autocfg-0.1.6/.cargo-checksum.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1 @@
{"files":{"Cargo.lock":"461e5e87b13d7faf25813b08b5003060c39d8af0953f30d5b80ae0926c888022","Cargo.toml":"1eded5c9954b3bb92bb2c7403e026198e66a2a42199db06fc9cafddc8d1fd677","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"27995d58ad5c1145c1a8cd86244ce844886958a35eb2b78c6b772748669999ac","README.md":"ba9a1621483e0b9f017f07c282d00d5cf3a2d8660cca6df6b14941319d748953","examples/integers.rs":"589ff4271566dfa322becddf3e2c7b592e6e0bc97b02892ce75619b7e452e930","examples/paths.rs":"1b30e466b824ce8df7ad0a55334424131d9d2573d6cf9f7d5d50c09c8901d526","examples/traits.rs":"cbee6a3e1f7db60b02ae25b714926517144a77cb492021f492774cf0e1865a9e","examples/versions.rs":"38535e6d9f5bfae0de474a3db79a40e8f5da8ba9334c5ff4c363de9bc99d4d12","src/error.rs":"12de7dafea4a35d1dc2f0fa79bfa038386bbbea72bf083979f4ddf227999eeda","src/lib.rs":"411d8dbc48ab0f67cb10243f1e16b235407818c96556c838182e4004da995dff","src/tests.rs":"0b1353344e832553d328c47f1639ced877b5dff70fd2024d84130bd1c33eee07","src/version.rs":"175727d5f02f2fe2271ddc9b041db2a5b9c6fe0f95afd17c73a4d982612764a3"},"package":"b671c8fb71b457dd4ae18c4ba1e59aa81793daacc361d82fcd410cef0d491875"}

6
third_party/rust/autocfg-0.1.6/Cargo.lock сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "autocfg"
version = "0.1.6"

24
third_party/rust/autocfg-0.1.6/Cargo.toml поставляемый Normal file
Просмотреть файл

@ -0,0 +1,24 @@
# 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 believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
# editing this file be aware that the upstream Cargo.toml
# will likely look very different (and much more reasonable)
[package]
name = "autocfg"
version = "0.1.6"
authors = ["Josh Stone <cuviper@gmail.com>"]
description = "Automatic cfg for Rust compiler features"
readme = "README.md"
keywords = ["rustc", "build", "autoconf"]
categories = ["development-tools::build-utils"]
license = "Apache-2.0/MIT"
repository = "https://github.com/cuviper/autocfg"
[dependencies]

201
third_party/rust/autocfg-0.1.6/LICENSE-APACHE поставляемый Normal file
Просмотреть файл

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
third_party/rust/autocfg-0.1.6/LICENSE-MIT поставляемый Normal file
Просмотреть файл

@ -0,0 +1,25 @@
Copyright (c) 2018 Josh Stone
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.

81
third_party/rust/autocfg-0.1.6/README.md поставляемый Normal file
Просмотреть файл

@ -0,0 +1,81 @@
autocfg
=======
[![autocfg crate](https://img.shields.io/crates/v/autocfg.svg)](https://crates.io/crates/autocfg)
[![autocfg documentation](https://docs.rs/autocfg/badge.svg)](https://docs.rs/autocfg)
![minimum rustc 1.0](https://img.shields.io/badge/rustc-1.0+-red.svg)
[![Travis Status](https://travis-ci.org/cuviper/autocfg.svg?branch=master)](https://travis-ci.org/cuviper/autocfg)
A Rust library for build scripts to automatically configure code based on
compiler support. Code snippets are dynamically tested to see if the `rustc`
will accept them, rather than hard-coding specific version support.
## Usage
Add this to your `Cargo.toml`:
```toml
[build-dependencies]
autocfg = "0.1"
```
Then use it in your `build.rs` script to detect compiler features. For
example, to test for 128-bit integer support, it might look like:
```rust
extern crate autocfg;
fn main() {
let ac = autocfg::new();
ac.emit_has_type("i128");
// (optional) We don't need to rerun for anything external.
autocfg::rerun_path(file!());
}
```
If the type test succeeds, this will write a `cargo:rustc-cfg=has_i128` line
for Cargo, which translates to Rust arguments `--cfg has_i128`. Then in the
rest of your Rust code, you can add `#[cfg(has_i128)]` conditions on code that
should only be used when the compiler supports it.
## Release Notes
- 0.1.6 (2019-08-19)
- Add `probe`/`emit_sysroot_crate`, by @leo60228
- 0.1.5 (2019-07-16)
- Mask some warnings from newer rustc.
- 0.1.4 (2019-05-22)
- Relax `std`/`no_std` probing to a warning instead of an error.
- Improve `rustc` bootstrap compatibility.
- 0.1.3 (2019-05-21)
- Auto-detects if `#![no_std]` is needed for the `$TARGET`
- 0.1.2 (2019-01-16)
- Add `rerun_env(ENV)` to print `cargo:rerun-if-env-changed=ENV`
- Add `rerun_path(PATH)` to print `cargo:rerun-if-changed=PATH`
## Minimum Rust version policy
This crate's minimum supported `rustc` version is `1.0.0`. Compatibility is
its entire reason for existence, so this crate will be extremely conservative
about raising this requirement. If this is ever deemed necessary, it will be
treated as a major breaking change for semver purposes.
## License
This project is licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or
http://opensource.org/licenses/MIT)
at your option.

9
third_party/rust/autocfg-0.1.6/examples/integers.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,9 @@
extern crate autocfg;
fn main() {
// Normally, cargo will set `OUT_DIR` for build scripts.
let ac = autocfg::AutoCfg::with_dir("target").unwrap();
for i in 3..8 {
ac.emit_has_type(&format!("i{}", 1 << i));
}
}

22
third_party/rust/autocfg-0.1.6/examples/paths.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,22 @@
extern crate autocfg;
fn main() {
// Normally, cargo will set `OUT_DIR` for build scripts.
let ac = autocfg::AutoCfg::with_dir("target").unwrap();
// since ancient times...
ac.emit_has_path("std::vec::Vec");
ac.emit_path_cfg("std::vec::Vec", "has_vec");
// rustc 1.10.0
ac.emit_has_path("std::panic::PanicInfo");
ac.emit_path_cfg("std::panic::PanicInfo", "has_panic_info");
// rustc 1.20.0
ac.emit_has_path("std::mem::ManuallyDrop");
ac.emit_path_cfg("std::mem::ManuallyDrop", "has_manually_drop");
// rustc 1.25.0
ac.emit_has_path("std::ptr::NonNull");
ac.emit_path_cfg("std::ptr::NonNull", "has_non_null");
}

26
third_party/rust/autocfg-0.1.6/examples/traits.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,26 @@
extern crate autocfg;
fn main() {
// Normally, cargo will set `OUT_DIR` for build scripts.
let ac = autocfg::AutoCfg::with_dir("target").unwrap();
// since ancient times...
ac.emit_has_trait("std::ops::Add");
ac.emit_trait_cfg("std::ops::Add", "has_ops");
// trait parameters have to be provided
ac.emit_has_trait("std::borrow::Borrow<str>");
ac.emit_trait_cfg("std::borrow::Borrow<str>", "has_borrow");
// rustc 1.8.0
ac.emit_has_trait("std::ops::AddAssign");
ac.emit_trait_cfg("std::ops::AddAssign", "has_assign_ops");
// rustc 1.12.0
ac.emit_has_trait("std::iter::Sum");
ac.emit_trait_cfg("std::iter::Sum", "has_sum");
// rustc 1.28.0
ac.emit_has_trait("std::alloc::GlobalAlloc");
ac.emit_trait_cfg("std::alloc::GlobalAlloc", "has_global_alloc");
}

9
third_party/rust/autocfg-0.1.6/examples/versions.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,9 @@
extern crate autocfg;
fn main() {
// Normally, cargo will set `OUT_DIR` for build scripts.
let ac = autocfg::AutoCfg::with_dir("target").unwrap();
for i in 0..100 {
ac.emit_rustc_version(1, i);
}
}

69
third_party/rust/autocfg-0.1.6/src/error.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,69 @@
use std::error;
use std::fmt;
use std::io;
use std::num;
use std::str;
/// A common error type for the `autocfg` crate.
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
}
impl error::Error for Error {
fn description(&self) -> &str {
"AutoCfg error"
}
fn cause(&self) -> Option<&error::Error> {
match self.kind {
ErrorKind::Io(ref e) => Some(e),
ErrorKind::Num(ref e) => Some(e),
ErrorKind::Utf8(ref e) => Some(e),
ErrorKind::Other(_) => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self.kind {
ErrorKind::Io(ref e) => e.fmt(f),
ErrorKind::Num(ref e) => e.fmt(f),
ErrorKind::Utf8(ref e) => e.fmt(f),
ErrorKind::Other(s) => s.fmt(f),
}
}
}
#[derive(Debug)]
enum ErrorKind {
Io(io::Error),
Num(num::ParseIntError),
Utf8(str::Utf8Error),
Other(&'static str),
}
pub fn from_io(e: io::Error) -> Error {
Error {
kind: ErrorKind::Io(e),
}
}
pub fn from_num(e: num::ParseIntError) -> Error {
Error {
kind: ErrorKind::Num(e),
}
}
pub fn from_utf8(e: str::Utf8Error) -> Error {
Error {
kind: ErrorKind::Utf8(e),
}
}
pub fn from_str(s: &'static str) -> Error {
Error {
kind: ErrorKind::Other(s),
}
}

328
third_party/rust/autocfg-0.1.6/src/lib.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,328 @@
//! A Rust library for build scripts to automatically configure code based on
//! compiler support. Code snippets are dynamically tested to see if the `rustc`
//! will accept them, rather than hard-coding specific version support.
//!
//!
//! ## Usage
//!
//! Add this to your `Cargo.toml`:
//!
//! ```toml
//! [build-dependencies]
//! autocfg = "0.1"
//! ```
//!
//! Then use it in your `build.rs` script to detect compiler features. For
//! example, to test for 128-bit integer support, it might look like:
//!
//! ```rust
//! extern crate autocfg;
//!
//! fn main() {
//! # // Normally, cargo will set `OUT_DIR` for build scripts.
//! # std::env::set_var("OUT_DIR", "target");
//! let ac = autocfg::new();
//! ac.emit_has_type("i128");
//!
//! // (optional) We don't need to rerun for anything external.
//! autocfg::rerun_path(file!());
//! }
//! ```
//!
//! If the type test succeeds, this will write a `cargo:rustc-cfg=has_i128` line
//! for Cargo, which translates to Rust arguments `--cfg has_i128`. Then in the
//! rest of your Rust code, you can add `#[cfg(has_i128)]` conditions on code that
//! should only be used when the compiler supports it.
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
// allow future warnings that can't be fixed while keeping 1.0 compatibility
#![allow(unknown_lints)]
#![allow(bare_trait_objects)]
#![allow(ellipsis_inclusive_range_patterns)]
use std::env;
use std::ffi::OsString;
use std::fs;
use std::io::{stderr, Write};
use std::path::PathBuf;
use std::process::{Command, Stdio};
#[allow(deprecated)]
use std::sync::atomic::ATOMIC_USIZE_INIT;
use std::sync::atomic::{AtomicUsize, Ordering};
mod error;
pub use error::Error;
mod version;
use version::Version;
#[cfg(test)]
mod tests;
/// Helper to detect compiler features for `cfg` output in build scripts.
#[derive(Clone, Debug)]
pub struct AutoCfg {
out_dir: PathBuf,
rustc: PathBuf,
rustc_version: Version,
target: Option<OsString>,
no_std: bool,
}
/// Writes a config flag for rustc on standard out.
///
/// This looks like: `cargo:rustc-cfg=CFG`
///
/// Cargo will use this in arguments to rustc, like `--cfg CFG`.
pub fn emit(cfg: &str) {
println!("cargo:rustc-cfg={}", cfg);
}
/// Writes a line telling Cargo to rerun the build script if `path` changes.
///
/// This looks like: `cargo:rerun-if-changed=PATH`
///
/// This requires at least cargo 0.7.0, corresponding to rustc 1.6.0. Earlier
/// versions of cargo will simply ignore the directive.
pub fn rerun_path(path: &str) {
println!("cargo:rerun-if-changed={}", path);
}
/// Writes a line telling Cargo to rerun the build script if the environment
/// variable `var` changes.
///
/// This looks like: `cargo:rerun-if-env-changed=VAR`
///
/// This requires at least cargo 0.21.0, corresponding to rustc 1.20.0. Earlier
/// versions of cargo will simply ignore the directive.
pub fn rerun_env(var: &str) {
println!("cargo:rerun-if-env-changed={}", var);
}
/// Create a new `AutoCfg` instance.
///
/// # Panics
///
/// Panics if `AutoCfg::new()` returns an error.
pub fn new() -> AutoCfg {
AutoCfg::new().unwrap()
}
impl AutoCfg {
/// Create a new `AutoCfg` instance.
///
/// # Common errors
///
/// - `rustc` can't be executed, from `RUSTC` or in the `PATH`.
/// - The version output from `rustc` can't be parsed.
/// - `OUT_DIR` is not set in the environment, or is not a writable directory.
///
pub fn new() -> Result<Self, Error> {
match env::var_os("OUT_DIR") {
Some(d) => Self::with_dir(d),
None => Err(error::from_str("no OUT_DIR specified!")),
}
}
/// Create a new `AutoCfg` instance with the specified output directory.
///
/// # Common errors
///
/// - `rustc` can't be executed, from `RUSTC` or in the `PATH`.
/// - The version output from `rustc` can't be parsed.
/// - `dir` is not a writable directory.
///
pub fn with_dir<T: Into<PathBuf>>(dir: T) -> Result<Self, Error> {
let rustc = env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());
let rustc: PathBuf = rustc.into();
let rustc_version = try!(Version::from_rustc(&rustc));
// Sanity check the output directory
let dir = dir.into();
let meta = try!(fs::metadata(&dir).map_err(error::from_io));
if !meta.is_dir() || meta.permissions().readonly() {
return Err(error::from_str("output path is not a writable directory"));
}
let mut ac = AutoCfg {
out_dir: dir,
rustc: rustc,
rustc_version: rustc_version,
target: env::var_os("TARGET"),
no_std: false,
};
// Sanity check with and without `std`.
if !ac.probe("").unwrap_or(false) {
ac.no_std = true;
if !ac.probe("").unwrap_or(false) {
// Neither worked, so assume nothing...
ac.no_std = false;
let warning = b"warning: autocfg could not probe for `std`\n";
stderr().write_all(warning).ok();
}
}
Ok(ac)
}
/// Test whether the current `rustc` reports a version greater than
/// or equal to "`major`.`minor`".
pub fn probe_rustc_version(&self, major: usize, minor: usize) -> bool {
self.rustc_version >= Version::new(major, minor, 0)
}
/// Sets a `cfg` value of the form `rustc_major_minor`, like `rustc_1_29`,
/// if the current `rustc` is at least that version.
pub fn emit_rustc_version(&self, major: usize, minor: usize) {
if self.probe_rustc_version(major, minor) {
emit(&format!("rustc_{}_{}", major, minor));
}
}
fn probe<T: AsRef<[u8]>>(&self, code: T) -> Result<bool, Error> {
#[allow(deprecated)]
static ID: AtomicUsize = ATOMIC_USIZE_INIT;
let id = ID.fetch_add(1, Ordering::Relaxed);
let mut command = Command::new(&self.rustc);
command
.arg("--crate-name")
.arg(format!("probe{}", id))
.arg("--crate-type=lib")
.arg("--out-dir")
.arg(&self.out_dir)
.arg("--emit=llvm-ir");
if let Some(target) = self.target.as_ref() {
command.arg("--target").arg(target);
}
command.arg("-").stdin(Stdio::piped());
let mut child = try!(command.spawn().map_err(error::from_io));
let mut stdin = child.stdin.take().expect("rustc stdin");
if self.no_std {
try!(stdin.write_all(b"#![no_std]\n").map_err(error::from_io));
}
try!(stdin.write_all(code.as_ref()).map_err(error::from_io));
drop(stdin);
let status = try!(child.wait().map_err(error::from_io));
Ok(status.success())
}
/// Tests whether the given sysroot crate can be used.
///
/// The test code is subject to change, but currently looks like:
///
/// ```ignore
/// extern crate CRATE as probe;
/// ```
pub fn probe_sysroot_crate(&self, name: &str) -> bool {
self.probe(format!("extern crate {} as probe;", name)) // `as _` wasn't stabilized until Rust 1.33
.unwrap_or(false)
}
/// Emits a config value `has_CRATE` if `probe_sysroot_crate` returns true.
pub fn emit_sysroot_crate(&self, name: &str) {
if self.probe_sysroot_crate(name) {
emit(&format!("has_{}", mangle(name)));
}
}
/// Tests whether the given path can be used.
///
/// The test code is subject to change, but currently looks like:
///
/// ```ignore
/// pub use PATH;
/// ```
pub fn probe_path(&self, path: &str) -> bool {
self.probe(format!("pub use {};", path)).unwrap_or(false)
}
/// Emits a config value `has_PATH` if `probe_path` returns true.
///
/// Any non-identifier characters in the `path` will be replaced with
/// `_` in the generated config value.
pub fn emit_has_path(&self, path: &str) {
if self.probe_path(path) {
emit(&format!("has_{}", mangle(path)));
}
}
/// Emits the given `cfg` value if `probe_path` returns true.
pub fn emit_path_cfg(&self, path: &str, cfg: &str) {
if self.probe_path(path) {
emit(cfg);
}
}
/// Tests whether the given trait can be used.
///
/// The test code is subject to change, but currently looks like:
///
/// ```ignore
/// pub trait Probe: TRAIT + Sized {}
/// ```
pub fn probe_trait(&self, name: &str) -> bool {
self.probe(format!("pub trait Probe: {} + Sized {{}}", name))
.unwrap_or(false)
}
/// Emits a config value `has_TRAIT` if `probe_trait` returns true.
///
/// Any non-identifier characters in the trait `name` will be replaced with
/// `_` in the generated config value.
pub fn emit_has_trait(&self, name: &str) {
if self.probe_trait(name) {
emit(&format!("has_{}", mangle(name)));
}
}
/// Emits the given `cfg` value if `probe_trait` returns true.
pub fn emit_trait_cfg(&self, name: &str, cfg: &str) {
if self.probe_trait(name) {
emit(cfg);
}
}
/// Tests whether the given type can be used.
///
/// The test code is subject to change, but currently looks like:
///
/// ```ignore
/// pub type Probe = TYPE;
/// ```
pub fn probe_type(&self, name: &str) -> bool {
self.probe(format!("pub type Probe = {};", name))
.unwrap_or(false)
}
/// Emits a config value `has_TYPE` if `probe_type` returns true.
///
/// Any non-identifier characters in the type `name` will be replaced with
/// `_` in the generated config value.
pub fn emit_has_type(&self, name: &str) {
if self.probe_type(name) {
emit(&format!("has_{}", mangle(name)));
}
}
/// Emits the given `cfg` value if `probe_type` returns true.
pub fn emit_type_cfg(&self, name: &str, cfg: &str) {
if self.probe_type(name) {
emit(cfg);
}
}
}
fn mangle(s: &str) -> String {
s.chars()
.map(|c| match c {
'A'...'Z' | 'a'...'z' | '0'...'9' => c,
_ => '_',
})
.collect()
}

99
third_party/rust/autocfg-0.1.6/src/tests.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,99 @@
use super::AutoCfg;
impl AutoCfg {
fn core_std(&self, path: &str) -> String {
let krate = if self.no_std { "core" } else { "std" };
format!("{}::{}", krate, path)
}
}
#[test]
fn autocfg_version() {
let ac = AutoCfg::with_dir("target").unwrap();
println!("version: {:?}", ac.rustc_version);
assert!(ac.probe_rustc_version(1, 0));
}
#[test]
fn version_cmp() {
use super::version::Version;
let v123 = Version::new(1, 2, 3);
assert!(Version::new(1, 0, 0) < v123);
assert!(Version::new(1, 2, 2) < v123);
assert!(Version::new(1, 2, 3) == v123);
assert!(Version::new(1, 2, 4) > v123);
assert!(Version::new(1, 10, 0) > v123);
assert!(Version::new(2, 0, 0) > v123);
}
#[test]
fn probe_add() {
let ac = AutoCfg::with_dir("target").unwrap();
let add = ac.core_std("ops::Add");
let add_rhs = ac.core_std("ops::Add<i32>");
let add_rhs_output = ac.core_std("ops::Add<i32, Output = i32>");
assert!(ac.probe_path(&add));
assert!(ac.probe_trait(&add));
assert!(ac.probe_trait(&add_rhs));
assert!(ac.probe_trait(&add_rhs_output));
assert!(ac.probe_type(&add_rhs_output));
}
#[test]
fn probe_as_ref() {
let ac = AutoCfg::with_dir("target").unwrap();
let as_ref = ac.core_std("convert::AsRef");
let as_ref_str = ac.core_std("convert::AsRef<str>");
assert!(ac.probe_path(&as_ref));
assert!(ac.probe_trait(&as_ref_str));
assert!(ac.probe_type(&as_ref_str));
}
#[test]
fn probe_i128() {
let ac = AutoCfg::with_dir("target").unwrap();
let missing = !ac.probe_rustc_version(1, 26);
let i128_path = ac.core_std("i128");
assert!(missing ^ ac.probe_path(&i128_path));
assert!(missing ^ ac.probe_type("i128"));
}
#[test]
fn probe_sum() {
let ac = AutoCfg::with_dir("target").unwrap();
let missing = !ac.probe_rustc_version(1, 12);
let sum = ac.core_std("iter::Sum");
let sum_i32 = ac.core_std("iter::Sum<i32>");
assert!(missing ^ ac.probe_path(&sum));
assert!(missing ^ ac.probe_trait(&sum));
assert!(missing ^ ac.probe_trait(&sum_i32));
assert!(missing ^ ac.probe_type(&sum_i32));
}
#[test]
fn probe_std() {
let ac = AutoCfg::with_dir("target").unwrap();
assert_eq!(ac.probe_sysroot_crate("std"), !ac.no_std);
}
#[test]
fn probe_alloc() {
let ac = AutoCfg::with_dir("target").unwrap();
let missing = !ac.probe_rustc_version(1, 36);
assert!(missing ^ ac.probe_sysroot_crate("alloc"));
}
#[test]
fn probe_bad_sysroot_crate() {
let ac = AutoCfg::with_dir("target").unwrap();
assert!(!ac.probe_sysroot_crate("doesnt_exist"));
}
#[test]
fn probe_no_std() {
let ac = AutoCfg::with_dir("target").unwrap();
assert!(ac.probe_type("i32"));
assert!(ac.probe_type("[i32]"));
assert_eq!(ac.probe_type("Vec<i32>"), !ac.no_std);
}

60
third_party/rust/autocfg-0.1.6/src/version.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,60 @@
use std::path::Path;
use std::process::Command;
use std::str;
use super::{error, Error};
/// A version structure for making relative comparisons.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Version {
major: usize,
minor: usize,
patch: usize,
}
impl Version {
/// Creates a `Version` instance for a specific `major.minor.patch` version.
pub fn new(major: usize, minor: usize, patch: usize) -> Self {
Version {
major: major,
minor: minor,
patch: patch,
}
}
pub fn from_rustc(rustc: &Path) -> Result<Self, Error> {
// Get rustc's verbose version
let output = try!(Command::new(rustc)
.args(&["--version", "--verbose"])
.output()
.map_err(error::from_io));
if !output.status.success() {
return Err(error::from_str("could not execute rustc"));
}
let output = try!(str::from_utf8(&output.stdout).map_err(error::from_utf8));
// Find the release line in the verbose version output.
let release = match output.lines().find(|line| line.starts_with("release: ")) {
Some(line) => &line["release: ".len()..],
None => return Err(error::from_str("could not find rustc release")),
};
// Strip off any extra channel info, e.g. "-beta.N", "-nightly"
let version = match release.find('-') {
Some(i) => &release[..i],
None => release,
};
// Split the version into semver components.
let mut iter = version.splitn(3, '.');
let major = try!(iter.next().ok_or(error::from_str("missing major version")));
let minor = try!(iter.next().ok_or(error::from_str("missing minor version")));
let patch = try!(iter.next().ok_or(error::from_str("missing patch version")));
Ok(Version::new(
try!(major.parse().map_err(error::from_num)),
try!(minor.parse().map_err(error::from_num)),
try!(patch.parse().map_err(error::from_num)),
))
}
}

Просмотреть файл

@ -1 +1 @@
{"files":{"Cargo.lock":"461e5e87b13d7faf25813b08b5003060c39d8af0953f30d5b80ae0926c888022","Cargo.toml":"1eded5c9954b3bb92bb2c7403e026198e66a2a42199db06fc9cafddc8d1fd677","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"27995d58ad5c1145c1a8cd86244ce844886958a35eb2b78c6b772748669999ac","README.md":"ba9a1621483e0b9f017f07c282d00d5cf3a2d8660cca6df6b14941319d748953","examples/integers.rs":"589ff4271566dfa322becddf3e2c7b592e6e0bc97b02892ce75619b7e452e930","examples/paths.rs":"1b30e466b824ce8df7ad0a55334424131d9d2573d6cf9f7d5d50c09c8901d526","examples/traits.rs":"cbee6a3e1f7db60b02ae25b714926517144a77cb492021f492774cf0e1865a9e","examples/versions.rs":"38535e6d9f5bfae0de474a3db79a40e8f5da8ba9334c5ff4c363de9bc99d4d12","src/error.rs":"12de7dafea4a35d1dc2f0fa79bfa038386bbbea72bf083979f4ddf227999eeda","src/lib.rs":"411d8dbc48ab0f67cb10243f1e16b235407818c96556c838182e4004da995dff","src/tests.rs":"0b1353344e832553d328c47f1639ced877b5dff70fd2024d84130bd1c33eee07","src/version.rs":"175727d5f02f2fe2271ddc9b041db2a5b9c6fe0f95afd17c73a4d982612764a3"},"package":"b671c8fb71b457dd4ae18c4ba1e59aa81793daacc361d82fcd410cef0d491875"}
{"files":{"Cargo.lock":"d658acfaa27a2b30de98cf004d4d3f4ec0f1757b136610289cbbd1c847ae2e6c","Cargo.toml":"e2176be78c2989884eba4a20a58a672277b3a8a99a72b0ba7347f48eb827ae0e","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"27995d58ad5c1145c1a8cd86244ce844886958a35eb2b78c6b772748669999ac","README.md":"2d8b6f07819ad7adfab1d153216bfdcde154ffd4a870d98794125c910b0f4593","examples/integers.rs":"589ff4271566dfa322becddf3e2c7b592e6e0bc97b02892ce75619b7e452e930","examples/paths.rs":"1b30e466b824ce8df7ad0a55334424131d9d2573d6cf9f7d5d50c09c8901d526","examples/traits.rs":"cbee6a3e1f7db60b02ae25b714926517144a77cb492021f492774cf0e1865a9e","examples/versions.rs":"38535e6d9f5bfae0de474a3db79a40e8f5da8ba9334c5ff4c363de9bc99d4d12","src/error.rs":"12de7dafea4a35d1dc2f0fa79bfa038386bbbea72bf083979f4ddf227999eeda","src/lib.rs":"9b450d90730624807979045ea7ff48374355314cd894345e1b9651485ba1b2ff","src/tests.rs":"a902fbd42b0f0b81a2830f2368fab733041b02fcb902c8e2520d07b3bff10713","src/version.rs":"175727d5f02f2fe2271ddc9b041db2a5b9c6fe0f95afd17c73a4d982612764a3","tests/rustflags.rs":"441fb0c6606e243c31d3817a5ae2240b65fcae0ea8ab583f80f8f6d6c267e614"},"package":"cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"}

2
third_party/rust/autocfg/Cargo.lock сгенерированный поставляемый
Просмотреть файл

@ -2,5 +2,5 @@
# It is not intended for manual editing.
[[package]]
name = "autocfg"
version = "0.1.6"
version = "1.0.1"

5
third_party/rust/autocfg/Cargo.toml поставляемый
Просмотреть файл

@ -12,13 +12,14 @@
[package]
name = "autocfg"
version = "0.1.6"
version = "1.0.1"
authors = ["Josh Stone <cuviper@gmail.com>"]
exclude = ["/.github/**", "/bors.toml"]
description = "Automatic cfg for Rust compiler features"
readme = "README.md"
keywords = ["rustc", "build", "autoconf"]
categories = ["development-tools::build-utils"]
license = "Apache-2.0/MIT"
license = "Apache-2.0 OR MIT"
repository = "https://github.com/cuviper/autocfg"
[dependencies]

25
third_party/rust/autocfg/README.md поставляемый
Просмотреть файл

@ -4,7 +4,7 @@ autocfg
[![autocfg crate](https://img.shields.io/crates/v/autocfg.svg)](https://crates.io/crates/autocfg)
[![autocfg documentation](https://docs.rs/autocfg/badge.svg)](https://docs.rs/autocfg)
![minimum rustc 1.0](https://img.shields.io/badge/rustc-1.0+-red.svg)
[![Travis Status](https://travis-ci.org/cuviper/autocfg.svg?branch=master)](https://travis-ci.org/cuviper/autocfg)
![build status](https://github.com/cuviper/autocfg/workflows/master/badge.svg)
A Rust library for build scripts to automatically configure code based on
compiler support. Code snippets are dynamically tested to see if the `rustc`
@ -17,7 +17,7 @@ Add this to your `Cargo.toml`:
```toml
[build-dependencies]
autocfg = "0.1"
autocfg = "1"
```
Then use it in your `build.rs` script to detect compiler features. For
@ -31,7 +31,7 @@ fn main() {
ac.emit_has_type("i128");
// (optional) We don't need to rerun for anything external.
autocfg::rerun_path(file!());
autocfg::rerun_path("build.rs");
}
```
@ -43,8 +43,19 @@ should only be used when the compiler supports it.
## Release Notes
- 1.0.1 (2020-08-20)
- Apply `RUSTFLAGS` for more `--target` scenarios, by @adamreichold.
- 1.0.0 (2020-01-08)
- 🎉 Release 1.0! 🎉 (no breaking changes)
- Add `probe_expression` and `emit_expression_cfg` to test arbitrary expressions.
- Add `probe_constant` and `emit_constant_cfg` to test arbitrary constant expressions.
- 0.1.7 (2019-10-20)
- Apply `RUSTFLAGS` when probing `$TARGET != $HOST`, mainly for sysroot, by @roblabla.
- 0.1.6 (2019-08-19)
- Add `probe`/`emit_sysroot_crate`, by @leo60228
- Add `probe`/`emit_sysroot_crate`, by @leo60228.
- 0.1.5 (2019-07-16)
- Mask some warnings from newer rustc.
@ -54,11 +65,11 @@ should only be used when the compiler supports it.
- Improve `rustc` bootstrap compatibility.
- 0.1.3 (2019-05-21)
- Auto-detects if `#![no_std]` is needed for the `$TARGET`
- Auto-detects if `#![no_std]` is needed for the `$TARGET`.
- 0.1.2 (2019-01-16)
- Add `rerun_env(ENV)` to print `cargo:rerun-if-env-changed=ENV`
- Add `rerun_path(PATH)` to print `cargo:rerun-if-changed=PATH`
- Add `rerun_env(ENV)` to print `cargo:rerun-if-env-changed=ENV`.
- Add `rerun_path(PATH)` to print `cargo:rerun-if-changed=PATH`.
## Minimum Rust version policy

116
third_party/rust/autocfg/src/lib.rs поставляемый
Просмотреть файл

@ -9,7 +9,7 @@
//!
//! ```toml
//! [build-dependencies]
//! autocfg = "0.1"
//! autocfg = "1"
//! ```
//!
//! Then use it in your `build.rs` script to detect compiler features. For
@ -25,7 +25,7 @@
//! ac.emit_has_type("i128");
//!
//! // (optional) We don't need to rerun for anything external.
//! autocfg::rerun_path(file!());
//! autocfg::rerun_path("build.rs");
//! }
//! ```
//!
@ -33,6 +33,14 @@
//! for Cargo, which translates to Rust arguments `--cfg has_i128`. Then in the
//! rest of your Rust code, you can add `#[cfg(has_i128)]` conditions on code that
//! should only be used when the compiler supports it.
//!
//! ## Caution
//!
//! Many of the probing methods of `AutoCfg` document the particular template they
//! use, **subject to change**. The inputs are not validated to make sure they are
//! semantically correct for their expected use, so it's _possible_ to escape and
//! inject something unintended. However, such abuse is unsupported and will not
//! be considered when making changes to the templates.
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
@ -41,6 +49,16 @@
#![allow(bare_trait_objects)]
#![allow(ellipsis_inclusive_range_patterns)]
/// Local macro to avoid `std::try!`, deprecated in Rust 1.39.
macro_rules! try {
($result:expr) => {
match $result {
Ok(value) => value,
Err(error) => return Err(error),
}
};
}
use std::env;
use std::ffi::OsString;
use std::fs;
@ -68,6 +86,7 @@ pub struct AutoCfg {
rustc_version: Version,
target: Option<OsString>,
no_std: bool,
rustflags: Option<Vec<String>>,
}
/// Writes a config flag for rustc on standard out.
@ -138,6 +157,8 @@ impl AutoCfg {
let rustc: PathBuf = rustc.into();
let rustc_version = try!(Version::from_rustc(&rustc));
let target = env::var_os("TARGET");
// Sanity check the output directory
let dir = dir.into();
let meta = try!(fs::metadata(&dir).map_err(error::from_io));
@ -145,12 +166,37 @@ impl AutoCfg {
return Err(error::from_str("output path is not a writable directory"));
}
// Cargo only applies RUSTFLAGS for building TARGET artifact in
// cross-compilation environment. Sadly, we don't have a way to detect
// when we're building HOST artifact in a cross-compilation environment,
// so for now we only apply RUSTFLAGS when cross-compiling an artifact.
//
// See https://github.com/cuviper/autocfg/pull/10#issuecomment-527575030.
let rustflags = if target != env::var_os("HOST")
|| dir_contains_target(&target, &dir, env::var_os("CARGO_TARGET_DIR"))
{
env::var("RUSTFLAGS").ok().map(|rustflags| {
// This is meant to match how cargo handles the RUSTFLAG environment
// variable.
// See https://github.com/rust-lang/cargo/blob/69aea5b6f69add7c51cca939a79644080c0b0ba0/src/cargo/core/compiler/build_context/target_info.rs#L434-L441
rustflags
.split(' ')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect::<Vec<String>>()
})
} else {
None
};
let mut ac = AutoCfg {
out_dir: dir,
rustc: rustc,
rustc_version: rustc_version,
target: env::var_os("TARGET"),
target: target,
no_std: false,
rustflags: rustflags,
};
// Sanity check with and without `std`.
@ -194,6 +240,10 @@ impl AutoCfg {
.arg(&self.out_dir)
.arg("--emit=llvm-ir");
if let &Some(ref rustflags) = &self.rustflags {
command.args(rustflags);
}
if let Some(target) = self.target.as_ref() {
command.arg("--target").arg(target);
}
@ -316,6 +366,44 @@ impl AutoCfg {
emit(cfg);
}
}
/// Tests whether the given expression can be used.
///
/// The test code is subject to change, but currently looks like:
///
/// ```ignore
/// pub fn probe() { let _ = EXPR; }
/// ```
pub fn probe_expression(&self, expr: &str) -> bool {
self.probe(format!("pub fn probe() {{ let _ = {}; }}", expr))
.unwrap_or(false)
}
/// Emits the given `cfg` value if `probe_expression` returns true.
pub fn emit_expression_cfg(&self, expr: &str, cfg: &str) {
if self.probe_expression(expr) {
emit(cfg);
}
}
/// Tests whether the given constant expression can be used.
///
/// The test code is subject to change, but currently looks like:
///
/// ```ignore
/// pub const PROBE: () = ((), EXPR).0;
/// ```
pub fn probe_constant(&self, expr: &str) -> bool {
self.probe(format!("pub const PROBE: () = ((), {}).0;", expr))
.unwrap_or(false)
}
/// Emits the given `cfg` value if `probe_constant` returns true.
pub fn emit_constant_cfg(&self, expr: &str, cfg: &str) {
if self.probe_constant(expr) {
emit(cfg);
}
}
}
fn mangle(s: &str) -> String {
@ -326,3 +414,25 @@ fn mangle(s: &str) -> String {
})
.collect()
}
fn dir_contains_target(
target: &Option<OsString>,
dir: &PathBuf,
cargo_target_dir: Option<OsString>,
) -> bool {
target
.as_ref()
.and_then(|target| {
dir.to_str().and_then(|dir| {
let mut cargo_target_dir = cargo_target_dir
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("target"));
cargo_target_dir.push(target);
cargo_target_dir
.to_str()
.map(|cargo_target_dir| dir.contains(&cargo_target_dir))
})
})
.unwrap_or(false)
}

122
third_party/rust/autocfg/src/tests.rs поставляемый
Просмотреть файл

@ -1,15 +1,31 @@
use super::AutoCfg;
use std::env;
impl AutoCfg {
fn core_std(&self, path: &str) -> String {
let krate = if self.no_std { "core" } else { "std" };
format!("{}::{}", krate, path)
}
fn assert_std(&self, probe_result: bool) {
assert_eq!(!self.no_std, probe_result);
}
fn assert_min(&self, major: usize, minor: usize, probe_result: bool) {
assert_eq!(self.probe_rustc_version(major, minor), probe_result);
}
fn for_test() -> Result<Self, super::error::Error> {
match env::var_os("TESTS_TARGET_DIR") {
Some(d) => Self::with_dir(d),
None => Self::with_dir("target"),
}
}
}
#[test]
fn autocfg_version() {
let ac = AutoCfg::with_dir("target").unwrap();
let ac = AutoCfg::for_test().unwrap();
println!("version: {:?}", ac.rustc_version);
assert!(ac.probe_rustc_version(1, 0));
}
@ -29,71 +45,125 @@ fn version_cmp() {
#[test]
fn probe_add() {
let ac = AutoCfg::with_dir("target").unwrap();
let ac = AutoCfg::for_test().unwrap();
let add = ac.core_std("ops::Add");
let add_rhs = ac.core_std("ops::Add<i32>");
let add_rhs_output = ac.core_std("ops::Add<i32, Output = i32>");
let add_rhs = add.clone() + "<i32>";
let add_rhs_output = add.clone() + "<i32, Output = i32>";
let dyn_add_rhs_output = "dyn ".to_string() + &*add_rhs_output;
assert!(ac.probe_path(&add));
assert!(ac.probe_trait(&add));
assert!(ac.probe_trait(&add_rhs));
assert!(ac.probe_trait(&add_rhs_output));
assert!(ac.probe_type(&add_rhs_output));
ac.assert_min(1, 27, ac.probe_type(&dyn_add_rhs_output));
}
#[test]
fn probe_as_ref() {
let ac = AutoCfg::with_dir("target").unwrap();
let ac = AutoCfg::for_test().unwrap();
let as_ref = ac.core_std("convert::AsRef");
let as_ref_str = ac.core_std("convert::AsRef<str>");
let as_ref_str = as_ref.clone() + "<str>";
let dyn_as_ref_str = "dyn ".to_string() + &*as_ref_str;
assert!(ac.probe_path(&as_ref));
assert!(ac.probe_trait(&as_ref_str));
assert!(ac.probe_type(&as_ref_str));
ac.assert_min(1, 27, ac.probe_type(&dyn_as_ref_str));
}
#[test]
fn probe_i128() {
let ac = AutoCfg::with_dir("target").unwrap();
let missing = !ac.probe_rustc_version(1, 26);
let ac = AutoCfg::for_test().unwrap();
let i128_path = ac.core_std("i128");
assert!(missing ^ ac.probe_path(&i128_path));
assert!(missing ^ ac.probe_type("i128"));
ac.assert_min(1, 26, ac.probe_path(&i128_path));
ac.assert_min(1, 26, ac.probe_type("i128"));
}
#[test]
fn probe_sum() {
let ac = AutoCfg::with_dir("target").unwrap();
let missing = !ac.probe_rustc_version(1, 12);
let ac = AutoCfg::for_test().unwrap();
let sum = ac.core_std("iter::Sum");
let sum_i32 = ac.core_std("iter::Sum<i32>");
assert!(missing ^ ac.probe_path(&sum));
assert!(missing ^ ac.probe_trait(&sum));
assert!(missing ^ ac.probe_trait(&sum_i32));
assert!(missing ^ ac.probe_type(&sum_i32));
let sum_i32 = sum.clone() + "<i32>";
let dyn_sum_i32 = "dyn ".to_string() + &*sum_i32;
ac.assert_min(1, 12, ac.probe_path(&sum));
ac.assert_min(1, 12, ac.probe_trait(&sum));
ac.assert_min(1, 12, ac.probe_trait(&sum_i32));
ac.assert_min(1, 12, ac.probe_type(&sum_i32));
ac.assert_min(1, 27, ac.probe_type(&dyn_sum_i32));
}
#[test]
fn probe_std() {
let ac = AutoCfg::with_dir("target").unwrap();
assert_eq!(ac.probe_sysroot_crate("std"), !ac.no_std);
let ac = AutoCfg::for_test().unwrap();
ac.assert_std(ac.probe_sysroot_crate("std"));
}
#[test]
fn probe_alloc() {
let ac = AutoCfg::with_dir("target").unwrap();
let missing = !ac.probe_rustc_version(1, 36);
assert!(missing ^ ac.probe_sysroot_crate("alloc"));
let ac = AutoCfg::for_test().unwrap();
ac.assert_min(1, 36, ac.probe_sysroot_crate("alloc"));
}
#[test]
fn probe_bad_sysroot_crate() {
let ac = AutoCfg::with_dir("target").unwrap();
let ac = AutoCfg::for_test().unwrap();
assert!(!ac.probe_sysroot_crate("doesnt_exist"));
}
#[test]
fn probe_no_std() {
let ac = AutoCfg::with_dir("target").unwrap();
let ac = AutoCfg::for_test().unwrap();
assert!(ac.probe_type("i32"));
assert!(ac.probe_type("[i32]"));
assert_eq!(ac.probe_type("Vec<i32>"), !ac.no_std);
ac.assert_std(ac.probe_type("Vec<i32>"));
}
#[test]
fn probe_expression() {
let ac = AutoCfg::for_test().unwrap();
assert!(ac.probe_expression(r#""test".trim_left()"#));
ac.assert_min(1, 30, ac.probe_expression(r#""test".trim_start()"#));
ac.assert_std(ac.probe_expression("[1, 2, 3].to_vec()"));
}
#[test]
fn probe_constant() {
let ac = AutoCfg::for_test().unwrap();
assert!(ac.probe_constant("1 + 2 + 3"));
ac.assert_min(1, 33, ac.probe_constant("{ let x = 1 + 2 + 3; x * x }"));
ac.assert_min(1, 39, ac.probe_constant(r#""test".len()"#));
}
#[test]
fn dir_does_not_contain_target() {
assert!(!super::dir_contains_target(
&Some("x86_64-unknown-linux-gnu".into()),
&"/project/target/debug/build/project-ea75983148559682/out".into(),
None,
));
}
#[test]
fn dir_does_contain_target() {
assert!(super::dir_contains_target(
&Some("x86_64-unknown-linux-gnu".into()),
&"/project/target/x86_64-unknown-linux-gnu/debug/build/project-0147aca016480b9d/out".into(),
None,
));
}
#[test]
fn dir_does_not_contain_target_with_custom_target_dir() {
assert!(!super::dir_contains_target(
&Some("x86_64-unknown-linux-gnu".into()),
&"/project/custom/debug/build/project-ea75983148559682/out".into(),
Some("custom".into()),
));
}
#[test]
fn dir_does_contain_target_with_custom_target_dir() {
assert!(super::dir_contains_target(
&Some("x86_64-unknown-linux-gnu".into()),
&"/project/custom/x86_64-unknown-linux-gnu/debug/build/project-0147aca016480b9d/out".into(),
Some("custom".into()),
));
}

19
third_party/rust/autocfg/tests/rustflags.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,19 @@
extern crate autocfg;
use std::env;
/// Tests that autocfg uses the RUSTFLAGS environment variable when running
/// rustc.
#[test]
fn test_with_sysroot() {
// Use the same path as this test binary.
let dir = env::current_exe().unwrap().parent().unwrap().to_path_buf();
env::set_var("RUSTFLAGS", &format!("-L {}", dir.display()));
env::set_var("OUT_DIR", &format!("{}", dir.display()));
// Ensure HOST != TARGET.
env::set_var("HOST", "lol");
let ac = autocfg::AutoCfg::new().unwrap();
assert!(ac.probe_sysroot_crate("autocfg"));
}

Просмотреть файл

@ -1 +1 @@
{"files":{"Cargo.toml":"eeb5f5f88978e950820356ca434718da8ed9b40bf2745b03a400ac5a8b9fa57d","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"ecc269ef87fd38a1d98e30bfac9ba964a9dbd9315c3770fed98d4d7cb5882055","README.rst":"cdcaa79d0e2a2d4980604827b6b043a464a9949fa2bfd033f65a5d6ea4a844de","benches/bench.rs":"e34466bc3c56d3f0bb2ccf37a0588dbec51bb1048729f3b5f2ef41e36900460f","benches/faststring.rs":"c490c03dc5f3d686fcb17c92d4dd79428ca9eff78f9a2c1cab60f83c48140827","src/equivalent.rs":"4d07c0ae8c8ff405fdbb45e6c891158d3fdcfedd47001e4cec090c79b5c56564","src/lib.rs":"31cde3e6244107cea11be6584dd803eaa441fb9fb762f410c85975e5a286a071","src/macros.rs":"472c9ec707495e6de60b4e67c1b25f2201bb962fa6672fae32addde2eb4df376","src/map.rs":"7530ca07f39ba3d7101c129c729af58457fa0e7f41e9ae6ed662c070d2a058a3","src/mutable_keys.rs":"2bf26fb36ad0ccd3c40b0f2cc4e5b8429e6627207f50fca07110a5011880a9dc","src/rayon/map.rs":"9fc361acad0c65bdee35b826915fc595708728382fa8995254a2adf6277d5979","src/rayon/mod.rs":"d0657d28aaf5f5df8b6904ed4da6987565d98f92f686f30fb0b0af2eac94fdac","src/rayon/set.rs":"cea5e1724bc8449b0bbacbb18c5ae60a2d41cfc5cfd496e89e1c17f77c6e7a49","src/serde.rs":"96850a3adc93ad890573de596cfe1edd70a71e0ad1a0d55963c40f12f49e63d0","src/set.rs":"311b415b5e310f32036075d03b3e9bf7783cb86e9b0747be19dc02e292953326","src/util.rs":"331f80b48387878caa01ab9cfd43927ea0c15129c6beb755d6b40abc6ada900f","tests/equivalent_trait.rs":"f48ef255e4bc6bc85ed11fd9bee4cc53759efb182e448d315f8d12af1f80b05d","tests/quick.rs":"025e9e4355c4ce76daf0366d5bde2e32bf90fe2d27831a7b7617a6d0e5974529","tests/serde.rs":"48f2a2184c819ffaa5c234ccea9c3bea1c58edf8ad9ada1476eedc179438d07d","tests/tests.rs":"c916ae9c5d08c042b7c3a0447ef3db5a1b9d37b3122fddace4235296a623725b"},"package":"a4d6d89e0948bf10c08b9ecc8ac5b83f07f857ebe2c0cbe38de15b4e4f510356"}
{"files":{"Cargo.toml":"b2e03e7a524d10bb253021375ccc06a3d2a060d2c7c045a1a60d8bb3739b46a9","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"ecc269ef87fd38a1d98e30bfac9ba964a9dbd9315c3770fed98d4d7cb5882055","README.rst":"6751ed067142c9445ffb9c201457a40bb73af76aa3c7e525fb415508abec74b1","benches/bench.rs":"dda3c7e3cd68b8f5c74dbd60189e89f0e43339cdc25dae7b1e5a9d25b1fb80a9","benches/faststring.rs":"2472b9d0d52031988cd31401357908fd850d15f1efa9f9761aa6b6779aad1889","build.rs":"558b4d0b9e9b3a44f7e1a2b69f7a7567ea721cd45cb54f4e458e850bf702f35c","src/equivalent.rs":"2e6ae24ef09a09b917f4e2b0f6288f901878e42f5080f61b1bd1afdcc90aba87","src/lib.rs":"4c4fa0d4882387d2c1681fa29a333354230de157101783bea2af6af04951d973","src/macros.rs":"cb2e9742b7e2bcadc4eb356a4ca4eb3317d1a80e293f37a3cd5a0155c5347c50","src/map.rs":"21c0c04acfb25d526da41b447b2e572d14e52778b84910514869d1cd2dce267c","src/map/core.rs":"9d9df231fbc02e3539429451c6f8cfd142c97d6e47b0c1f58672f75e3806d578","src/map/core/raw.rs":"9842320404357ec15e536240a9ab32d969e61f31508d3c485c0c76077618ef63","src/mutable_keys.rs":"99fdec7c0182902ba19524f342c220b51475bcd41c44c2cb2c3f62eacb029335","src/rayon/map.rs":"cdbe6cad8e5753aca3f07b621d2bb3b480f1ae3e10697568b8c16aeb865de65b","src/rayon/mod.rs":"bf2b0fc074f20135a6734db600b04828e88dd263b3e361606be4efe8e916eafc","src/rayon/set.rs":"789efd10d41f03fa73268bae8afdc3b6582767420218a4b28f3c83c528ef726c","src/serde.rs":"2f7ce29e63e92ddbe14d3ad0b7e83bdc9662b226565ec0aa707d5cd92cb1e263","src/set.rs":"a88c5e902e8c67d014c7c1680a7e4b9156af67d2ac58e7dcf96698b742abc88b","src/util.rs":"c415261cff9f610d7331192feba0839cb05e04d3d375a5fa2f8190a29661994e","tests/equivalent_trait.rs":"efe9393069e3cfc893d2c9c0343679979578e437fdb98a10baefeced027ba310","tests/macros_full_path.rs":"c33c86d7341581fdd08e2e6375a4afca507fa603540c54a3b9e51c4cd011cd71","tests/quick.rs":"6efe8c6dfa5bdd466b3f5c491d9dfbf57fd730301849a710abff9358968218c5","tests/tests.rs":"f6dbeeb0e2950402b0e66ac52bf74c9e4197d3c5d9c0dde64a7998a2ef74d327"},"package":"55e2e4c765aa53a0424761bf9f41aa7a6ac1efa87238f59560640e27fca028f2"}

31
third_party/rust/indexmap/Cargo.toml поставляемый
Просмотреть файл

@ -11,13 +11,15 @@
# will likely look very different (and much more reasonable)
[package]
edition = "2018"
name = "indexmap"
version = "1.1.0"
version = "1.6.0"
authors = ["bluss", "Josh Stone <cuviper@gmail.com>"]
build = "build.rs"
description = "A hash table with consistent order and fast iteration.\n\nThe indexmap is a hash table where the iteration order of the key-value\npairs is independent of the hash values of the keys. It has the usual\nhash table functionality, it preserves insertion order except after\nremovals, and it allows lookup of its elements by either hash table key\nor numerical index. A corresponding hash set type is also provided.\n\nThis crate was initially published under the name ordermap, but it was renamed to\nindexmap.\n"
documentation = "https://docs.rs/indexmap/"
keywords = ["hashmap"]
categories = ["data-structures"]
keywords = ["hashmap", "no_std"]
categories = ["data-structures", "no-std"]
license = "Apache-2.0/MIT"
repository = "https://github.com/bluss/indexmap"
[package.metadata.docs.rs]
@ -25,11 +27,17 @@ features = ["serde-1", "rayon"]
[package.metadata.release]
no-dev-version = true
tag-name = "{{version}}"
[profile.bench]
debug = true
[lib]
bench = false
[dependencies.hashbrown]
version = "0.9.0"
features = ["raw"]
default-features = false
[dependencies.rayon]
version = "1.0"
optional = true
@ -37,26 +45,31 @@ optional = true
[dependencies.serde]
version = "1.0"
optional = true
default-features = false
[dev-dependencies.fnv]
version = "1.0"
[dev-dependencies.fxhash]
version = "0.2.1"
[dev-dependencies.itertools]
version = "0.8"
version = "0.9"
[dev-dependencies.lazy_static]
version = "1.3"
[dev-dependencies.quickcheck]
version = "0.8"
version = "0.9"
default-features = false
[dev-dependencies.rand]
version = "0.6"
[dev-dependencies.serde_test]
version = "1.0.99"
version = "0.7"
features = ["small_rng"]
[build-dependencies.autocfg]
version = "1"
[features]
serde-1 = ["serde"]
std = []
test_debug = []
test_low_transition_point = []

158
third_party/rust/indexmap/README.rst поставляемый
Просмотреть файл

@ -12,10 +12,10 @@ indexmap
.. |docs| image:: https://docs.rs/indexmap/badge.svg
.. _docs: https://docs.rs/indexmap
.. |rustc| image:: https://img.shields.io/badge/rust-1.18%2B-orange.svg
.. _rustc: https://img.shields.io/badge/rust-1.18%2B-orange.svg
.. |rustc| image:: https://img.shields.io/badge/rust-1.32%2B-orange.svg
.. _rustc: https://img.shields.io/badge/rust-1.32%2B-orange.svg
A safe, pure-Rust hash table which preserves insertion order.
A pure-Rust hash table which preserves (in a limited sense) insertion order.
This crate implements compact map and set data-structures,
where the iteration order of the keys is independent from their hash or
@ -38,16 +38,7 @@ was indexmap, a hash table that has following properties:
- Fast to iterate.
- Indexed in compact space.
- Preserves insertion order **as long** as you don't call ``.remove()``.
- Uses robin hood hashing just like Rust's libstd ``HashMap`` used to do
(before std switched to hashbrown).
- It's the usual backwards shift deletion, but only on the index vector, so
it's cheaper because it's moving less memory around.
Does not implement (Yet)
------------------------
- ``.reserve()`` exists but does not have a complete implementation
- Uses hashbrown for the inner table, just like Rust's libstd ``HashMap`` does.
Performance
-----------
@ -55,15 +46,14 @@ Performance
``IndexMap`` derives a couple of performance facts directly from how it is constructed,
which is roughly:
Two vectors, the first, sparse, with hashes and key-value indices, and the
second, dense, the key-value pairs.
A raw hash table of key-value indices, and a vector of key-value pairs.
- Iteration is very fast since it is on the dense key-values.
- Removal is fast since it moves memory areas only in the first vector,
and uses a single swap in the second vector.
- Lookup is fast-ish because the hashes and indices are densely stored.
Lookup also is slow-ish since hashes and key-value pairs are stored in
separate places. (Visible when cpu caches size is limiting.)
- Removal is fast since it moves memory areas only in the table,
and uses a single swap in the vector.
- Lookup is fast-ish because the initial 7-bit hash lookup uses SIMD, and indices are
densely stored. Lookup also is slow-ish since the actual key-value pairs are stored
separately. (Visible when cpu caches size is limiting.)
- In practice, ``IndexMap`` has been tested out as the hashmap in rustc in PR45282_ and
the performance was roughly on par across the whole workload.
@ -72,43 +62,105 @@ which is roughly:
.. _PR45282: https://github.com/rust-lang/rust/pull/45282
Interesting Features
--------------------
- Insertion order is preserved (``.swap_remove()`` perturbs the order, like the method name says).
- Implements ``.pop() -> Option<(K, V)>`` in O(1) time.
- ``IndexMap::new()`` is empty and uses no allocation until you insert something.
- Lookup key-value pairs by index and vice versa.
- No ``unsafe``.
- Supports ``IndexMut``.
Where to go from here?
----------------------
- Ideas and PRs for how to implement insertion-order preserving remove (for example tombstones)
are welcome. The plan is to split the crate into two hash table implementations
a) the current compact index space version and b) the full insertion order version.
Ideas that we already did
-------------------------
- It can be an *indexable* ordered map in the current fashion
(This was implemented in 0.2.0, for potential use as a graph datastructure).
- Idea for more cache efficient lookup (This was implemented in 0.1.2).
Current ``indices: Vec<Pos>``. ``Pos`` is interpreted as ``(u32, u32)`` more
or less when ``.raw_capacity()`` fits in 32 bits. ``Pos`` then stores both the lower
half of the hash and the entry index.
This means that the hash values in ``Bucket`` don't need to be accessed
while scanning for an entry.
Recent Changes
==============
- 1.6.0
- **MSRV**: Rust 1.36 or later is now required.
- The ``hashbrown`` dependency has been updated to version 0.9.
- 1.5.2
- The new "std" feature will force the use of ``std`` for users that explicitly
want the default ``S = RandomState``, bypassing the autodetection added in 1.3.0,
by @cuviper in PR 145_.
.. _145: https://github.com/bluss/indexmap/pull/145
- 1.5.1
- Values can now be indexed by their ``usize`` position by @cuviper in PR 132_.
- Some of the generic bounds have been relaxed to match ``std`` by @cuviper in PR 141_.
- ``drain`` now accepts any ``R: RangeBounds<usize>`` by @cuviper in PR 142_.
.. _132: https://github.com/bluss/indexmap/pull/132
.. _141: https://github.com/bluss/indexmap/pull/141
.. _142: https://github.com/bluss/indexmap/pull/142
- 1.5.0
- **MSRV**: Rust 1.32 or later is now required.
- The inner hash table is now based on ``hashbrown`` by @cuviper in PR 131_.
This also completes the method ``reserve`` and adds ``shrink_to_fit``.
- Add new methods ``get_key_value``, ``remove_entry``, ``swap_remove_entry``,
and ``shift_remove_entry``, by @cuviper in PR 136_
- ``Clone::clone_from`` reuses allocations by @cuviper in PR 125_
- Add new method ``reverse`` by @linclelinkpart5 in PR 128_
.. _125: https://github.com/bluss/indexmap/pull/125
.. _128: https://github.com/bluss/indexmap/pull/128
.. _131: https://github.com/bluss/indexmap/pull/131
.. _136: https://github.com/bluss/indexmap/pull/136
- 1.4.0
- Add new method ``get_index_of`` by @Thermatrix in PR 115_ and 120_
- Fix build script rebuild-if-changed configuration to use "build.rs";
fixes issue 123_. Fix by @cuviper.
- Dev-dependencies (rand and quickcheck) have been updated. The crate's tests
now run using Rust 1.32 or later (MSRV for building the crate has not changed).
by @kjeremy and @bluss
.. _123: https://github.com/bluss/indexmap/issues/123
.. _115: https://github.com/bluss/indexmap/pull/115
.. _120: https://github.com/bluss/indexmap/pull/120
- 1.3.2
- Maintenance update to regenerate the published `Cargo.toml`.
- 1.3.1
- Maintenance update for formatting and ``autocfg`` 1.0.
- 1.3.0
- The deprecation messages in the previous version have been removed.
(The methods have not otherwise changed.) Docs for removal methods have been
improved.
- From Rust 1.36, this crate supports being built **without std**, requiring
``alloc`` instead. This is enabled automatically when it is detected that
``std`` is not available. There is no crate feature to enable/disable to
trigger this. The new build-dep ``autocfg`` enables this.
- 1.2.0
- Plain ``.remove()`` now has a deprecation message, it informs the user
about picking one of the removal functions ``swap_remove`` and ``shift_remove``
which have different performance and order semantics.
Plain ``.remove()`` will not be removed, the warning message and method
will remain until further.
- Add new method ``shift_remove`` for order preserving removal on the map,
and ``shift_take`` for the corresponding operation on the set.
- Add methods ``swap_remove``, ``swap_remove_entry`` to ``Entry``.
- Fix indexset/indexmap to support full paths, like ``indexmap::indexmap!()``
- Internal improvements: fix warnings, deprecations and style lints
- 1.1.0
- Added optional feature `"rayon"` that adds parallel iterator support

220
third_party/rust/indexmap/benches/bench.rs поставляемый
Просмотреть файл

@ -1,19 +1,16 @@
#![feature(test)]
extern crate test;
extern crate rand;
extern crate fnv;
#[macro_use]
extern crate lazy_static;
use std::hash::Hash;
use fnv::FnvHasher;
use std::hash::BuildHasherDefault;
use std::hash::Hash;
type FnvBuilder = BuildHasherDefault<FnvHasher>;
use test::Bencher;
use test::black_box;
extern crate indexmap;
use test::Bencher;
use indexmap::IndexMap;
@ -21,35 +18,33 @@ use std::collections::HashMap;
use std::iter::FromIterator;
use rand::rngs::SmallRng;
use rand::FromEntropy;
use rand::seq::SliceRandom;
use rand::SeedableRng;
#[bench]
fn new_hashmap(b: &mut Bencher) {
b.iter(|| {
HashMap::<String, String>::new()
});
/// Use a consistently seeded Rng for benchmark stability
fn small_rng() -> SmallRng {
let seed = u64::from_le_bytes(*b"indexmap");
SmallRng::seed_from_u64(seed)
}
#[bench]
fn new_orderedmap(b: &mut Bencher) {
b.iter(|| {
IndexMap::<String, String>::new()
});
fn new_hashmap(b: &mut Bencher) {
b.iter(|| HashMap::<String, String>::new());
}
#[bench]
fn new_indexmap(b: &mut Bencher) {
b.iter(|| IndexMap::<String, String>::new());
}
#[bench]
fn with_capacity_10e5_hashmap(b: &mut Bencher) {
b.iter(|| {
HashMap::<String, String>::with_capacity(10_000)
});
b.iter(|| HashMap::<String, String>::with_capacity(10_000));
}
#[bench]
fn with_capacity_10e5_orderedmap(b: &mut Bencher) {
b.iter(|| {
IndexMap::<String, String>::with_capacity(10_000)
});
fn with_capacity_10e5_indexmap(b: &mut Bencher) {
b.iter(|| IndexMap::<String, String>::with_capacity(10_000));
}
#[bench]
@ -65,7 +60,7 @@ fn insert_hashmap_10_000(b: &mut Bencher) {
}
#[bench]
fn insert_orderedmap_10_000(b: &mut Bencher) {
fn insert_indexmap_10_000(b: &mut Bencher) {
let c = 10_000;
b.iter(|| {
let mut map = IndexMap::with_capacity(c);
@ -89,7 +84,7 @@ fn insert_hashmap_string_10_000(b: &mut Bencher) {
}
#[bench]
fn insert_orderedmap_string_10_000(b: &mut Bencher) {
fn insert_indexmap_string_10_000(b: &mut Bencher) {
let c = 10_000;
b.iter(|| {
let mut map = IndexMap::with_capacity(c);
@ -114,7 +109,7 @@ fn insert_hashmap_str_10_000(b: &mut Bencher) {
}
#[bench]
fn insert_orderedmap_str_10_000(b: &mut Bencher) {
fn insert_indexmap_str_10_000(b: &mut Bencher) {
let c = 10_000;
let ss = Vec::from_iter((0..c).map(|x| x.to_string()));
b.iter(|| {
@ -140,7 +135,7 @@ fn insert_hashmap_int_bigvalue_10_000(b: &mut Bencher) {
}
#[bench]
fn insert_orderedmap_int_bigvalue_10_000(b: &mut Bencher) {
fn insert_indexmap_int_bigvalue_10_000(b: &mut Bencher) {
let c = 10_000;
let value = [0u64; 10];
b.iter(|| {
@ -165,7 +160,7 @@ fn insert_hashmap_100_000(b: &mut Bencher) {
}
#[bench]
fn insert_orderedmap_100_000(b: &mut Bencher) {
fn insert_indexmap_100_000(b: &mut Bencher) {
let c = 100_000;
b.iter(|| {
let mut map = IndexMap::with_capacity(c);
@ -189,7 +184,7 @@ fn insert_hashmap_150(b: &mut Bencher) {
}
#[bench]
fn insert_orderedmap_150(b: &mut Bencher) {
fn insert_indexmap_150(b: &mut Bencher) {
let c = 150;
b.iter(|| {
let mut map = IndexMap::with_capacity(c);
@ -213,7 +208,7 @@ fn entry_hashmap_150(b: &mut Bencher) {
}
#[bench]
fn entry_orderedmap_150(b: &mut Bencher) {
fn entry_indexmap_150(b: &mut Bencher) {
let c = 150;
b.iter(|| {
let mut map = IndexMap::with_capacity(c);
@ -228,35 +223,31 @@ fn entry_orderedmap_150(b: &mut Bencher) {
fn iter_sum_hashmap_10_000(b: &mut Bencher) {
let c = 10_000;
let mut map = HashMap::with_capacity(c);
let len = c - c/10;
let len = c - c / 10;
for x in 0..len {
map.insert(x, ());
}
assert_eq!(map.len(), len);
b.iter(|| {
map.keys().sum::<usize>()
});
b.iter(|| map.keys().sum::<usize>());
}
#[bench]
fn iter_sum_orderedmap_10_000(b: &mut Bencher) {
fn iter_sum_indexmap_10_000(b: &mut Bencher) {
let c = 10_000;
let mut map = IndexMap::with_capacity(c);
let len = c - c/10;
let len = c - c / 10;
for x in 0..len {
map.insert(x, ());
}
assert_eq!(map.len(), len);
b.iter(|| {
map.keys().sum::<usize>()
});
b.iter(|| map.keys().sum::<usize>());
}
#[bench]
fn iter_black_box_hashmap_10_000(b: &mut Bencher) {
let c = 10_000;
let mut map = HashMap::with_capacity(c);
let len = c - c/10;
let len = c - c / 10;
for x in 0..len {
map.insert(x, ());
}
@ -269,10 +260,10 @@ fn iter_black_box_hashmap_10_000(b: &mut Bencher) {
}
#[bench]
fn iter_black_box_orderedmap_10_000(b: &mut Bencher) {
fn iter_black_box_indexmap_10_000(b: &mut Bencher) {
let c = 10_000;
let mut map = IndexMap::with_capacity(c);
let len = c - c/10;
let len = c - c / 10;
for x in 0..len {
map.insert(x, ());
}
@ -285,10 +276,11 @@ fn iter_black_box_orderedmap_10_000(b: &mut Bencher) {
}
fn shuffled_keys<I>(iter: I) -> Vec<I::Item>
where I: IntoIterator
where
I: IntoIterator,
{
let mut v = Vec::from_iter(iter);
let mut rng = SmallRng::from_entropy();
let mut rng = small_rng();
v.shuffle(&mut rng);
v
}
@ -328,7 +320,7 @@ fn lookup_hashmap_10_000_noexist(b: &mut Bencher) {
}
#[bench]
fn lookup_orderedmap_10_000_exist(b: &mut Bencher) {
fn lookup_indexmap_10_000_exist(b: &mut Bencher) {
let c = 10_000;
let mut map = IndexMap::with_capacity(c);
let keys = shuffled_keys(0..c);
@ -345,7 +337,7 @@ fn lookup_orderedmap_10_000_exist(b: &mut Bencher) {
}
#[bench]
fn lookup_orderedmap_10_000_noexist(b: &mut Bencher) {
fn lookup_indexmap_10_000_noexist(b: &mut Bencher) {
let c = 10_000;
let mut map = IndexMap::with_capacity(c);
let keys = shuffled_keys(0..c);
@ -366,12 +358,9 @@ const LOOKUP_MAP_SIZE: u32 = 100_000_u32;
const LOOKUP_SAMPLE_SIZE: u32 = 5000;
const SORT_MAP_SIZE: usize = 10_000;
// use lazy_static so that comparison benchmarks use the exact same inputs
lazy_static! {
static ref KEYS: Vec<u32> = {
shuffled_keys(0..LOOKUP_MAP_SIZE)
};
static ref KEYS: Vec<u32> = shuffled_keys(0..LOOKUP_MAP_SIZE);
}
lazy_static! {
@ -387,7 +376,7 @@ lazy_static! {
}
lazy_static! {
static ref OMAP_100K: IndexMap<u32, u32> = {
static ref IMAP_100K: IndexMap<u32, u32> = {
let c = LOOKUP_MAP_SIZE;
let mut map = IndexMap::with_capacity(c as usize);
let keys = &*KEYS;
@ -399,7 +388,7 @@ lazy_static! {
}
lazy_static! {
static ref OMAP_SORT_U32: IndexMap<u32, u32> = {
static ref IMAP_SORT_U32: IndexMap<u32, u32> = {
let mut map = IndexMap::with_capacity(SORT_MAP_SIZE);
for &key in &KEYS[..SORT_MAP_SIZE] {
map.insert(key, key);
@ -408,7 +397,7 @@ lazy_static! {
};
}
lazy_static! {
static ref OMAP_SORT_S: IndexMap<String, String> = {
static ref IMAP_SORT_S: IndexMap<String, String> = {
let mut map = IndexMap::with_capacity(SORT_MAP_SIZE);
for &key in &KEYS[..SORT_MAP_SIZE] {
map.insert(format!("{:^16x}", &key), String::new());
@ -429,10 +418,9 @@ fn lookup_hashmap_100_000_multi(b: &mut Bencher) {
});
}
#[bench]
fn lookup_ordermap_100_000_multi(b: &mut Bencher) {
let map = &*OMAP_100K;
fn lookup_indexmap_100_000_multi(b: &mut Bencher) {
let map = &*IMAP_100K;
b.iter(|| {
let mut found = 0;
for key in 0..LOOKUP_SAMPLE_SIZE {
@ -456,10 +444,9 @@ fn lookup_hashmap_100_000_inorder_multi(b: &mut Bencher) {
});
}
#[bench]
fn lookup_ordermap_100_000_inorder_multi(b: &mut Bencher) {
let map = &*OMAP_100K;
fn lookup_indexmap_100_000_inorder_multi(b: &mut Bencher) {
let map = &*IMAP_100K;
let keys = &*KEYS;
b.iter(|| {
let mut found = 0;
@ -480,10 +467,9 @@ fn lookup_hashmap_100_000_single(b: &mut Bencher) {
});
}
#[bench]
fn lookup_ordermap_100_000_single(b: &mut Bencher) {
let map = &*OMAP_100K;
fn lookup_indexmap_100_000_single(b: &mut Bencher) {
let map = &*IMAP_100K;
let mut iter = (0..LOOKUP_MAP_SIZE + LOOKUP_SAMPLE_SIZE).cycle();
b.iter(|| {
let key = iter.next().unwrap();
@ -507,7 +493,7 @@ fn grow_fnv_hashmap_100_000(b: &mut Bencher) {
}
#[bench]
fn grow_fnv_ordermap_100_000(b: &mut Bencher) {
fn grow_fnv_indexmap_100_000(b: &mut Bencher) {
b.iter(|| {
let mut map: IndexMap<_, _, FnvBuilder> = IndexMap::default();
for x in 0..GROW_SIZE {
@ -517,7 +503,6 @@ fn grow_fnv_ordermap_100_000(b: &mut Bencher) {
});
}
const MERGE: u64 = 10_000;
#[bench]
fn hashmap_merge_simple(b: &mut Bencher) {
@ -535,7 +520,7 @@ fn hashmap_merge_shuffle(b: &mut Bencher) {
let first_map: HashMap<u64, _> = (0..MERGE).map(|i| (i, ())).collect();
let second_map: HashMap<u64, _> = (MERGE..MERGE * 2).map(|i| (i, ())).collect();
let mut v = Vec::new();
let mut rng = SmallRng::from_entropy();
let mut rng = small_rng();
b.iter(|| {
let mut merged = first_map.clone();
v.extend(second_map.iter().map(|(&k, &v)| (k, v)));
@ -547,7 +532,7 @@ fn hashmap_merge_shuffle(b: &mut Bencher) {
}
#[bench]
fn ordermap_merge_simple(b: &mut Bencher) {
fn indexmap_merge_simple(b: &mut Bencher) {
let first_map: IndexMap<u64, _> = (0..MERGE).map(|i| (i, ())).collect();
let second_map: IndexMap<u64, _> = (MERGE..MERGE * 2).map(|i| (i, ())).collect();
b.iter(|| {
@ -558,11 +543,11 @@ fn ordermap_merge_simple(b: &mut Bencher) {
}
#[bench]
fn ordermap_merge_shuffle(b: &mut Bencher) {
fn indexmap_merge_shuffle(b: &mut Bencher) {
let first_map: IndexMap<u64, _> = (0..MERGE).map(|i| (i, ())).collect();
let second_map: IndexMap<u64, _> = (MERGE..MERGE * 2).map(|i| (i, ())).collect();
let mut v = Vec::new();
let mut rng = SmallRng::from_entropy();
let mut rng = small_rng();
b.iter(|| {
let mut merged = first_map.clone();
v.extend(second_map.iter().map(|(&k, &v)| (k, v)));
@ -574,16 +559,16 @@ fn ordermap_merge_shuffle(b: &mut Bencher) {
}
#[bench]
fn remove_ordermap_100_000(b: &mut Bencher) {
let map = OMAP_100K.clone();
fn swap_remove_indexmap_100_000(b: &mut Bencher) {
let map = IMAP_100K.clone();
let mut keys = Vec::from_iter(map.keys().cloned());
let mut rng = SmallRng::from_entropy();
let mut rng = small_rng();
keys.shuffle(&mut rng);
b.iter(|| {
let mut map = map.clone();
for key in &keys {
map.remove(key);
map.swap_remove(key);
}
assert_eq!(map.len(), 0);
map
@ -591,12 +576,50 @@ fn remove_ordermap_100_000(b: &mut Bencher) {
}
#[bench]
fn pop_ordermap_100_000(b: &mut Bencher) {
let map = OMAP_100K.clone();
fn shift_remove_indexmap_100_000_few(b: &mut Bencher) {
let map = IMAP_100K.clone();
let mut keys = Vec::from_iter(map.keys().cloned());
let mut rng = small_rng();
keys.shuffle(&mut rng);
keys.truncate(50);
b.iter(|| {
let mut map = map.clone();
while map.len() > 0 {
for key in &keys {
map.shift_remove(key);
}
assert_eq!(map.len(), IMAP_100K.len() - keys.len());
map
});
}
#[bench]
fn shift_remove_indexmap_2_000_full(b: &mut Bencher) {
let mut keys = KEYS[..2_000].to_vec();
let mut map = IndexMap::with_capacity(keys.len());
for &key in &keys {
map.insert(key, key);
}
let mut rng = small_rng();
keys.shuffle(&mut rng);
b.iter(|| {
let mut map = map.clone();
for key in &keys {
map.shift_remove(key);
}
assert_eq!(map.len(), 0);
map
});
}
#[bench]
fn pop_indexmap_100_000(b: &mut Bencher) {
let map = IMAP_100K.clone();
b.iter(|| {
let mut map = map.clone();
while !map.is_empty() {
map.pop();
}
assert_eq!(map.len(), 0);
@ -605,8 +628,8 @@ fn pop_ordermap_100_000(b: &mut Bencher) {
}
#[bench]
fn few_retain_ordermap_100_000(b: &mut Bencher) {
let map = OMAP_100K.clone();
fn few_retain_indexmap_100_000(b: &mut Bencher) {
let map = IMAP_100K.clone();
b.iter(|| {
let mut map = map.clone();
@ -627,8 +650,8 @@ fn few_retain_hashmap_100_000(b: &mut Bencher) {
}
#[bench]
fn half_retain_ordermap_100_000(b: &mut Bencher) {
let map = OMAP_100K.clone();
fn half_retain_indexmap_100_000(b: &mut Bencher) {
let map = IMAP_100K.clone();
b.iter(|| {
let mut map = map.clone();
@ -649,8 +672,8 @@ fn half_retain_hashmap_100_000(b: &mut Bencher) {
}
#[bench]
fn many_retain_ordermap_100_000(b: &mut Bencher) {
let map = OMAP_100K.clone();
fn many_retain_indexmap_100_000(b: &mut Bencher) {
let map = IMAP_100K.clone();
b.iter(|| {
let mut map = map.clone();
@ -670,7 +693,6 @@ fn many_retain_hashmap_100_000(b: &mut Bencher) {
});
}
// simple sort impl for comparison
pub fn simple_sort<K: Ord + Hash, V>(m: &mut IndexMap<K, V>) {
let mut ordered: Vec<_> = m.drain(..).collect();
@ -678,10 +700,9 @@ pub fn simple_sort<K: Ord + Hash, V>(m: &mut IndexMap<K, V>) {
m.extend(ordered);
}
#[bench]
fn ordermap_sort_s(b: &mut Bencher) {
let map = OMAP_SORT_S.clone();
fn indexmap_sort_s(b: &mut Bencher) {
let map = IMAP_SORT_S.clone();
// there's a map clone there, but it's still useful to profile this
b.iter(|| {
@ -692,8 +713,8 @@ fn ordermap_sort_s(b: &mut Bencher) {
}
#[bench]
fn ordermap_simple_sort_s(b: &mut Bencher) {
let map = OMAP_SORT_S.clone();
fn indexmap_simple_sort_s(b: &mut Bencher) {
let map = IMAP_SORT_S.clone();
// there's a map clone there, but it's still useful to profile this
b.iter(|| {
@ -704,8 +725,8 @@ fn ordermap_simple_sort_s(b: &mut Bencher) {
}
#[bench]
fn ordermap_sort_u32(b: &mut Bencher) {
let map = OMAP_SORT_U32.clone();
fn indexmap_sort_u32(b: &mut Bencher) {
let map = IMAP_SORT_U32.clone();
// there's a map clone there, but it's still useful to profile this
b.iter(|| {
@ -716,8 +737,8 @@ fn ordermap_sort_u32(b: &mut Bencher) {
}
#[bench]
fn ordermap_simple_sort_u32(b: &mut Bencher) {
let map = OMAP_SORT_U32.clone();
fn indexmap_simple_sort_u32(b: &mut Bencher) {
let map = IMAP_SORT_U32.clone();
// there's a map clone there, but it's still useful to profile this
b.iter(|| {
@ -729,20 +750,15 @@ fn ordermap_simple_sort_u32(b: &mut Bencher) {
// measure the fixed overhead of cloning in sort benchmarks
#[bench]
fn ordermap_clone_for_sort_s(b: &mut Bencher) {
let map = OMAP_SORT_S.clone();
fn indexmap_clone_for_sort_s(b: &mut Bencher) {
let map = IMAP_SORT_S.clone();
b.iter(|| {
map.clone()
});
b.iter(|| map.clone());
}
#[bench]
fn ordermap_clone_for_sort_u32(b: &mut Bencher) {
let map = OMAP_SORT_U32.clone();
fn indexmap_clone_for_sort_u32(b: &mut Bencher) {
let map = IMAP_SORT_U32.clone();
b.iter(|| {
map.clone()
});
b.iter(|| map.clone());
}

Просмотреть файл

@ -1,80 +1,78 @@
#![feature(test)]
extern crate test;
extern crate rand;
extern crate lazy_static;
use test::Bencher;
extern crate indexmap;
use indexmap::IndexMap;
use std::collections::HashMap;
use std::iter::FromIterator;
use rand::thread_rng;
use rand::rngs::SmallRng;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use std::hash::{Hash, Hasher};
use std::borrow::Borrow;
use std::ops::Deref;
use std::mem;
/// Use a consistently seeded Rng for benchmark stability
fn small_rng() -> SmallRng {
let seed = u64::from_le_bytes(*b"indexmap");
SmallRng::seed_from_u64(seed)
}
#[derive(PartialEq, Eq, Copy, Clone)]
#[repr(transparent)]
pub struct OneShot<T: ?Sized>(pub T);
impl Hash for OneShot<str>
{
impl Hash for OneShot<str> {
fn hash<H: Hasher>(&self, h: &mut H) {
h.write(self.0.as_bytes())
}
}
impl<'a, S> From<&'a S> for &'a OneShot<str>
where S: AsRef<str>
where
S: AsRef<str>,
{
fn from(s: &'a S) -> Self {
let s: &str = s.as_ref();
unsafe {
mem::transmute(s)
}
unsafe { &*(s as *const str as *const OneShot<str>) }
}
}
impl Hash for OneShot<String>
{
impl Hash for OneShot<String> {
fn hash<H: Hasher>(&self, h: &mut H) {
h.write(self.0.as_bytes())
}
}
impl Borrow<OneShot<str>> for OneShot<String>
{
impl Borrow<OneShot<str>> for OneShot<String> {
fn borrow(&self) -> &OneShot<str> {
<&OneShot<str>>::from(&self.0)
}
}
impl<T> Deref for OneShot<T>
{
impl<T> Deref for OneShot<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
fn shuffled_keys<I>(iter: I) -> Vec<I::Item>
where I: IntoIterator
where
I: IntoIterator,
{
let mut v = Vec::from_iter(iter);
let mut rng = thread_rng();
let mut rng = small_rng();
v.shuffle(&mut rng);
v
}
#[bench]
fn insert_hashmap_string_10_000(b: &mut Bencher) {
let c = 10_000;
@ -100,7 +98,7 @@ fn insert_hashmap_string_oneshot_10_000(b: &mut Bencher) {
}
#[bench]
fn insert_orderedmap_string_10_000(b: &mut Bencher) {
fn insert_indexmap_string_10_000(b: &mut Bencher) {
let c = 10_000;
b.iter(|| {
let mut map = IndexMap::with_capacity(c);
@ -137,7 +135,9 @@ fn lookup_hashmap_10_000_exist_string_oneshot(b: &mut Bencher) {
for &key in &keys {
map.insert(OneShot(key.to_string()), 1);
}
let lookups = (5000..c).map(|x| OneShot(x.to_string())).collect::<Vec<_>>();
let lookups = (5000..c)
.map(|x| OneShot(x.to_string()))
.collect::<Vec<_>>();
b.iter(|| {
let mut found = 0;
for key in &lookups {
@ -148,7 +148,7 @@ fn lookup_hashmap_10_000_exist_string_oneshot(b: &mut Bencher) {
}
#[bench]
fn lookup_ordermap_10_000_exist_string(b: &mut Bencher) {
fn lookup_indexmap_10_000_exist_string(b: &mut Bencher) {
let c = 10_000;
let mut map = IndexMap::with_capacity(c);
let keys = shuffled_keys(0..c);
@ -166,14 +166,16 @@ fn lookup_ordermap_10_000_exist_string(b: &mut Bencher) {
}
#[bench]
fn lookup_ordermap_10_000_exist_string_oneshot(b: &mut Bencher) {
fn lookup_indexmap_10_000_exist_string_oneshot(b: &mut Bencher) {
let c = 10_000;
let mut map = IndexMap::with_capacity(c);
let keys = shuffled_keys(0..c);
for &key in &keys {
map.insert(OneShot(key.to_string()), 1);
}
let lookups = (5000..c).map(|x| OneShot(x.to_string())).collect::<Vec<_>>();
let lookups = (5000..c)
.map(|x| OneShot(x.to_string()))
.collect::<Vec<_>>();
b.iter(|| {
let mut found = 0;
for key in &lookups {

8
third_party/rust/indexmap/build.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,8 @@
fn main() {
// If "std" is explicitly requested, don't bother probing the target for it.
match std::env::var_os("CARGO_FEATURE_STD") {
Some(_) => autocfg::emit("has_std"),
None => autocfg::new().emit_sysroot_crate("std"),
}
autocfg::rerun_path("build.rs");
}

8
third_party/rust/indexmap/src/equivalent.rs поставляемый
Просмотреть файл

@ -1,5 +1,4 @@
use std::borrow::Borrow;
use core::borrow::Borrow;
/// Key equivalence trait.
///
@ -17,8 +16,9 @@ pub trait Equivalent<K: ?Sized> {
}
impl<Q: ?Sized, K: ?Sized> Equivalent<K> for Q
where Q: Eq,
K: Borrow<Q>,
where
Q: Eq,
K: Borrow<Q>,
{
#[inline]
fn equivalent(&self, key: &K) -> bool {

162
third_party/rust/indexmap/src/lib.rs поставляемый
Просмотреть файл

@ -1,6 +1,8 @@
// We *mostly* avoid unsafe code, but `map::core::raw` allows it to use `RawTable` buckets.
#![deny(unsafe_code)]
#![warn(rust_2018_idioms)]
#![doc(html_root_url = "https://docs.rs/indexmap/1/")]
#![no_std]
//! [`IndexMap`] is a hash table where the iteration order of the key-value
//! pairs is independent of the hash values of the keys.
@ -12,75 +14,170 @@
//! [`IndexSet`]: set/struct.IndexSet.html
//!
//!
//! ## Rust Version
//! ### Feature Highlights
//!
//! This version of indexmap requires Rust 1.18 or later, or 1.30+ for
//! development builds.
//! [`IndexMap`] and [`IndexSet`] are drop-in compatible with the std `HashMap`
//! and `HashSet`, but they also have some features of note:
//!
//! - The ordering semantics (see their documentation for details)
//! - Sorting methods and the [`.pop()`][IndexMap::pop] methods.
//! - The [`Equivalent`] trait, which offers more flexible equality definitions
//! between borrowed and owned versions of keys.
//! - The [`MutableKeys`][map::MutableKeys] trait, which gives opt-in mutable
//! access to hash map keys.
//!
//! ### Alternate Hashers
//!
//! [`IndexMap`] and [`IndexSet`] have a default hasher type `S = RandomState`,
//! just like the standard `HashMap` and `HashSet`, which is resistant to
//! HashDoS attacks but not the most performant. Type aliases can make it easier
//! to use alternate hashers:
//!
//! ```
//! use fnv::FnvBuildHasher;
//! use fxhash::FxBuildHasher;
//! use indexmap::{IndexMap, IndexSet};
//!
//! type FnvIndexMap<K, V> = IndexMap<K, V, FnvBuildHasher>;
//! type FnvIndexSet<T> = IndexSet<T, FnvBuildHasher>;
//!
//! type FxIndexMap<K, V> = IndexMap<K, V, FxBuildHasher>;
//! type FxIndexSet<T> = IndexSet<T, FxBuildHasher>;
//!
//! let std: IndexSet<i32> = (0..100).collect();
//! let fnv: FnvIndexSet<i32> = (0..100).collect();
//! let fx: FxIndexSet<i32> = (0..100).collect();
//! assert_eq!(std, fnv);
//! assert_eq!(std, fx);
//! ```
//!
//! ### Rust Version
//!
//! This version of indexmap requires Rust 1.32 or later, or Rust 1.36+ for
//! using with `alloc` (without `std`), see below.
//!
//! The indexmap 1.x release series will use a carefully considered version
//! upgrade policy, where in a later 1.x version, we will raise the minimum
//! required Rust version.
//!
//! ## No Standard Library Targets
//!
//! From Rust 1.36, this crate supports being built without `std`, requiring
//! `alloc` instead. This is enabled automatically when it is detected that
//! `std` is not available. There is no crate feature to enable/disable to
//! trigger this. It can be tested by building for a std-less target.
//!
//! - Creating maps and sets using [`new`][IndexMap::new] and
//! [`with_capacity`][IndexMap::with_capacity] is unavailable without `std`.
//! Use methods [`IndexMap::default`][def],
//! [`with_hasher`][IndexMap::with_hasher],
//! [`with_capacity_and_hasher`][IndexMap::with_capacity_and_hasher] instead.
//! A no-std compatible hasher will be needed as well, for example
//! from the crate `twox-hash`.
//! - Macros [`indexmap!`] and [`indexset!`] are unavailable without `std`.
//!
//! [def]: map/struct.IndexMap.html#impl-Default
#[cfg(not(has_std))]
extern crate alloc;
#[cfg(has_std)]
#[macro_use]
extern crate std;
#[cfg(not(has_std))]
use alloc::vec::{self, Vec};
#[cfg(has_std)]
use std::vec::{self, Vec};
#[macro_use]
mod macros;
mod equivalent;
mod mutable_keys;
#[cfg(feature = "serde-1")]
mod serde;
mod util;
mod equivalent;
mod mutable_keys;
pub mod set;
pub mod map;
pub mod set;
// Placed after `map` and `set` so new `rayon` methods on the types
// are documented after the "normal" methods.
#[cfg(feature = "rayon")]
mod rayon;
pub use equivalent::Equivalent;
pub use map::IndexMap;
pub use set::IndexSet;
pub use crate::equivalent::Equivalent;
pub use crate::map::IndexMap;
pub use crate::set::IndexSet;
// shared private items
/// Hash value newtype. Not larger than usize, since anything larger
/// isn't used for selecting position anyway.
#[derive(Copy, Debug)]
#[derive(Clone, Copy, Debug, PartialEq)]
struct HashValue(usize);
impl HashValue {
#[inline(always)]
fn get(self) -> usize { self.0 }
}
impl Clone for HashValue {
#[inline]
fn clone(&self) -> Self { *self }
}
impl PartialEq for HashValue {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.0 == rhs.0
fn get(self) -> u64 {
self.0 as u64
}
}
#[derive(Copy, Clone, Debug)]
#[derive(Copy, Debug)]
struct Bucket<K, V> {
hash: HashValue,
key: K,
value: V,
}
impl<K, V> Clone for Bucket<K, V>
where
K: Clone,
V: Clone,
{
fn clone(&self) -> Self {
Bucket {
hash: self.hash,
key: self.key.clone(),
value: self.value.clone(),
}
}
fn clone_from(&mut self, other: &Self) {
self.hash = other.hash;
self.key.clone_from(&other.key);
self.value.clone_from(&other.value);
}
}
impl<K, V> Bucket<K, V> {
// field accessors -- used for `f` instead of closures in `.map(f)`
fn key_ref(&self) -> &K { &self.key }
fn value_ref(&self) -> &V { &self.value }
fn value_mut(&mut self) -> &mut V { &mut self.value }
fn key(self) -> K { self.key }
fn key_value(self) -> (K, V) { (self.key, self.value) }
fn refs(&self) -> (&K, &V) { (&self.key, &self.value) }
fn ref_mut(&mut self) -> (&K, &mut V) { (&self.key, &mut self.value) }
fn muts(&mut self) -> (&mut K, &mut V) { (&mut self.key, &mut self.value) }
fn key_ref(&self) -> &K {
&self.key
}
fn value_ref(&self) -> &V {
&self.value
}
fn value_mut(&mut self) -> &mut V {
&mut self.value
}
fn key(self) -> K {
self.key
}
fn key_value(self) -> (K, V) {
(self.key, self.value)
}
fn refs(&self) -> (&K, &V) {
(&self.key, &self.value)
}
fn ref_mut(&mut self) -> (&K, &mut V) {
(&self.key, &mut self.value)
}
fn muts(&mut self) -> (&mut K, &mut V) {
(&mut self.key, &mut self.value)
}
}
trait Entries {
@ -89,5 +186,6 @@ trait Entries {
fn as_entries(&self) -> &[Self::Entry];
fn as_entries_mut(&mut self) -> &mut [Self::Entry];
fn with_entries<F>(&mut self, f: F)
where F: FnOnce(&mut [Self::Entry]);
where
F: FnOnce(&mut [Self::Entry]);
}

30
third_party/rust/indexmap/src/macros.rs поставляемый
Просмотреть файл

@ -1,12 +1,11 @@
#[cfg(has_std)]
#[macro_export]
/// Create an `IndexMap` from a list of key-value pairs
///
/// ## Example
///
/// ```
/// #[macro_use] extern crate indexmap;
/// # fn main() {
/// use indexmap::indexmap;
///
/// let map = indexmap!{
/// "a" => 1,
@ -18,16 +17,15 @@
///
/// // "a" is the first key
/// assert_eq!(map.keys().next(), Some(&"a"));
/// # }
/// ```
macro_rules! indexmap {
(@single $($x:tt)*) => (());
(@count $($rest:expr),*) => (<[()]>::len(&[$(indexmap!(@single $rest)),*]));
(@count $($rest:expr),*) => (<[()]>::len(&[$($crate::indexmap!(@single $rest)),*]));
($($key:expr => $value:expr,)+) => { indexmap!($($key => $value),+) };
($($key:expr => $value:expr,)+) => { $crate::indexmap!($($key => $value),+) };
($($key:expr => $value:expr),*) => {
{
let _cap = indexmap!(@count $($key),*);
let _cap = $crate::indexmap!(@count $($key),*);
let mut _map = $crate::IndexMap::with_capacity(_cap);
$(
_map.insert($key, $value);
@ -37,14 +35,14 @@ macro_rules! indexmap {
};
}
#[cfg(has_std)]
#[macro_export]
/// Create an `IndexSet` from a list of values
///
/// ## Example
///
/// ```
/// #[macro_use] extern crate indexmap;
/// # fn main() {
/// use indexmap::indexset;
///
/// let set = indexset!{
/// "a",
@ -56,16 +54,15 @@ macro_rules! indexmap {
///
/// // "a" is the first value
/// assert_eq!(set.iter().next(), Some(&"a"));
/// # }
/// ```
macro_rules! indexset {
(@single $($x:tt)*) => (());
(@count $($rest:expr),*) => (<[()]>::len(&[$(indexset!(@single $rest)),*]));
(@count $($rest:expr),*) => (<[()]>::len(&[$($crate::indexset!(@single $rest)),*]));
($($value:expr,)+) => { indexset!($($value),+) };
($($value:expr,)+) => { $crate::indexset!($($value),+) };
($($value:expr),*) => {
{
let _cap = indexset!(@count $($value),*);
let _cap = $crate::indexset!(@count $($value),*);
let mut _set = $crate::IndexSet::with_capacity(_cap);
$(
_set.insert($value);
@ -102,13 +99,14 @@ macro_rules! iterator_methods {
}
fn collect<C>(self) -> C
where C: FromIterator<Self::Item>
where
C: FromIterator<Self::Item>,
{
// NB: forwarding this directly to standard iterators will
// allow it to leverage unstable traits like `TrustedLen`.
self.iter.map($map_elt).collect()
}
}
};
}
macro_rules! double_ended_iterator_methods {
@ -118,5 +116,5 @@ macro_rules! double_ended_iterator_methods {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back().map($map_elt)
}
}
};
}

1999
third_party/rust/indexmap/src/map.rs поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

410
third_party/rust/indexmap/src/map/core.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,410 @@
//! This is the core implementation that doesn't depend on the hasher at all.
//!
//! The methods of `IndexMapCore` don't use any Hash properties of K.
//!
//! It's cleaner to separate them out, then the compiler checks that we are not
//! using Hash at all in these methods.
//!
//! However, we should probably not let this show in the public API or docs.
mod raw;
use hashbrown::raw::RawTable;
use crate::vec::{Drain, Vec};
use core::cmp;
use core::fmt;
use core::mem::replace;
use core::ops::RangeBounds;
use crate::equivalent::Equivalent;
use crate::util::{enumerate, simplify_range};
use crate::{Bucket, Entries, HashValue};
/// Core of the map that does not depend on S
pub(crate) struct IndexMapCore<K, V> {
/// indices mapping from the entry hash to its index.
indices: RawTable<usize>,
/// entries is a dense vec of entries in their order.
entries: Vec<Bucket<K, V>>,
}
#[inline(always)]
fn get_hash<K, V>(entries: &[Bucket<K, V>]) -> impl Fn(&usize) -> u64 + '_ {
move |&i| entries[i].hash.get()
}
impl<K, V> Clone for IndexMapCore<K, V>
where
K: Clone,
V: Clone,
{
fn clone(&self) -> Self {
let indices = self.indices.clone();
let mut entries = Vec::with_capacity(indices.capacity());
entries.clone_from(&self.entries);
IndexMapCore { indices, entries }
}
fn clone_from(&mut self, other: &Self) {
let hasher = get_hash(&other.entries);
self.indices.clone_from_with_hasher(&other.indices, hasher);
if self.entries.capacity() < other.entries.len() {
// If we must resize, match the indices capacity
self.reserve_entries();
}
self.entries.clone_from(&other.entries);
}
}
impl<K, V> fmt::Debug for IndexMapCore<K, V>
where
K: fmt::Debug,
V: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IndexMapCore")
.field("indices", &raw::DebugIndices(&self.indices))
.field("entries", &self.entries)
.finish()
}
}
impl<K, V> Entries for IndexMapCore<K, V> {
type Entry = Bucket<K, V>;
#[inline]
fn into_entries(self) -> Vec<Self::Entry> {
self.entries
}
#[inline]
fn as_entries(&self) -> &[Self::Entry] {
&self.entries
}
#[inline]
fn as_entries_mut(&mut self) -> &mut [Self::Entry] {
&mut self.entries
}
fn with_entries<F>(&mut self, f: F)
where
F: FnOnce(&mut [Self::Entry]),
{
f(&mut self.entries);
self.rebuild_hash_table();
}
}
impl<K, V> IndexMapCore<K, V> {
#[inline]
pub(crate) fn new() -> Self {
IndexMapCore {
indices: RawTable::new(),
entries: Vec::new(),
}
}
#[inline]
pub(crate) fn with_capacity(n: usize) -> Self {
IndexMapCore {
indices: RawTable::with_capacity(n),
entries: Vec::with_capacity(n),
}
}
#[inline]
pub(crate) fn len(&self) -> usize {
self.indices.len()
}
#[inline]
pub(crate) fn capacity(&self) -> usize {
cmp::min(self.indices.capacity(), self.entries.capacity())
}
pub(crate) fn clear(&mut self) {
self.indices.clear();
self.entries.clear();
}
pub(crate) fn drain<R>(&mut self, range: R) -> Drain<'_, Bucket<K, V>>
where
R: RangeBounds<usize>,
{
let range = simplify_range(range, self.entries.len());
self.erase_indices(range.start, range.end);
self.entries.drain(range)
}
/// Reserve capacity for `additional` more key-value pairs.
pub(crate) fn reserve(&mut self, additional: usize) {
self.indices.reserve(additional, get_hash(&self.entries));
self.reserve_entries();
}
/// Reserve entries capacity to match the indices
fn reserve_entries(&mut self) {
let additional = self.indices.capacity() - self.entries.len();
self.entries.reserve_exact(additional);
}
/// Shrink the capacity of the map as much as possible.
pub(crate) fn shrink_to_fit(&mut self) {
self.indices.shrink_to(0, get_hash(&self.entries));
self.entries.shrink_to_fit();
}
/// Remove the last key-value pair
pub(crate) fn pop(&mut self) -> Option<(K, V)> {
if let Some(entry) = self.entries.pop() {
let last = self.entries.len();
self.erase_index(entry.hash, last);
Some((entry.key, entry.value))
} else {
None
}
}
/// Append a key-value pair, *without* checking whether it already exists,
/// and return the pair's new index.
fn push(&mut self, hash: HashValue, key: K, value: V) -> usize {
let i = self.entries.len();
self.indices.insert(hash.get(), i, get_hash(&self.entries));
if i == self.entries.capacity() {
// Reserve our own capacity synced to the indices,
// rather than letting `Vec::push` just double it.
self.reserve_entries();
}
self.entries.push(Bucket { hash, key, value });
i
}
pub(crate) fn insert_full(&mut self, hash: HashValue, key: K, value: V) -> (usize, Option<V>)
where
K: Eq,
{
match self.get_index_of(hash, &key) {
Some(i) => (i, Some(replace(&mut self.entries[i].value, value))),
None => (self.push(hash, key, value), None),
}
}
pub(crate) fn retain_in_order<F>(&mut self, mut keep: F)
where
F: FnMut(&mut K, &mut V) -> bool,
{
// Like Vec::retain in self.entries, but with mutable K and V.
// We swap-shift all the items we want to keep, truncate the rest,
// then rebuild the raw hash table with the new indexes.
let len = self.entries.len();
let mut n_deleted = 0;
for i in 0..len {
let will_keep = {
let entry = &mut self.entries[i];
keep(&mut entry.key, &mut entry.value)
};
if !will_keep {
n_deleted += 1;
} else if n_deleted > 0 {
self.entries.swap(i - n_deleted, i);
}
}
if n_deleted > 0 {
self.entries.truncate(len - n_deleted);
self.rebuild_hash_table();
}
}
fn rebuild_hash_table(&mut self) {
self.indices.clear();
debug_assert!(self.indices.capacity() >= self.entries.len());
for (i, entry) in enumerate(&self.entries) {
// We should never have to reallocate, so there's no need for a real hasher.
self.indices.insert_no_grow(entry.hash.get(), i);
}
}
}
/// Entry for an existing key-value pair or a vacant location to
/// insert one.
pub enum Entry<'a, K, V> {
/// Existing slot with equivalent key.
Occupied(OccupiedEntry<'a, K, V>),
/// Vacant slot (no equivalent key in the map).
Vacant(VacantEntry<'a, K, V>),
}
impl<'a, K, V> Entry<'a, K, V> {
/// Computes in **O(1)** time (amortized average).
pub fn or_insert(self, default: V) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(default),
}
}
/// Computes in **O(1)** time (amortized average).
pub fn or_insert_with<F>(self, call: F) -> &'a mut V
where
F: FnOnce() -> V,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(call()),
}
}
pub fn key(&self) -> &K {
match *self {
Entry::Occupied(ref entry) => entry.key(),
Entry::Vacant(ref entry) => entry.key(),
}
}
/// Return the index where the key-value pair exists or will be inserted.
pub fn index(&self) -> usize {
match *self {
Entry::Occupied(ref entry) => entry.index(),
Entry::Vacant(ref entry) => entry.index(),
}
}
/// Modifies the entry if it is occupied.
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(&mut V),
{
match self {
Entry::Occupied(mut o) => {
f(o.get_mut());
Entry::Occupied(o)
}
x => x,
}
}
/// Inserts a default-constructed value in the entry if it is vacant and returns a mutable
/// reference to it. Otherwise a mutable reference to an already existent value is returned.
///
/// Computes in **O(1)** time (amortized average).
pub fn or_default(self) -> &'a mut V
where
V: Default,
{
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(V::default()),
}
}
}
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Entry<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Entry::Vacant(ref v) => f.debug_tuple(stringify!(Entry)).field(v).finish(),
Entry::Occupied(ref o) => f.debug_tuple(stringify!(Entry)).field(o).finish(),
}
}
}
pub use self::raw::OccupiedEntry;
// Extra methods that don't threaten the unsafe encapsulation.
impl<K, V> OccupiedEntry<'_, K, V> {
/// Sets the value of the entry to `value`, and returns the entry's old value.
pub fn insert(&mut self, value: V) -> V {
replace(self.get_mut(), value)
}
/// Remove the key, value pair stored in the map for this entry, and return the value.
///
/// **NOTE:** This is equivalent to `.swap_remove()`.
pub fn remove(self) -> V {
self.swap_remove()
}
/// Remove the key, value pair stored in the map for this entry, and return the value.
///
/// Like `Vec::swap_remove`, the pair is removed by swapping it with the
/// last element of the map and popping it off. **This perturbs
/// the postion of what used to be the last element!**
///
/// Computes in **O(1)** time (average).
pub fn swap_remove(self) -> V {
self.swap_remove_entry().1
}
/// Remove the key, value pair stored in the map for this entry, and return the value.
///
/// Like `Vec::remove`, the pair is removed by shifting all of the
/// elements that follow it, preserving their relative order.
/// **This perturbs the index of all of those elements!**
///
/// Computes in **O(n)** time (average).
pub fn shift_remove(self) -> V {
self.shift_remove_entry().1
}
/// Remove and return the key, value pair stored in the map for this entry
///
/// **NOTE:** This is equivalent to `.swap_remove_entry()`.
pub fn remove_entry(self) -> (K, V) {
self.swap_remove_entry()
}
}
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for OccupiedEntry<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct(stringify!(OccupiedEntry))
.field("key", self.key())
.field("value", self.get())
.finish()
}
}
/// A view into a vacant entry in a `IndexMap`.
/// It is part of the [`Entry`] enum.
///
/// [`Entry`]: enum.Entry.html
pub struct VacantEntry<'a, K, V> {
map: &'a mut IndexMapCore<K, V>,
hash: HashValue,
key: K,
}
impl<'a, K, V> VacantEntry<'a, K, V> {
pub fn key(&self) -> &K {
&self.key
}
pub fn into_key(self) -> K {
self.key
}
/// Return the index where the key-value pair will be inserted.
pub fn index(&self) -> usize {
self.map.len()
}
pub fn insert(self, value: V) -> &'a mut V {
let i = self.map.push(self.hash, self.key, value);
&mut self.map.entries[i].value
}
}
impl<K: fmt::Debug, V> fmt::Debug for VacantEntry<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple(stringify!(VacantEntry))
.field(self.key())
.finish()
}
}
#[test]
fn assert_send_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<IndexMapCore<i32, i32>>();
assert_send_sync::<Entry<'_, i32, i32>>();
}

335
third_party/rust/indexmap/src/map/core/raw.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,335 @@
#![allow(unsafe_code)]
//! This module encapsulates the `unsafe` access to `hashbrown::raw::RawTable`,
//! mostly in dealing with its bucket "pointers".
use super::{Entry, Equivalent, HashValue, IndexMapCore, VacantEntry};
use crate::util::enumerate;
use core::fmt;
use core::mem::replace;
use hashbrown::raw::RawTable;
type RawBucket = hashbrown::raw::Bucket<usize>;
pub(super) struct DebugIndices<'a>(pub &'a RawTable<usize>);
impl fmt::Debug for DebugIndices<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let indices = unsafe { self.0.iter().map(|raw_bucket| raw_bucket.read()) };
f.debug_list().entries(indices).finish()
}
}
impl<K, V> IndexMapCore<K, V> {
/// Return the raw bucket with an equivalent key
fn find_equivalent<Q>(&self, hash: HashValue, key: &Q) -> Option<RawBucket>
where
Q: ?Sized + Equivalent<K>,
{
self.indices.find(hash.get(), {
move |&i| Q::equivalent(key, &self.entries[i].key)
})
}
/// Return the raw bucket for the given index
fn find_index(&self, hash: HashValue, index: usize) -> Option<RawBucket> {
self.indices.find(hash.get(), move |&i| i == index)
}
/// Return the index in `entries` where an equivalent key can be found
pub(crate) fn get_index_of<Q>(&self, hash: HashValue, key: &Q) -> Option<usize>
where
Q: ?Sized + Equivalent<K>,
{
match self.find_equivalent(hash, key) {
Some(raw_bucket) => Some(unsafe { raw_bucket.read() }),
None => None,
}
}
/// Erase the given index from `indices`.
///
/// The index doesn't need to be valid in `entries` while calling this. No other index
/// adjustments are made -- this is only used by `pop` for the greatest index.
pub(super) fn erase_index(&mut self, hash: HashValue, index: usize) {
debug_assert_eq!(index, self.indices.len() - 1);
let raw_bucket = self.find_index(hash, index).unwrap();
unsafe { self.indices.erase(raw_bucket) };
}
/// Erase `start..end` from `indices`, and shift `end..` indices down to `start..`
///
/// All of these items should still be at their original location in `entries`.
/// This is used by `drain`, which will let `Vec::drain` do the work on `entries`.
pub(super) fn erase_indices(&mut self, start: usize, end: usize) {
let (init, shifted_entries) = self.entries.split_at(end);
let (start_entries, erased_entries) = init.split_at(start);
let erased = erased_entries.len();
let shifted = shifted_entries.len();
let half_capacity = self.indices.buckets() / 2;
// Use a heuristic between different strategies
if erased == 0 {
// Degenerate case, nothing to do
} else if start + shifted < half_capacity && start < erased {
// Reinsert everything, as there are few kept indices
self.indices.clear();
// Reinsert stable indices
for (i, entry) in enumerate(start_entries) {
self.indices.insert_no_grow(entry.hash.get(), i);
}
// Reinsert shifted indices
for (i, entry) in (start..).zip(shifted_entries) {
self.indices.insert_no_grow(entry.hash.get(), i);
}
} else if erased + shifted < half_capacity {
// Find each affected index, as there are few to adjust
// Find erased indices
for (i, entry) in (start..).zip(erased_entries) {
let bucket = self.find_index(entry.hash, i).unwrap();
unsafe { self.indices.erase(bucket) };
}
// Find shifted indices
for ((new, old), entry) in (start..).zip(end..).zip(shifted_entries) {
let bucket = self.find_index(entry.hash, old).unwrap();
unsafe { bucket.write(new) };
}
} else {
// Sweep the whole table for adjustments
unsafe {
for bucket in self.indices.iter() {
let i = bucket.read();
if i >= end {
bucket.write(i - erased);
} else if i >= start {
self.indices.erase(bucket);
}
}
}
}
debug_assert_eq!(self.indices.len(), start + shifted);
}
pub(crate) fn entry(&mut self, hash: HashValue, key: K) -> Entry<'_, K, V>
where
K: Eq,
{
match self.find_equivalent(hash, &key) {
// Safety: The entry is created with a live raw bucket, at the same time we have a &mut
// reference to the map, so it can not be modified further.
Some(raw_bucket) => Entry::Occupied(OccupiedEntry {
map: self,
raw_bucket,
key,
}),
None => Entry::Vacant(VacantEntry {
map: self,
hash,
key,
}),
}
}
/// Remove an entry by shifting all entries that follow it
pub(crate) fn shift_remove_full<Q>(&mut self, hash: HashValue, key: &Q) -> Option<(usize, K, V)>
where
Q: ?Sized + Equivalent<K>,
{
match self.find_equivalent(hash, key) {
Some(raw_bucket) => unsafe { Some(self.shift_remove_bucket(raw_bucket)) },
None => None,
}
}
/// Remove an entry by shifting all entries that follow it
pub(crate) fn shift_remove_index(&mut self, index: usize) -> Option<(K, V)> {
let raw_bucket = match self.entries.get(index) {
Some(entry) => self.find_index(entry.hash, index).unwrap(),
None => return None,
};
unsafe {
let (_, key, value) = self.shift_remove_bucket(raw_bucket);
Some((key, value))
}
}
/// Remove an entry by shifting all entries that follow it
///
/// Safety: The caller must pass a live `raw_bucket`.
#[allow(unused_unsafe)]
unsafe fn shift_remove_bucket(&mut self, raw_bucket: RawBucket) -> (usize, K, V) {
// use Vec::remove, but then we need to update the indices that point
// to all of the other entries that have to move
let index = unsafe { self.indices.remove(raw_bucket) };
let entry = self.entries.remove(index);
// correct indices that point to the entries that followed the removed entry.
// use a heuristic between a full sweep vs. a `find()` for every shifted item.
let raw_capacity = self.indices.buckets();
let shifted_entries = &self.entries[index..];
if shifted_entries.len() > raw_capacity / 2 {
// shift all indices greater than `index`
unsafe {
for bucket in self.indices.iter() {
let i = bucket.read();
if i > index {
bucket.write(i - 1);
}
}
}
} else {
// find each following entry to shift its index
for (i, entry) in (index + 1..).zip(shifted_entries) {
let shifted_bucket = self.find_index(entry.hash, i).unwrap();
unsafe { shifted_bucket.write(i - 1) };
}
}
(index, entry.key, entry.value)
}
/// Remove an entry by swapping it with the last
pub(crate) fn swap_remove_full<Q>(&mut self, hash: HashValue, key: &Q) -> Option<(usize, K, V)>
where
Q: ?Sized + Equivalent<K>,
{
match self.find_equivalent(hash, key) {
Some(raw_bucket) => unsafe { Some(self.swap_remove_bucket(raw_bucket)) },
None => None,
}
}
/// Remove an entry by swapping it with the last
pub(crate) fn swap_remove_index(&mut self, index: usize) -> Option<(K, V)> {
let raw_bucket = match self.entries.get(index) {
Some(entry) => self.find_index(entry.hash, index).unwrap(),
None => return None,
};
unsafe {
let (_, key, value) = self.swap_remove_bucket(raw_bucket);
Some((key, value))
}
}
/// Remove an entry by swapping it with the last
///
/// Safety: The caller must pass a live `raw_bucket`.
#[allow(unused_unsafe)]
unsafe fn swap_remove_bucket(&mut self, raw_bucket: RawBucket) -> (usize, K, V) {
// use swap_remove, but then we need to update the index that points
// to the other entry that has to move
let index = unsafe { self.indices.remove(raw_bucket) };
let entry = self.entries.swap_remove(index);
// correct index that points to the entry that had to swap places
if let Some(entry) = self.entries.get(index) {
// was not last element
// examine new element in `index` and find it in indices
let last = self.entries.len();
let swapped_bucket = self.find_index(entry.hash, last).unwrap();
unsafe { swapped_bucket.write(index) };
}
(index, entry.key, entry.value)
}
pub(crate) fn reverse(&mut self) {
self.entries.reverse();
// No need to save hash indices, can easily calculate what they should
// be, given that this is an in-place reversal.
let len = self.entries.len();
unsafe {
for raw_bucket in self.indices.iter() {
let i = raw_bucket.read();
raw_bucket.write(len - i - 1);
}
}
}
}
/// A view into an occupied entry in a `IndexMap`.
/// It is part of the [`Entry`] enum.
///
/// [`Entry`]: enum.Entry.html
// SAFETY: The lifetime of the map reference also constrains the raw bucket,
// which is essentially a raw pointer into the map indices.
pub struct OccupiedEntry<'a, K, V> {
map: &'a mut IndexMapCore<K, V>,
raw_bucket: RawBucket,
key: K,
}
// `hashbrown::raw::Bucket` is only `Send`, not `Sync`.
// SAFETY: `&self` only accesses the bucket to read it.
unsafe impl<K: Sync, V: Sync> Sync for OccupiedEntry<'_, K, V> {}
// The parent module also adds methods that don't threaten the unsafe encapsulation.
impl<'a, K, V> OccupiedEntry<'a, K, V> {
pub fn key(&self) -> &K {
&self.key
}
pub fn get(&self) -> &V {
&self.map.entries[self.index()].value
}
pub fn get_mut(&mut self) -> &mut V {
let index = self.index();
&mut self.map.entries[index].value
}
/// Put the new key in the occupied entry's key slot
pub(crate) fn replace_key(self) -> K {
let index = self.index();
let old_key = &mut self.map.entries[index].key;
replace(old_key, self.key)
}
/// Return the index of the key-value pair
#[inline]
pub fn index(&self) -> usize {
unsafe { self.raw_bucket.read() }
}
pub fn into_mut(self) -> &'a mut V {
let index = self.index();
&mut self.map.entries[index].value
}
/// Remove and return the key, value pair stored in the map for this entry
///
/// Like `Vec::swap_remove`, the pair is removed by swapping it with the
/// last element of the map and popping it off. **This perturbs
/// the postion of what used to be the last element!**
///
/// Computes in **O(1)** time (average).
pub fn swap_remove_entry(self) -> (K, V) {
// This is safe because it can only happen once (self is consumed)
// and map.indices have not been modified since entry construction
unsafe {
let (_, key, value) = self.map.swap_remove_bucket(self.raw_bucket);
(key, value)
}
}
/// Remove and return the key, value pair stored in the map for this entry
///
/// Like `Vec::remove`, the pair is removed by shifting all of the
/// elements that follow it, preserving their relative order.
/// **This perturbs the index of all of those elements!**
///
/// Computes in **O(n)** time (average).
pub fn shift_remove_entry(self) -> (K, V) {
// This is safe because it can only happen once (self is consumed)
// and map.indices have not been modified since entry construction
unsafe {
let (_, key, value) = self.map.shift_remove_bucket(self.raw_bucket);
(key, value)
}
}
}

38
third_party/rust/indexmap/src/mutable_keys.rs поставляемый
Просмотреть файл

@ -1,10 +1,8 @@
use core::hash::{BuildHasher, Hash};
use std::hash::Hash;
use std::hash::BuildHasher;
use super::{Equivalent, IndexMap};
use super::{IndexMap, Equivalent};
pub struct PrivateMarker { }
pub struct PrivateMarker {}
/// Opt-in mutable access to keys.
///
@ -21,11 +19,14 @@ pub struct PrivateMarker { }
pub trait MutableKeys {
type Key;
type Value;
/// Return item index, mutable reference to key and value
fn get_full_mut2<Q: ?Sized>(&mut self, key: &Q)
-> Option<(usize, &mut Self::Key, &mut Self::Value)>
where Q: Hash + Equivalent<Self::Key>;
fn get_full_mut2<Q: ?Sized>(
&mut self,
key: &Q,
) -> Option<(usize, &mut Self::Key, &mut Self::Value)>
where
Q: Hash + Equivalent<Self::Key>;
/// Scan through each key-value pair in the map and keep those where the
/// closure `keep` returns `true`.
@ -35,7 +36,8 @@ pub trait MutableKeys {
///
/// Computes in **O(n)** time (average).
fn retain2<F>(&mut self, keep: F)
where F: FnMut(&mut Self::Key, &mut Self::Value) -> bool;
where
F: FnMut(&mut Self::Key, &mut Self::Value) -> bool;
/// This method is not useful in itself – it is there to “seal” the trait
/// for external implementation, so that we can add methods without
@ -47,25 +49,27 @@ pub trait MutableKeys {
///
/// See [`MutableKeys`](trait.MutableKeys.html) for more information.
impl<K, V, S> MutableKeys for IndexMap<K, V, S>
where K: Eq + Hash,
S: BuildHasher,
where
K: Eq + Hash,
S: BuildHasher,
{
type Key = K;
type Value = V;
fn get_full_mut2<Q: ?Sized>(&mut self, key: &Q)
-> Option<(usize, &mut K, &mut V)>
where Q: Hash + Equivalent<K>,
fn get_full_mut2<Q: ?Sized>(&mut self, key: &Q) -> Option<(usize, &mut K, &mut V)>
where
Q: Hash + Equivalent<K>,
{
self.get_full_mut2_impl(key)
}
fn retain2<F>(&mut self, keep: F)
where F: FnMut(&mut K, &mut V) -> bool,
where
F: FnMut(&mut K, &mut V) -> bool,
{
self.retain_mut(keep)
}
fn __private_marker(&self) -> PrivateMarker {
PrivateMarker { }
PrivateMarker {}
}
}

205
third_party/rust/indexmap/src/rayon/map.rs поставляемый
Просмотреть файл

@ -6,23 +6,23 @@
//! Requires crate feature `"rayon"`
use super::collect;
use super::rayon::prelude::*;
use super::rayon::iter::plumbing::{Consumer, UnindexedConsumer, ProducerCallback};
use rayon::iter::plumbing::{Consumer, ProducerCallback, UnindexedConsumer};
use rayon::prelude::*;
use std::cmp::Ordering;
use std::fmt;
use std::hash::Hash;
use std::hash::BuildHasher;
use crate::vec::Vec;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{BuildHasher, Hash};
use Bucket;
use Entries;
use IndexMap;
use crate::Bucket;
use crate::Entries;
use crate::IndexMap;
/// Requires crate feature `"rayon"`.
impl<K, V, S> IntoParallelIterator for IndexMap<K, V, S>
where K: Hash + Eq + Send,
V: Send,
S: BuildHasher,
where
K: Send,
V: Send,
{
type Item = (K, V);
type Iter = IntoParIter<K, V>;
@ -46,7 +46,7 @@ pub struct IntoParIter<K, V> {
}
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoParIter<K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let iter = self.entries.iter().map(Bucket::refs);
f.debug_list().entries(iter).finish()
}
@ -62,12 +62,11 @@ impl<K: Send, V: Send> IndexedParallelIterator for IntoParIter<K, V> {
indexed_parallel_iterator_methods!(Bucket::key_value);
}
/// Requires crate feature `"rayon"`.
impl<'a, K, V, S> IntoParallelIterator for &'a IndexMap<K, V, S>
where K: Hash + Eq + Sync,
V: Sync,
S: BuildHasher,
where
K: Sync,
V: Sync,
{
type Item = (&'a K, &'a V);
type Iter = ParIter<'a, K, V>;
@ -86,18 +85,18 @@ impl<'a, K, V, S> IntoParallelIterator for &'a IndexMap<K, V, S>
///
/// [`par_iter`]: ../struct.IndexMap.html#method.par_iter
/// [`IndexMap`]: ../struct.IndexMap.html
pub struct ParIter<'a, K: 'a, V: 'a> {
pub struct ParIter<'a, K, V> {
entries: &'a [Bucket<K, V>],
}
impl<'a, K, V> Clone for ParIter<'a, K, V> {
fn clone(&self) -> ParIter<'a, K, V> {
impl<K, V> Clone for ParIter<'_, K, V> {
fn clone(&self) -> Self {
ParIter { ..*self }
}
}
impl<'a, K: fmt::Debug, V: fmt::Debug> fmt::Debug for ParIter<'a, K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for ParIter<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let iter = self.entries.iter().map(Bucket::refs);
f.debug_list().entries(iter).finish()
}
@ -109,16 +108,15 @@ impl<'a, K: Sync, V: Sync> ParallelIterator for ParIter<'a, K, V> {
parallel_iterator_methods!(Bucket::refs);
}
impl<'a, K: Sync, V: Sync> IndexedParallelIterator for ParIter<'a, K, V> {
impl<K: Sync, V: Sync> IndexedParallelIterator for ParIter<'_, K, V> {
indexed_parallel_iterator_methods!(Bucket::refs);
}
/// Requires crate feature `"rayon"`.
impl<'a, K, V, S> IntoParallelIterator for &'a mut IndexMap<K, V, S>
where K: Hash + Eq + Sync + Send,
V: Send,
S: BuildHasher,
where
K: Sync + Send,
V: Send,
{
type Item = (&'a K, &'a mut V);
type Iter = ParIterMut<'a, K, V>;
@ -137,7 +135,7 @@ impl<'a, K, V, S> IntoParallelIterator for &'a mut IndexMap<K, V, S>
///
/// [`par_iter_mut`]: ../struct.IndexMap.html#method.par_iter_mut
/// [`IndexMap`]: ../struct.IndexMap.html
pub struct ParIterMut<'a, K: 'a, V: 'a> {
pub struct ParIterMut<'a, K, V> {
entries: &'a mut [Bucket<K, V>],
}
@ -147,22 +145,25 @@ impl<'a, K: Sync + Send, V: Send> ParallelIterator for ParIterMut<'a, K, V> {
parallel_iterator_methods!(Bucket::ref_mut);
}
impl<'a, K: Sync + Send, V: Send> IndexedParallelIterator for ParIterMut<'a, K, V> {
impl<K: Sync + Send, V: Send> IndexedParallelIterator for ParIterMut<'_, K, V> {
indexed_parallel_iterator_methods!(Bucket::ref_mut);
}
/// Requires crate feature `"rayon"`.
/// Parallel iterator methods and other parallel methods.
///
/// The following methods **require crate feature `"rayon"`**.
///
/// See also the `IntoParallelIterator` implementations.
impl<K, V, S> IndexMap<K, V, S>
where K: Hash + Eq + Sync,
V: Sync,
S: BuildHasher,
where
K: Sync,
V: Sync,
{
/// Return a parallel iterator over the keys of the map.
///
/// While parallel iterators can process items in any order, their relative order
/// in the map is still preserved for operations like `reduce` and `collect`.
pub fn par_keys(&self) -> ParKeys<K, V> {
pub fn par_keys(&self) -> ParKeys<'_, K, V> {
ParKeys {
entries: self.as_entries(),
}
@ -172,23 +173,31 @@ impl<K, V, S> IndexMap<K, V, S>
///
/// While parallel iterators can process items in any order, their relative order
/// in the map is still preserved for operations like `reduce` and `collect`.
pub fn par_values(&self) -> ParValues<K, V> {
pub fn par_values(&self) -> ParValues<'_, K, V> {
ParValues {
entries: self.as_entries(),
}
}
}
impl<K, V, S> IndexMap<K, V, S>
where
K: Hash + Eq + Sync,
V: Sync,
S: BuildHasher,
{
/// Returns `true` if `self` contains all of the same key-value pairs as `other`,
/// regardless of each map's indexed order, determined in parallel.
pub fn par_eq<V2, S2>(&self, other: &IndexMap<K, V2, S2>) -> bool
where V: PartialEq<V2>,
V2: Sync,
S2: BuildHasher + Sync
where
V: PartialEq<V2>,
V2: Sync,
S2: BuildHasher + Sync,
{
self.len() == other.len() &&
self.par_iter().all(move |(key, value)| {
other.get(key).map_or(false, |v| *value == *v)
})
self.len() == other.len()
&& self
.par_iter()
.all(move |(key, value)| other.get(key).map_or(false, |v| *value == *v))
}
}
@ -199,18 +208,18 @@ impl<K, V, S> IndexMap<K, V, S>
///
/// [`par_keys`]: ../struct.IndexMap.html#method.par_keys
/// [`IndexMap`]: ../struct.IndexMap.html
pub struct ParKeys<'a, K: 'a, V: 'a> {
pub struct ParKeys<'a, K, V> {
entries: &'a [Bucket<K, V>],
}
impl<'a, K, V> Clone for ParKeys<'a, K, V> {
fn clone(&self) -> ParKeys<'a, K, V> {
impl<K, V> Clone for ParKeys<'_, K, V> {
fn clone(&self) -> Self {
ParKeys { ..*self }
}
}
impl<'a, K: fmt::Debug, V> fmt::Debug for ParKeys<'a, K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
impl<K: fmt::Debug, V> fmt::Debug for ParKeys<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let iter = self.entries.iter().map(Bucket::key_ref);
f.debug_list().entries(iter).finish()
}
@ -222,7 +231,7 @@ impl<'a, K: Sync, V: Sync> ParallelIterator for ParKeys<'a, K, V> {
parallel_iterator_methods!(Bucket::key_ref);
}
impl<'a, K: Sync, V: Sync> IndexedParallelIterator for ParKeys<'a, K, V> {
impl<K: Sync, V: Sync> IndexedParallelIterator for ParKeys<'_, K, V> {
indexed_parallel_iterator_methods!(Bucket::key_ref);
}
@ -233,18 +242,18 @@ impl<'a, K: Sync, V: Sync> IndexedParallelIterator for ParKeys<'a, K, V> {
///
/// [`par_values`]: ../struct.IndexMap.html#method.par_values
/// [`IndexMap`]: ../struct.IndexMap.html
pub struct ParValues<'a, K: 'a, V: 'a> {
pub struct ParValues<'a, K, V> {
entries: &'a [Bucket<K, V>],
}
impl<'a, K, V> Clone for ParValues<'a, K, V> {
fn clone(&self) -> ParValues<'a, K, V> {
impl<K, V> Clone for ParValues<'_, K, V> {
fn clone(&self) -> Self {
ParValues { ..*self }
}
}
impl<'a, K, V: fmt::Debug> fmt::Debug for ParValues<'a, K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
impl<K, V: fmt::Debug> fmt::Debug for ParValues<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let iter = self.entries.iter().map(Bucket::value_ref);
f.debug_list().entries(iter).finish()
}
@ -256,30 +265,37 @@ impl<'a, K: Sync, V: Sync> ParallelIterator for ParValues<'a, K, V> {
parallel_iterator_methods!(Bucket::value_ref);
}
impl<'a, K: Sync, V: Sync> IndexedParallelIterator for ParValues<'a, K, V> {
impl<K: Sync, V: Sync> IndexedParallelIterator for ParValues<'_, K, V> {
indexed_parallel_iterator_methods!(Bucket::value_ref);
}
/// Requires crate feature `"rayon"`.
impl<K, V, S> IndexMap<K, V, S>
where K: Hash + Eq + Send,
V: Send,
S: BuildHasher,
where
K: Send,
V: Send,
{
/// Return a parallel iterator over mutable references to the the values of the map
///
/// While parallel iterators can process items in any order, their relative order
/// in the map is still preserved for operations like `reduce` and `collect`.
pub fn par_values_mut(&mut self) -> ParValuesMut<K, V> {
pub fn par_values_mut(&mut self) -> ParValuesMut<'_, K, V> {
ParValuesMut {
entries: self.as_entries_mut(),
}
}
}
impl<K, V, S> IndexMap<K, V, S>
where
K: Hash + Eq + Send,
V: Send,
S: BuildHasher,
{
/// Sort the maps key-value pairs in parallel, by the default ordering of the keys.
pub fn par_sort_keys(&mut self)
where K: Ord,
where
K: Ord,
{
self.with_entries(|entries| {
entries.par_sort_by(|a, b| K::cmp(&a.key, &b.key));
@ -292,7 +308,8 @@ impl<K, V, S> IndexMap<K, V, S>
/// The comparison function receives two key and value pairs to compare (you
/// can sort by keys or values or their combination as needed).
pub fn par_sort_by<F>(&mut self, cmp: F)
where F: Fn(&K, &V, &K, &V) -> Ordering + Sync,
where
F: Fn(&K, &V, &K, &V) -> Ordering + Sync,
{
self.with_entries(|entries| {
entries.par_sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
@ -302,7 +319,8 @@ impl<K, V, S> IndexMap<K, V, S>
/// Sort the key-value pairs of the map in parallel and return a by value parallel
/// iterator of the key-value pairs with the result.
pub fn par_sorted_by<F>(self, cmp: F) -> IntoParIter<K, V>
where F: Fn(&K, &V, &K, &V) -> Ordering + Sync
where
F: Fn(&K, &V, &K, &V) -> Ordering + Sync,
{
let mut entries = self.into_entries();
entries.par_sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
@ -317,7 +335,7 @@ impl<K, V, S> IndexMap<K, V, S>
///
/// [`par_values_mut`]: ../struct.IndexMap.html#method.par_values_mut
/// [`IndexMap`]: ../struct.IndexMap.html
pub struct ParValuesMut<'a, K: 'a, V: 'a> {
pub struct ParValuesMut<'a, K, V> {
entries: &'a mut [Bucket<K, V>],
}
@ -327,19 +345,20 @@ impl<'a, K: Send, V: Send> ParallelIterator for ParValuesMut<'a, K, V> {
parallel_iterator_methods!(Bucket::value_mut);
}
impl<'a, K: Send, V: Send> IndexedParallelIterator for ParValuesMut<'a, K, V> {
impl<K: Send, V: Send> IndexedParallelIterator for ParValuesMut<'_, K, V> {
indexed_parallel_iterator_methods!(Bucket::value_mut);
}
/// Requires crate feature `"rayon"`.
impl<K, V, S> FromParallelIterator<(K, V)> for IndexMap<K, V, S>
where K: Eq + Hash + Send,
V: Send,
S: BuildHasher + Default + Send,
where
K: Eq + Hash + Send,
V: Send,
S: BuildHasher + Default + Send,
{
fn from_par_iter<I>(iter: I) -> Self
where I: IntoParallelIterator<Item = (K, V)>
where
I: IntoParallelIterator<Item = (K, V)>,
{
let list = collect(iter);
let len = list.iter().map(Vec::len).sum();
@ -353,12 +372,14 @@ impl<K, V, S> FromParallelIterator<(K, V)> for IndexMap<K, V, S>
/// Requires crate feature `"rayon"`.
impl<K, V, S> ParallelExtend<(K, V)> for IndexMap<K, V, S>
where K: Eq + Hash + Send,
V: Send,
S: BuildHasher + Send,
where
K: Eq + Hash + Send,
V: Send,
S: BuildHasher + Send,
{
fn par_extend<I>(&mut self, iter: I)
where I: IntoParallelIterator<Item = (K, V)>
where
I: IntoParallelIterator<Item = (K, V)>,
{
for vec in collect(iter) {
self.extend(vec);
@ -368,12 +389,14 @@ impl<K, V, S> ParallelExtend<(K, V)> for IndexMap<K, V, S>
/// Requires crate feature `"rayon"`.
impl<'a, K: 'a, V: 'a, S> ParallelExtend<(&'a K, &'a V)> for IndexMap<K, V, S>
where K: Copy + Eq + Hash + Send + Sync,
V: Copy + Send + Sync,
S: BuildHasher + Send,
where
K: Copy + Eq + Hash + Send + Sync,
V: Copy + Send + Sync,
S: BuildHasher + Send,
{
fn par_extend<I>(&mut self, iter: I)
where I: IntoParallelIterator<Item = (&'a K, &'a V)>
where
I: IntoParallelIterator<Item = (&'a K, &'a V)>,
{
for vec in collect(iter) {
self.extend(vec);
@ -381,10 +404,10 @@ impl<'a, K: 'a, V: 'a, S> ParallelExtend<(&'a K, &'a V)> for IndexMap<K, V, S>
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::string::String;
#[test]
fn insert_order() {
@ -400,9 +423,12 @@ mod tests {
insert.par_iter().zip(map.par_keys()).for_each(|(a, b)| {
assert_eq!(a, b);
});
(0..insert.len()).into_par_iter().zip(map.par_keys()).for_each(|(i, k)| {
assert_eq!(map.get_index(i).unwrap().0, k);
});
(0..insert.len())
.into_par_iter()
.zip(map.par_keys())
.for_each(|(i, k)| {
assert_eq!(map.get_index(i).unwrap().0, k);
});
}
#[test]
@ -412,13 +438,13 @@ mod tests {
map_a.insert(2, "2");
let mut map_b = map_a.clone();
assert!(map_a.par_eq(&map_b));
map_b.remove(&1);
map_b.swap_remove(&1);
assert!(!map_a.par_eq(&map_b));
map_b.insert(3, "3");
assert!(!map_a.par_eq(&map_b));
let map_c: IndexMap<_, String>
= map_b.into_par_iter().map(|(k, v)| (k, v.to_owned())).collect();
let map_c: IndexMap<_, String> =
map_b.into_par_iter().map(|(k, v)| (k, v.into())).collect();
assert!(!map_a.par_eq(&map_c));
assert!(!map_c.par_eq(&map_a));
}
@ -428,7 +454,10 @@ mod tests {
let mut map = IndexMap::new();
map.par_extend(vec![(&1, &2), (&3, &4)]);
map.par_extend(vec![(5, 6)]);
assert_eq!(map.into_par_iter().collect::<Vec<_>>(), vec![(1, 2), (3, 4), (5, 6)]);
assert_eq!(
map.into_par_iter().collect::<Vec<_>>(),
vec![(1, 2), (3, 4), (5, 6)]
);
}
#[test]
@ -457,9 +486,7 @@ mod tests {
fn values_mut() {
let vec = vec![(1, 1), (2, 2), (3, 3)];
let mut map: IndexMap<_, _> = vec.into_par_iter().collect();
map.par_values_mut().for_each(|value| {
*value = (*value) * 2
});
map.par_values_mut().for_each(|value| *value *= 2);
let values: Vec<_> = map.par_values().cloned().collect();
assert_eq!(values.len(), 3);
assert!(values.contains(&2));

34
third_party/rust/indexmap/src/rayon/mod.rs поставляемый
Просмотреть файл

@ -1,19 +1,24 @@
use rayon::prelude::*;
extern crate rayon;
use self::rayon::prelude::*;
#[cfg(not(has_std))]
use alloc::collections::LinkedList;
#[cfg(has_std)]
use std::collections::LinkedList;
use crate::vec::Vec;
// generate `ParallelIterator` methods by just forwarding to the underlying
// self.entries and mapping its elements.
macro_rules! parallel_iterator_methods {
// $map_elt is the mapping function from the underlying iterator's element
($map_elt:expr) => {
fn drive_unindexed<C>(self, consumer: C) -> C::Result
where C: UnindexedConsumer<Self::Item>
where
C: UnindexedConsumer<Self::Item>,
{
self.entries.into_par_iter()
self.entries
.into_par_iter()
.map($map_elt)
.drive_unindexed(consumer)
}
@ -24,7 +29,7 @@ macro_rules! parallel_iterator_methods {
fn opt_len(&self) -> Option<usize> {
Some(self.entries.len())
}
}
};
}
// generate `IndexedParallelIterator` methods by just forwarding to the underlying
@ -33,11 +38,10 @@ macro_rules! indexed_parallel_iterator_methods {
// $map_elt is the mapping function from the underlying iterator's element
($map_elt:expr) => {
fn drive<C>(self, consumer: C) -> C::Result
where C: Consumer<Self::Item>
where
C: Consumer<Self::Item>,
{
self.entries.into_par_iter()
.map($map_elt)
.drive(consumer)
self.entries.into_par_iter().map($map_elt).drive(consumer)
}
fn len(&self) -> usize {
@ -45,20 +49,20 @@ macro_rules! indexed_parallel_iterator_methods {
}
fn with_producer<CB>(self, callback: CB) -> CB::Output
where CB: ProducerCallback<Self::Item>
where
CB: ProducerCallback<Self::Item>,
{
self.entries.into_par_iter()
self.entries
.into_par_iter()
.map($map_elt)
.with_producer(callback)
}
}
};
}
pub mod map;
pub mod set;
// This form of intermediate collection is also how Rayon collects `HashMap`.
// Note that the order will also be preserved!
fn collect<I: IntoParallelIterator>(iter: I) -> LinkedList<Vec<I::Item>> {

281
third_party/rust/indexmap/src/rayon/set.rs поставляемый
Просмотреть файл

@ -6,23 +6,23 @@
//! Requires crate feature `"rayon"`.
use super::collect;
use super::rayon::prelude::*;
use super::rayon::iter::plumbing::{Consumer, UnindexedConsumer, ProducerCallback};
use rayon::iter::plumbing::{Consumer, ProducerCallback, UnindexedConsumer};
use rayon::prelude::*;
use std::cmp::Ordering;
use std::fmt;
use std::hash::Hash;
use std::hash::BuildHasher;
use crate::vec::Vec;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{BuildHasher, Hash};
use Entries;
use IndexSet;
use crate::Entries;
use crate::IndexSet;
type Bucket<T> = ::Bucket<T, ()>;
type Bucket<T> = crate::Bucket<T, ()>;
/// Requires crate feature `"rayon"`.
impl<T, S> IntoParallelIterator for IndexSet<T, S>
where T: Hash + Eq + Send,
S: BuildHasher,
where
T: Send,
{
type Item = T;
type Iter = IntoParIter<T>;
@ -46,7 +46,7 @@ pub struct IntoParIter<T> {
}
impl<T: fmt::Debug> fmt::Debug for IntoParIter<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let iter = self.entries.iter().map(Bucket::key_ref);
f.debug_list().entries(iter).finish()
}
@ -62,11 +62,10 @@ impl<T: Send> IndexedParallelIterator for IntoParIter<T> {
indexed_parallel_iterator_methods!(Bucket::key);
}
/// Requires crate feature `"rayon"`.
impl<'a, T, S> IntoParallelIterator for &'a IndexSet<T, S>
where T: Hash + Eq + Sync,
S: BuildHasher,
where
T: Sync,
{
type Item = &'a T;
type Iter = ParIter<'a, T>;
@ -85,18 +84,18 @@ impl<'a, T, S> IntoParallelIterator for &'a IndexSet<T, S>
///
/// [`IndexSet`]: ../struct.IndexSet.html
/// [`par_iter`]: ../struct.IndexSet.html#method.par_iter
pub struct ParIter<'a, T: 'a> {
pub struct ParIter<'a, T> {
entries: &'a [Bucket<T>],
}
impl<'a, T> Clone for ParIter<'a, T> {
impl<T> Clone for ParIter<'_, T> {
fn clone(&self) -> Self {
ParIter { ..*self }
}
}
impl<'a, T: fmt::Debug> fmt::Debug for ParIter<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
impl<T: fmt::Debug> fmt::Debug for ParIter<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let iter = self.entries.iter().map(Bucket::key_ref);
f.debug_list().entries(iter).finish()
}
@ -108,23 +107,30 @@ impl<'a, T: Sync> ParallelIterator for ParIter<'a, T> {
parallel_iterator_methods!(Bucket::key_ref);
}
impl<'a, T: Sync> IndexedParallelIterator for ParIter<'a, T> {
impl<T: Sync> IndexedParallelIterator for ParIter<'_, T> {
indexed_parallel_iterator_methods!(Bucket::key_ref);
}
/// Requires crate feature `"rayon"`.
/// Parallel iterator methods and other parallel methods.
///
/// The following methods **require crate feature `"rayon"`**.
///
/// See also the `IntoParallelIterator` implementations.
impl<T, S> IndexSet<T, S>
where T: Hash + Eq + Sync,
S: BuildHasher + Sync,
where
T: Hash + Eq + Sync,
S: BuildHasher + Sync,
{
/// Return a parallel iterator over the values that are in `self` but not `other`.
///
/// While parallel iterators can process items in any order, their relative order
/// in the `self` set is still preserved for operations like `reduce` and `collect`.
pub fn par_difference<'a, S2>(&'a self, other: &'a IndexSet<T, S2>)
-> ParDifference<'a, T, S, S2>
where S2: BuildHasher + Sync
pub fn par_difference<'a, S2>(
&'a self,
other: &'a IndexSet<T, S2>,
) -> ParDifference<'a, T, S, S2>
where
S2: BuildHasher + Sync,
{
ParDifference {
set1: self,
@ -139,9 +145,12 @@ impl<T, S> IndexSet<T, S>
/// in the sets is still preserved for operations like `reduce` and `collect`.
/// Values from `self` are produced in their original order, followed by
/// values from `other` in their original order.
pub fn par_symmetric_difference<'a, S2>(&'a self, other: &'a IndexSet<T, S2>)
-> ParSymmetricDifference<'a, T, S, S2>
where S2: BuildHasher + Sync
pub fn par_symmetric_difference<'a, S2>(
&'a self,
other: &'a IndexSet<T, S2>,
) -> ParSymmetricDifference<'a, T, S, S2>
where
S2: BuildHasher + Sync,
{
ParSymmetricDifference {
set1: self,
@ -153,9 +162,12 @@ impl<T, S> IndexSet<T, S>
///
/// While parallel iterators can process items in any order, their relative order
/// in the `self` set is still preserved for operations like `reduce` and `collect`.
pub fn par_intersection<'a, S2>(&'a self, other: &'a IndexSet<T, S2>)
-> ParIntersection<'a, T, S, S2>
where S2: BuildHasher + Sync
pub fn par_intersection<'a, S2>(
&'a self,
other: &'a IndexSet<T, S2>,
) -> ParIntersection<'a, T, S, S2>
where
S2: BuildHasher + Sync,
{
ParIntersection {
set1: self,
@ -169,9 +181,9 @@ impl<T, S> IndexSet<T, S>
/// in the sets is still preserved for operations like `reduce` and `collect`.
/// Values from `self` are produced in their original order, followed by
/// values that are unique to `other` in their original order.
pub fn par_union<'a, S2>(&'a self, other: &'a IndexSet<T, S2>)
-> ParUnion<'a, T, S, S2>
where S2: BuildHasher + Sync
pub fn par_union<'a, S2>(&'a self, other: &'a IndexSet<T, S2>) -> ParUnion<'a, T, S, S2>
where
S2: BuildHasher + Sync,
{
ParUnion {
set1: self,
@ -182,7 +194,8 @@ impl<T, S> IndexSet<T, S>
/// Returns `true` if `self` contains all of the same values as `other`,
/// regardless of each set's indexed order, determined in parallel.
pub fn par_eq<S2>(&self, other: &IndexSet<T, S2>) -> bool
where S2: BuildHasher + Sync
where
S2: BuildHasher + Sync,
{
self.len() == other.len() && self.par_is_subset(other)
}
@ -190,7 +203,8 @@ impl<T, S> IndexSet<T, S>
/// Returns `true` if `self` has no elements in common with `other`,
/// determined in parallel.
pub fn par_is_disjoint<S2>(&self, other: &IndexSet<T, S2>) -> bool
where S2: BuildHasher + Sync
where
S2: BuildHasher + Sync,
{
if self.len() <= other.len() {
self.par_iter().all(move |value| !other.contains(value))
@ -202,7 +216,8 @@ impl<T, S> IndexSet<T, S>
/// Returns `true` if all elements of `other` are contained in `self`,
/// determined in parallel.
pub fn par_is_superset<S2>(&self, other: &IndexSet<T, S2>) -> bool
where S2: BuildHasher + Sync
where
S2: BuildHasher + Sync,
{
other.par_is_subset(self)
}
@ -210,7 +225,8 @@ impl<T, S> IndexSet<T, S>
/// Returns `true` if all elements of `self` are contained in `other`,
/// determined in parallel.
pub fn par_is_subset<S2>(&self, other: &IndexSet<T, S2>) -> bool
where S2: BuildHasher + Sync
where
S2: BuildHasher + Sync,
{
self.len() <= other.len() && self.par_iter().all(move |value| other.contains(value))
}
@ -223,36 +239,41 @@ impl<T, S> IndexSet<T, S>
///
/// [`IndexSet`]: ../struct.IndexSet.html
/// [`par_difference`]: ../struct.IndexSet.html#method.par_difference
pub struct ParDifference<'a, T: 'a, S1: 'a, S2: 'a> {
pub struct ParDifference<'a, T, S1, S2> {
set1: &'a IndexSet<T, S1>,
set2: &'a IndexSet<T, S2>,
}
impl<'a, T, S1, S2> Clone for ParDifference<'a, T, S1, S2> {
impl<T, S1, S2> Clone for ParDifference<'_, T, S1, S2> {
fn clone(&self) -> Self {
ParDifference { ..*self }
}
}
impl<'a, T, S1, S2> fmt::Debug for ParDifference<'a, T, S1, S2>
where T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
impl<T, S1, S2> fmt::Debug for ParDifference<'_, T, S1, S2>
where
T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.set1.difference(&self.set2)).finish()
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.set1.difference(&self.set2))
.finish()
}
}
impl<'a, T, S1, S2> ParallelIterator for ParDifference<'a, T, S1, S2>
where T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
where
T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
{
type Item = &'a T;
fn drive_unindexed<C>(self, consumer: C) -> C::Result
where C: UnindexedConsumer<Self::Item>
where
C: UnindexedConsumer<Self::Item>,
{
let Self { set1, set2 } = self;
@ -269,36 +290,41 @@ impl<'a, T, S1, S2> ParallelIterator for ParDifference<'a, T, S1, S2>
///
/// [`IndexSet`]: ../struct.IndexSet.html
/// [`par_intersection`]: ../struct.IndexSet.html#method.par_intersection
pub struct ParIntersection<'a, T: 'a, S1: 'a, S2: 'a> {
pub struct ParIntersection<'a, T, S1, S2> {
set1: &'a IndexSet<T, S1>,
set2: &'a IndexSet<T, S2>,
}
impl<'a, T, S1, S2> Clone for ParIntersection<'a, T, S1, S2> {
impl<T, S1, S2> Clone for ParIntersection<'_, T, S1, S2> {
fn clone(&self) -> Self {
ParIntersection { ..*self }
}
}
impl<'a, T, S1, S2> fmt::Debug for ParIntersection<'a, T, S1, S2>
where T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
impl<T, S1, S2> fmt::Debug for ParIntersection<'_, T, S1, S2>
where
T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.set1.intersection(&self.set2)).finish()
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.set1.intersection(&self.set2))
.finish()
}
}
impl<'a, T, S1, S2> ParallelIterator for ParIntersection<'a, T, S1, S2>
where T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
where
T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
{
type Item = &'a T;
fn drive_unindexed<C>(self, consumer: C) -> C::Result
where C: UnindexedConsumer<Self::Item>
where
C: UnindexedConsumer<Self::Item>,
{
let Self { set1, set2 } = self;
@ -315,36 +341,41 @@ impl<'a, T, S1, S2> ParallelIterator for ParIntersection<'a, T, S1, S2>
///
/// [`IndexSet`]: ../struct.IndexSet.html
/// [`par_symmetric_difference`]: ../struct.IndexSet.html#method.par_symmetric_difference
pub struct ParSymmetricDifference<'a, T: 'a, S1: 'a, S2: 'a> {
pub struct ParSymmetricDifference<'a, T, S1, S2> {
set1: &'a IndexSet<T, S1>,
set2: &'a IndexSet<T, S2>,
}
impl<'a, T, S1, S2> Clone for ParSymmetricDifference<'a, T, S1, S2> {
impl<T, S1, S2> Clone for ParSymmetricDifference<'_, T, S1, S2> {
fn clone(&self) -> Self {
ParSymmetricDifference { ..*self }
}
}
impl<'a, T, S1, S2> fmt::Debug for ParSymmetricDifference<'a, T, S1, S2>
where T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
impl<T, S1, S2> fmt::Debug for ParSymmetricDifference<'_, T, S1, S2>
where
T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.set1.symmetric_difference(&self.set2)).finish()
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.set1.symmetric_difference(&self.set2))
.finish()
}
}
impl<'a, T, S1, S2> ParallelIterator for ParSymmetricDifference<'a, T, S1, S2>
where T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
where
T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
{
type Item = &'a T;
fn drive_unindexed<C>(self, consumer: C) -> C::Result
where C: UnindexedConsumer<Self::Item>
where
C: UnindexedConsumer<Self::Item>,
{
let Self { set1, set2 } = self;
@ -361,36 +392,39 @@ impl<'a, T, S1, S2> ParallelIterator for ParSymmetricDifference<'a, T, S1, S2>
///
/// [`IndexSet`]: ../struct.IndexSet.html
/// [`par_union`]: ../struct.IndexSet.html#method.par_union
pub struct ParUnion<'a, T: 'a, S1: 'a, S2: 'a> {
pub struct ParUnion<'a, T, S1, S2> {
set1: &'a IndexSet<T, S1>,
set2: &'a IndexSet<T, S2>,
}
impl<'a, T, S1, S2> Clone for ParUnion<'a, T, S1, S2> {
impl<T, S1, S2> Clone for ParUnion<'_, T, S1, S2> {
fn clone(&self) -> Self {
ParUnion { ..*self }
}
}
impl<'a, T, S1, S2> fmt::Debug for ParUnion<'a, T, S1, S2>
where T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
impl<T, S1, S2> fmt::Debug for ParUnion<'_, T, S1, S2>
where
T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.set1.union(&self.set2)).finish()
}
}
impl<'a, T, S1, S2> ParallelIterator for ParUnion<'a, T, S1, S2>
where T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
where
T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
{
type Item = &'a T;
fn drive_unindexed<C>(self, consumer: C) -> C::Result
where C: UnindexedConsumer<Self::Item>
where
C: UnindexedConsumer<Self::Item>,
{
let Self { set1, set2 } = self;
@ -400,15 +434,18 @@ impl<'a, T, S1, S2> ParallelIterator for ParUnion<'a, T, S1, S2>
}
}
/// Requires crate feature `"rayon"`.
/// Parallel sorting methods.
///
/// The following methods **require crate feature `"rayon"`**.
impl<T, S> IndexSet<T, S>
where T: Hash + Eq + Send,
S: BuildHasher + Send,
where
T: Hash + Eq + Send,
S: BuildHasher + Send,
{
/// Sort the sets values in parallel by their default ordering.
pub fn par_sort(&mut self)
where T: Ord,
where
T: Ord,
{
self.with_entries(|entries| {
entries.par_sort_by(|a, b| T::cmp(&a.key, &b.key));
@ -417,7 +454,8 @@ impl<T, S> IndexSet<T, S>
/// Sort the sets values in place and in parallel, using the comparison function `compare`.
pub fn par_sort_by<F>(&mut self, cmp: F)
where F: Fn(&T, &T) -> Ordering + Sync,
where
F: Fn(&T, &T) -> Ordering + Sync,
{
self.with_entries(|entries| {
entries.par_sort_by(move |a, b| cmp(&a.key, &b.key));
@ -427,7 +465,8 @@ impl<T, S> IndexSet<T, S>
/// Sort the values of the set in parallel and return a by value parallel iterator of
/// the values with the result.
pub fn par_sorted_by<F>(self, cmp: F) -> IntoParIter<T>
where F: Fn(&T, &T) -> Ordering + Sync
where
F: Fn(&T, &T) -> Ordering + Sync,
{
let mut entries = self.into_entries();
entries.par_sort_by(move |a, b| cmp(&a.key, &b.key));
@ -435,14 +474,15 @@ impl<T, S> IndexSet<T, S>
}
}
/// Requires crate feature `"rayon"`.
impl<T, S> FromParallelIterator<T> for IndexSet<T, S>
where T: Eq + Hash + Send,
S: BuildHasher + Default + Send,
where
T: Eq + Hash + Send,
S: BuildHasher + Default + Send,
{
fn from_par_iter<I>(iter: I) -> Self
where I: IntoParallelIterator<Item = T>
where
I: IntoParallelIterator<Item = T>,
{
let list = collect(iter);
let len = list.iter().map(Vec::len).sum();
@ -455,12 +495,14 @@ impl<T, S> FromParallelIterator<T> for IndexSet<T, S>
}
/// Requires crate feature `"rayon"`.
impl<T, S> ParallelExtend<(T)> for IndexSet<T, S>
where T: Eq + Hash + Send,
S: BuildHasher + Send,
impl<T, S> ParallelExtend<T> for IndexSet<T, S>
where
T: Eq + Hash + Send,
S: BuildHasher + Send,
{
fn par_extend<I>(&mut self, iter: I)
where I: IntoParallelIterator<Item = T>
where
I: IntoParallelIterator<Item = T>,
{
for vec in collect(iter) {
self.extend(vec);
@ -470,11 +512,13 @@ impl<T, S> ParallelExtend<(T)> for IndexSet<T, S>
/// Requires crate feature `"rayon"`.
impl<'a, T: 'a, S> ParallelExtend<&'a T> for IndexSet<T, S>
where T: Copy + Eq + Hash + Send + Sync,
S: BuildHasher + Send,
where
T: Copy + Eq + Hash + Send + Sync,
S: BuildHasher + Send,
{
fn par_extend<I>(&mut self, iter: I)
where I: IntoParallelIterator<Item = &'a T>
where
I: IntoParallelIterator<Item = &'a T>,
{
for vec in collect(iter) {
self.extend(vec);
@ -482,7 +526,6 @@ impl<'a, T: 'a, S> ParallelExtend<&'a T> for IndexSet<T, S>
}
}
#[cfg(test)]
mod tests {
use super::*;
@ -501,9 +544,12 @@ mod tests {
insert.par_iter().zip(&set).for_each(|(a, b)| {
assert_eq!(a, b);
});
(0..insert.len()).into_par_iter().zip(&set).for_each(|(i, v)| {
assert_eq!(set.get_index(i).unwrap(), v);
});
(0..insert.len())
.into_par_iter()
.zip(&set)
.for_each(|(i, v)| {
assert_eq!(set.get_index(i).unwrap(), v);
});
}
#[test]
@ -513,7 +559,7 @@ mod tests {
set_a.insert(2);
let mut set_b = set_a.clone();
assert!(set_a.par_eq(&set_b));
set_b.remove(&1);
set_b.swap_remove(&1);
assert!(!set_a.par_eq(&set_b));
set_b.insert(3);
assert!(!set_a.par_eq(&set_b));
@ -528,7 +574,10 @@ mod tests {
let mut set = IndexSet::new();
set.par_extend(vec![&1, &2, &3, &4]);
set.par_extend(vec![5, 6]);
assert_eq!(set.into_par_iter().collect::<Vec<_>>(), vec![1, 2, 3, 4, 5, 6]);
assert_eq!(
set.into_par_iter().collect::<Vec<_>>(),
vec![1, 2, 3, 4, 5, 6]
);
}
#[test]
@ -608,8 +657,14 @@ mod tests {
check(set_c.par_difference(&set_d), 0..3);
check(set_d.par_difference(&set_c), (6..9).rev());
check(set_c.par_symmetric_difference(&set_d), (0..3).chain((6..9).rev()));
check(set_d.par_symmetric_difference(&set_c), (6..9).rev().chain(0..3));
check(
set_c.par_symmetric_difference(&set_d),
(0..3).chain((6..9).rev()),
);
check(
set_d.par_symmetric_difference(&set_c),
(6..9).rev().chain(0..3),
);
check(set_c.par_intersection(&set_d), 3..6);
check(set_d.par_intersection(&set_c), (3..6).rev());
check(set_c.par_union(&set_d), (0..6).chain((6..9).rev()));

126
third_party/rust/indexmap/src/serde.rs поставляемый
Просмотреть файл

@ -1,52 +1,56 @@
use serde::de::value::{MapDeserializer, SeqDeserializer};
use serde::de::{
Deserialize, Deserializer, Error, IntoDeserializer, MapAccess, SeqAccess, Visitor,
};
use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer};
extern crate serde;
use core::fmt::{self, Formatter};
use core::hash::{BuildHasher, Hash};
use core::marker::PhantomData;
use self::serde::ser::{Serialize, Serializer, SerializeMap, SerializeSeq};
use self::serde::de::{Deserialize, Deserializer, Error, IntoDeserializer, MapAccess, SeqAccess, Visitor};
use self::serde::de::value::{MapDeserializer, SeqDeserializer};
use std::fmt::{self, Formatter};
use std::hash::{BuildHasher, Hash};
use std::marker::PhantomData;
use IndexMap;
use crate::IndexMap;
/// Requires crate feature `"serde-1"`
impl<K, V, S> Serialize for IndexMap<K, V, S>
where K: Serialize + Hash + Eq,
V: Serialize,
S: BuildHasher
where
K: Serialize + Hash + Eq,
V: Serialize,
S: BuildHasher,
{
fn serialize<T>(&self, serializer: T) -> Result<T::Ok, T::Error>
where T: Serializer
where
T: Serializer,
{
let mut map_serializer = try!(serializer.serialize_map(Some(self.len())));
let mut map_serializer = serializer.serialize_map(Some(self.len()))?;
for (key, value) in self {
try!(map_serializer.serialize_entry(key, value));
map_serializer.serialize_entry(key, value)?;
}
map_serializer.end()
}
}
struct OrderMapVisitor<K, V, S>(PhantomData<(K, V, S)>);
struct IndexMapVisitor<K, V, S>(PhantomData<(K, V, S)>);
impl<'de, K, V, S> Visitor<'de> for OrderMapVisitor<K, V, S>
where K: Deserialize<'de> + Eq + Hash,
V: Deserialize<'de>,
S: Default + BuildHasher
impl<'de, K, V, S> Visitor<'de> for IndexMapVisitor<K, V, S>
where
K: Deserialize<'de> + Eq + Hash,
V: Deserialize<'de>,
S: Default + BuildHasher,
{
type Value = IndexMap<K, V, S>;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(formatter, "a map")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where A: MapAccess<'de>
where
A: MapAccess<'de>,
{
let mut values = IndexMap::with_capacity_and_hasher(map.size_hint().unwrap_or(0), S::default());
let mut values =
IndexMap::with_capacity_and_hasher(map.size_hint().unwrap_or(0), S::default());
while let Some((key, value)) = try!(map.next_entry()) {
while let Some((key, value)) = map.next_entry()? {
values.insert(key, value);
}
@ -56,22 +60,25 @@ impl<'de, K, V, S> Visitor<'de> for OrderMapVisitor<K, V, S>
/// Requires crate feature `"serde-1"`
impl<'de, K, V, S> Deserialize<'de> for IndexMap<K, V, S>
where K: Deserialize<'de> + Eq + Hash,
V: Deserialize<'de>,
S: Default + BuildHasher
where
K: Deserialize<'de> + Eq + Hash,
V: Deserialize<'de>,
S: Default + BuildHasher,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
where
D: Deserializer<'de>,
{
deserializer.deserialize_map(OrderMapVisitor(PhantomData))
deserializer.deserialize_map(IndexMapVisitor(PhantomData))
}
}
impl<'de, K, V, S, E> IntoDeserializer<'de, E> for IndexMap<K, V, S>
where K: IntoDeserializer<'de, E> + Eq + Hash,
V: IntoDeserializer<'de, E>,
S: BuildHasher,
E: Error,
where
K: IntoDeserializer<'de, E> + Eq + Hash,
V: IntoDeserializer<'de, E>,
S: BuildHasher,
E: Error,
{
type Deserializer = MapDeserializer<'de, <Self as IntoIterator>::IntoIter, E>;
@ -80,43 +87,47 @@ impl<'de, K, V, S, E> IntoDeserializer<'de, E> for IndexMap<K, V, S>
}
}
use IndexSet;
use crate::IndexSet;
/// Requires crate feature `"serde-1"`
impl<T, S> Serialize for IndexSet<T, S>
where T: Serialize + Hash + Eq,
S: BuildHasher
where
T: Serialize + Hash + Eq,
S: BuildHasher,
{
fn serialize<Se>(&self, serializer: Se) -> Result<Se::Ok, Se::Error>
where Se: Serializer
where
Se: Serializer,
{
let mut set_serializer = try!(serializer.serialize_seq(Some(self.len())));
let mut set_serializer = serializer.serialize_seq(Some(self.len()))?;
for value in self {
try!(set_serializer.serialize_element(value));
set_serializer.serialize_element(value)?;
}
set_serializer.end()
}
}
struct OrderSetVisitor<T, S>(PhantomData<(T, S)>);
struct IndexSetVisitor<T, S>(PhantomData<(T, S)>);
impl<'de, T, S> Visitor<'de> for OrderSetVisitor<T, S>
where T: Deserialize<'de> + Eq + Hash,
S: Default + BuildHasher
impl<'de, T, S> Visitor<'de> for IndexSetVisitor<T, S>
where
T: Deserialize<'de> + Eq + Hash,
S: Default + BuildHasher,
{
type Value = IndexSet<T, S>;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(formatter, "a set")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where A: SeqAccess<'de>
where
A: SeqAccess<'de>,
{
let mut values = IndexSet::with_capacity_and_hasher(seq.size_hint().unwrap_or(0), S::default());
let mut values =
IndexSet::with_capacity_and_hasher(seq.size_hint().unwrap_or(0), S::default());
while let Some(value) = try!(seq.next_element()) {
while let Some(value) = seq.next_element()? {
values.insert(value);
}
@ -126,20 +137,23 @@ impl<'de, T, S> Visitor<'de> for OrderSetVisitor<T, S>
/// Requires crate feature `"serde-1"`
impl<'de, T, S> Deserialize<'de> for IndexSet<T, S>
where T: Deserialize<'de> + Eq + Hash,
S: Default + BuildHasher
where
T: Deserialize<'de> + Eq + Hash,
S: Default + BuildHasher,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
where
D: Deserializer<'de>,
{
deserializer.deserialize_seq(OrderSetVisitor(PhantomData))
deserializer.deserialize_seq(IndexSetVisitor(PhantomData))
}
}
impl<'de, T, S, E> IntoDeserializer<'de, E> for IndexSet<T, S>
where T: IntoDeserializer<'de, E> + Eq + Hash,
S: BuildHasher,
E: Error,
where
T: IntoDeserializer<'de, E> + Eq + Hash,
S: BuildHasher,
E: Error,
{
type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>;

713
third_party/rust/indexmap/src/set.rs поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

42
third_party/rust/indexmap/src/util.rs поставляемый
Просмотреть файл

@ -1,17 +1,39 @@
use core::iter::Enumerate;
use core::ops::{Bound, Range, RangeBounds};
use std::iter::Enumerate;
use std::mem::size_of;
pub(crate) fn third<A, B, C>(t: (A, B, C)) -> C {
t.2
}
pub fn third<A, B, C>(t: (A, B, C)) -> C { t.2 }
pub fn enumerate<I>(iterable: I) -> Enumerate<I::IntoIter>
where I: IntoIterator
pub(crate) fn enumerate<I>(iterable: I) -> Enumerate<I::IntoIter>
where
I: IntoIterator,
{
iterable.into_iter().enumerate()
}
/// return the number of steps from a to b
pub fn ptrdistance<T>(a: *const T, b: *const T) -> usize {
debug_assert!(a as usize <= b as usize);
(b as usize - a as usize) / size_of::<T>()
pub(crate) fn simplify_range<R>(range: R, len: usize) -> Range<usize>
where
R: RangeBounds<usize>,
{
let start = match range.start_bound() {
Bound::Unbounded => 0,
Bound::Included(&i) if i <= len => i,
Bound::Excluded(&i) if i < len => i + 1,
bound => panic!("range start {:?} should be <= length {}", bound, len),
};
let end = match range.end_bound() {
Bound::Unbounded => len,
Bound::Excluded(&i) if i <= len => i,
Bound::Included(&i) if i < len => i + 1,
bound => panic!("range end {:?} should be <= length {}", bound, len),
};
if start > end {
panic!(
"range start {:?} should be <= range end {:?}",
range.start_bound(),
range.end_bound()
);
}
start..end
}

Просмотреть файл

@ -1,6 +1,4 @@
#[macro_use] extern crate indexmap;
use indexmap::indexmap;
use indexmap::Equivalent;
use std::hash::Hash;
@ -9,20 +7,20 @@ use std::hash::Hash;
pub struct Pair<A, B>(pub A, pub B);
impl<A, B, C, D> PartialEq<(A, B)> for Pair<C, D>
where C: PartialEq<A>,
D: PartialEq<B>,
where
C: PartialEq<A>,
D: PartialEq<B>,
{
fn eq(&self, rhs: &(A, B)) -> bool {
self.0 == rhs.0 &&
self.1 == rhs.1 &&
true
self.0 == rhs.0 && self.1 == rhs.1
}
}
impl<A, B, X> Equivalent<X> for Pair<A, B>
where Pair<A, B>: PartialEq<X>,
A: Hash + Eq,
B: Hash + Eq,
where
Pair<A, B>: PartialEq<X>,
A: Hash + Eq,
B: Hash + Eq,
{
fn equivalent(&self, other: &X) -> bool {
*self == *other
@ -51,5 +49,5 @@ fn test_string_str() {
assert!(map.contains_key("a"));
assert!(!map.contains_key("z"));
assert_eq!(map.remove("b"), Some(2));
assert_eq!(map.swap_remove("b"), Some(2));
}

19
third_party/rust/indexmap/tests/macros_full_path.rs поставляемый Normal file
Просмотреть файл

@ -0,0 +1,19 @@
#[test]
fn test_create_map() {
let _m = indexmap::indexmap! {
1 => 2,
7 => 1,
2 => 2,
3 => 3,
};
}
#[test]
fn test_create_set() {
let _s = indexmap::indexset! {
1,
7,
2,
3,
};
}

235
third_party/rust/indexmap/tests/quick.rs поставляемый
Просмотреть файл

@ -1,48 +1,42 @@
extern crate indexmap;
extern crate itertools;
#[macro_use]
extern crate quickcheck;
extern crate rand;
extern crate fnv;
use indexmap::IndexMap;
use indexmap::{IndexMap, IndexSet};
use itertools::Itertools;
use quickcheck::quickcheck;
use quickcheck::Arbitrary;
use quickcheck::Gen;
use quickcheck::TestResult;
use rand::Rng;
use fnv::FnvHasher;
use std::hash::{BuildHasher, BuildHasherDefault};
type FnvBuilder = BuildHasherDefault<FnvHasher>;
type OrderMapFnv<K, V> = IndexMap<K, V, FnvBuilder>;
type IndexMapFnv<K, V> = IndexMap<K, V, FnvBuilder>;
use std::collections::HashSet;
use std::collections::HashMap;
use std::iter::FromIterator;
use std::hash::Hash;
use std::fmt::Debug;
use std::ops::Deref;
use std::cmp::min;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::FromIterator;
use std::ops::Bound;
use std::ops::Deref;
use indexmap::map::Entry as OEntry;
use std::collections::hash_map::Entry as HEntry;
fn set<'a, T: 'a, I>(iter: I) -> HashSet<T>
where I: IntoIterator<Item=&'a T>,
T: Copy + Hash + Eq
where
I: IntoIterator<Item = &'a T>,
T: Copy + Hash + Eq,
{
iter.into_iter().cloned().collect()
}
fn indexmap<'a, T: 'a, I>(iter: I) -> IndexMap<T, ()>
where I: IntoIterator<Item=&'a T>,
T: Copy + Hash + Eq,
where
I: IntoIterator<Item = &'a T>,
T: Copy + Hash + Eq,
{
IndexMap::from_iter(iter.into_iter().cloned().map(|k| (k, ())))
}
@ -108,7 +102,7 @@ quickcheck! {
map.capacity() >= cap
}
fn drain(insert: Vec<u8>) -> bool {
fn drain_full(insert: Vec<u8>) -> bool {
let mut map = IndexMap::new();
for &key in &insert {
map.insert(key, ());
@ -116,13 +110,82 @@ quickcheck! {
let mut clone = map.clone();
let drained = clone.drain(..);
for (key, _) in drained {
map.remove(&key);
map.swap_remove(&key);
}
map.is_empty()
}
fn drain_bounds(insert: Vec<u8>, range: (Bound<usize>, Bound<usize>)) -> TestResult {
let mut map = IndexMap::new();
for &key in &insert {
map.insert(key, ());
}
// First see if `Vec::drain` is happy with this range.
let result = std::panic::catch_unwind(|| {
let mut keys: Vec<u8> = map.keys().cloned().collect();
keys.drain(range);
keys
});
if let Ok(keys) = result {
map.drain(range);
// Check that our `drain` matches the same key order.
assert!(map.keys().eq(&keys));
// Check that hash lookups all work too.
assert!(keys.iter().all(|key| map.contains_key(key)));
TestResult::passed()
} else {
// If `Vec::drain` panicked, so should we.
TestResult::must_fail(move || { map.drain(range); })
}
}
fn shift_remove(insert: Vec<u8>, remove: Vec<u8>) -> bool {
let mut map = IndexMap::new();
for &key in &insert {
map.insert(key, ());
}
for &key in &remove {
map.shift_remove(&key);
}
let elements = &set(&insert) - &set(&remove);
// Check that order is preserved after removals
let mut iter = map.keys();
for &key in insert.iter().unique() {
if elements.contains(&key) {
assert_eq!(Some(key), iter.next().cloned());
}
}
map.len() == elements.len() && map.iter().count() == elements.len() &&
elements.iter().all(|k| map.get(k).is_some())
}
fn indexing(insert: Vec<u8>) -> bool {
let mut map: IndexMap<_, _> = insert.into_iter().map(|x| (x, x)).collect();
let set: IndexSet<_> = map.keys().cloned().collect();
assert_eq!(map.len(), set.len());
for (i, &key) in set.iter().enumerate() {
assert_eq!(map.get_index(i), Some((&key, &key)));
assert_eq!(set.get_index(i), Some(&key));
assert_eq!(map[i], key);
assert_eq!(set[i], key);
*map.get_index_mut(i).unwrap().1 >>= 1;
map[i] <<= 1;
}
set.iter().enumerate().all(|(i, &key)| {
let value = key & !1;
map[&key] == value && map[i] == value
})
}
}
use Op::*;
use crate::Op::*;
#[derive(Copy, Clone, Debug)]
enum Op<K, V> {
Add(K, V),
@ -132,8 +195,9 @@ enum Op<K, V> {
}
impl<K, V> Arbitrary for Op<K, V>
where K: Arbitrary,
V: Arbitrary,
where
K: Arbitrary,
V: Arbitrary,
{
fn arbitrary<G: Gen>(g: &mut G) -> Self {
match g.gen::<u32>() % 4 {
@ -146,9 +210,10 @@ impl<K, V> Arbitrary for Op<K, V>
}
fn do_ops<K, V, S>(ops: &[Op<K, V>], a: &mut IndexMap<K, V, S>, b: &mut HashMap<K, V>)
where K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher,
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher,
{
for op in ops {
match *op {
@ -157,21 +222,19 @@ fn do_ops<K, V, S>(ops: &[Op<K, V>], a: &mut IndexMap<K, V, S>, b: &mut HashMap<
b.insert(k.clone(), v.clone());
}
AddEntry(ref k, ref v) => {
a.entry(k.clone()).or_insert(v.clone());
b.entry(k.clone()).or_insert(v.clone());
a.entry(k.clone()).or_insert_with(|| v.clone());
b.entry(k.clone()).or_insert_with(|| v.clone());
}
Remove(ref k) => {
a.swap_remove(k);
b.remove(k);
}
RemoveEntry(ref k) => {
match a.entry(k.clone()) {
OEntry::Occupied(ent) => { ent.remove_entry(); },
_ => { }
if let OEntry::Occupied(ent) = a.entry(k.clone()) {
ent.swap_remove_entry();
}
match b.entry(k.clone()) {
HEntry::Occupied(ent) => { ent.remove_entry(); },
_ => { }
if let HEntry::Occupied(ent) = b.entry(k.clone()) {
ent.remove_entry();
}
}
}
@ -180,8 +243,9 @@ fn do_ops<K, V, S>(ops: &[Op<K, V>], a: &mut IndexMap<K, V, S>, b: &mut HashMap<
}
fn assert_maps_equivalent<K, V>(a: &IndexMap<K, V>, b: &HashMap<K, V>) -> bool
where K: Hash + Eq + Debug,
V: Eq + Debug,
where
K: Hash + Eq + Debug,
V: Eq + Debug,
{
assert_eq!(a.len(), b.len());
assert_eq!(a.iter().next().is_some(), b.iter().next().is_some());
@ -252,7 +316,7 @@ quickcheck! {
ops2.remove(i);
}
}
let mut map2 = OrderMapFnv::default();
let mut map2 = IndexMapFnv::default();
let mut reference2 = HashMap::new();
do_ops(&ops2, &mut map2, &mut reference2);
assert_eq!(map == map2, reference == reference2);
@ -307,13 +371,67 @@ quickcheck! {
map.sort_by(|_, v1, _, v2| Ord::cmp(v1, v2));
assert_sorted_by_key(map, |t| t.1);
}
fn reverse(keyvals: Large<Vec<(i8, i8)>>) -> () {
let mut map: IndexMap<_, _> = IndexMap::from_iter(keyvals.to_vec());
fn generate_answer(input: &Vec<(i8, i8)>) -> Vec<(i8, i8)> {
// to mimic what `IndexMap::from_iter` does:
// need to get (A) the unique keys in forward order, and (B) the
// last value of each of those keys.
// create (A): an iterable that yields the unique keys in ltr order
let mut seen_keys = HashSet::new();
let unique_keys_forward = input.iter().filter_map(move |(k, _)| {
if seen_keys.contains(k) { None }
else { seen_keys.insert(*k); Some(*k) }
});
// create (B): a mapping of keys to the last value seen for that key
// this is the same as reversing the input and taking the first
// value seen for that key!
let mut last_val_per_key = HashMap::new();
for &(k, v) in input.iter().rev() {
if !last_val_per_key.contains_key(&k) {
last_val_per_key.insert(k, v);
}
}
// iterate over the keys in (A) in order, and match each one with
// the corresponding last value from (B)
let mut ans: Vec<_> = unique_keys_forward
.map(|k| (k, *last_val_per_key.get(&k).unwrap()))
.collect();
// finally, since this test is testing `.reverse()`, reverse the
// answer in-place
ans.reverse();
ans
}
let answer = generate_answer(&keyvals.0);
// perform the work
map.reverse();
// check it contains all the values it should
for &(key, val) in &answer {
assert_eq!(map[&key], val);
}
// check the order
let mapv = Vec::from_iter(map);
assert_eq!(answer, mapv);
}
}
fn assert_sorted_by_key<I, Key, X>(iterable: I, key: Key)
where I: IntoIterator,
I::Item: Ord + Clone + Debug,
Key: Fn(&I::Item) -> X,
X: Ord,
where
I: IntoIterator,
I::Item: Ord + Clone + Debug,
Key: Fn(&I::Item) -> X,
X: Ord,
{
let input = Vec::from_iter(iterable);
let mut sorted = input.clone();
@ -326,21 +444,25 @@ struct Alpha(String);
impl Deref for Alpha {
type Target = String;
fn deref(&self) -> &String { &self.0 }
fn deref(&self) -> &String {
&self.0
}
}
const ALPHABET: &'static [u8] = b"abcdefghijklmnopqrstuvwxyz";
const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
impl Arbitrary for Alpha {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let len = g.next_u32() % g.size() as u32;
let len = min(len, 16);
Alpha((0..len).map(|_| {
ALPHABET[g.next_u32() as usize % ALPHABET.len()] as char
}).collect())
Alpha(
(0..len)
.map(|_| ALPHABET[g.next_u32() as usize % ALPHABET.len()] as char)
.collect(),
)
}
fn shrink(&self) -> Box<Iterator<Item=Self>> {
fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
Box::new((**self).shrink().map(Alpha))
}
}
@ -351,18 +473,21 @@ struct Large<T>(T);
impl<T> Deref for Large<T> {
type Target = T;
fn deref(&self) -> &T { &self.0 }
fn deref(&self) -> &T {
&self.0
}
}
impl<T> Arbitrary for Large<Vec<T>>
where T: Arbitrary
where
T: Arbitrary,
{
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let len = g.next_u32() % (g.size() * 10) as u32;
Large((0..len).map(|_| T::arbitrary(g)).collect())
}
fn shrink(&self) -> Box<Iterator<Item=Self>> {
fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
Box::new((**self).shrink().map(Large))
}
}

59
third_party/rust/indexmap/tests/serde.rs поставляемый
Просмотреть файл

@ -1,59 +0,0 @@
#![cfg(feature = "serde-1")]
#[macro_use]
extern crate indexmap;
extern crate serde_test;
extern crate fnv;
use serde_test::{Token, assert_tokens};
#[test]
fn test_serde() {
let map = indexmap! { 1 => 2, 3 => 4 };
assert_tokens(&map,
&[Token::Map { len: Some(2) },
Token::I32(1),
Token::I32(2),
Token::I32(3),
Token::I32(4),
Token::MapEnd]);
}
#[test]
fn test_serde_set() {
let set = indexset! { 1, 2, 3, 4 };
assert_tokens(&set,
&[Token::Seq { len: Some(4) },
Token::I32(1),
Token::I32(2),
Token::I32(3),
Token::I32(4),
Token::SeqEnd]);
}
#[test]
fn test_serde_fnv_hasher() {
let mut map: ::indexmap::IndexMap<i32, i32, ::fnv::FnvBuildHasher> = Default::default();
map.insert(1, 2);
map.insert(3, 4);
assert_tokens(&map,
&[Token::Map { len: Some(2) },
Token::I32(1),
Token::I32(2),
Token::I32(3),
Token::I32(4),
Token::MapEnd]);
}
#[test]
fn test_serde_map_fnv_hasher() {
let mut set: ::indexmap::IndexSet<i32, ::fnv::FnvBuildHasher> = Default::default();
set.extend(1..5);
assert_tokens(&set,
&[Token::Seq { len: Some(4) },
Token::I32(1),
Token::I32(2),
Token::I32(3),
Token::I32(4),
Token::SeqEnd]);
}

16
third_party/rust/indexmap/tests/tests.rs поставляемый
Просмотреть файл

@ -1,8 +1,4 @@
#[macro_use]
extern crate indexmap;
extern crate itertools;
use indexmap::{indexmap, indexset};
#[test]
fn test_sort() {
@ -13,11 +9,12 @@ fn test_sort() {
3 => 3,
};
itertools::assert_equal(m.sorted_by(|_k1, v1, _k2, v2| v1.cmp(v2)),
vec![(7, 1), (1, 2), (2, 2), (3, 3)]);
itertools::assert_equal(
m.sorted_by(|_k1, v1, _k2, v2| v1.cmp(v2)),
vec![(7, 1), (1, 2), (2, 2), (3, 3)],
);
}
#[test]
fn test_sort_set() {
let s = indexset! {
@ -27,6 +24,5 @@ fn test_sort_set() {
3,
};
itertools::assert_equal(s.sorted_by(|v1, v2| v1.cmp(v2)),
vec![1, 2, 3, 7]);
itertools::assert_equal(s.sorted_by(|v1, v2| v1.cmp(v2)), vec![1, 2, 3, 7]);
}