Merge branch 'benma-agent/prost-size-update'
What changed, and why it matters
This commit is a large dependency update for the BitBox02 firmware, primarily updating the vendored Rust 'prost' protobuf library and related crates. It removes old vendored copies of 'concurrent-queue' and 'crossbeam-utils' and updates generated protobuf code. The commit itself does not describe any security fix, and the visible diff does not show a clear, exploitable vulnerability. It appears to be routine maintenance to keep dependencies current and reduce vendored code size.
Treat as a routine dependency refresh. Review the upstream prost release notes and the new vendored dependency versions for any security advisories. Run the project's firmware test suite and simulator tests to ensure the regenerated protobuf bindings remain compatible. If this update was triggered by a known advisory, request the corresponding CVE/advisory URL and verify the fix version.
Security signals we found
Large dependency update/removal in external/vendor/
Update of prost protobuf library and regenerated bindings
Removal of concurrent-queue and crossbeam-utils vendored sources
No explicit security mention in commit title or message
No CVE or advisory referenced in commit materials
Evidence from the diff
The merge commit ‘benma-agent/prost-size-update’ updates vendored Rust dependencies in external/vendor/, regenerates protobuf Rust bindings under src/rust/bitbox-proto/src/generated/, and refreshes Cargo.lock files. The old versions of ‘concurrent-queue’ (2.5.0) and ‘crossbeam-utils’ (0.8.21) are removed entirely, while ‘prost’ and ‘prost-derive’ are updated. The AGENTS.md documentation is updated to mention the vendor-rust.sh script. No explicit security fix, CVE, or researcher attribution is present in the commit message or diff. The change is broad but mechanical, and without the full new dependency contents or upstream release notes, we cannot confirm it addresses a specific security issue.
Changed components
external/vendor/prostexternal/vendor/prost-derivesrc/rust/bitbox-proto/src/generated/shiftcrypto.bitbox02.rssrc/rust/bitbox-proto/src/generated/shiftcrypto.bitbox02.backups.rssrc/rust/Cargo.locksrc/rust/bitbox-proto/Cargo.tomlsrc/rust/bitbox02-rust/Cargo.tomlInspect captured patch +2513 / −10734
### .containerversion
@@ -1 +1 @@
-57
+58
### AGENTS.md
@@ -6,6 +6,7 @@ Core firmware and bootloader code sits in `src/`, grouped by subsystem (`bootloa
`hardware-fakes/` for device shims, and `simulator/` assets. The BitB02 Python client library is in
`py/bitbox02`. Supporting tooling is in `scripts/` (CI, J-Link macros), and `doc/` for
manuals. Vendored dependencies are tracked in `external/`.
+For Rust dependencies, run `./external/vendor-rust.sh` to update `external/vendor/`.
The firmware has C and Rust code. Rust code lives in src/rust. The most important rust crates are:
- bitbox02-rust: the main app logic. It can expose functions to C using extern "C". If it needs
### external/vendor/concurrent-queue/.cargo-checksum.json
@@ -1 +0,0 @@
-{"files":{".cargo_vcs_info.json":"a70c1490e6daa375beb4928e5f4f97a6d9d6ba215fb4ff8b03ebc02a58a16439","CHANGELOG.md":"e9a4a11edce8b62146fdade24e1a74ee624601b2efcaa7035359c464a1ff7ff7","Cargo.toml":"d14f713829a83746178dd8a52732e1d106c895b3b4370bb9436fb190a2d763b2","Cargo.toml.orig":"18cfe5d32e53cdd29e2566612323ba36657b9cf2de41f7fae2a13e3880b9f458","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"d7a326783ef72b063a5a237b8c64e209e80fe61b9dda20e4686b5d8b19b16fb1","benches/bench.rs":"6bac7fcdfbd1b1caa2b36089a347fb120091b95ca7bd399249a96f1271e1bf08","src/bounded.rs":"f161cc0e03f59cc764a44dc0782f7fcef7325fc328dfc8cb8c7fd608fc259cc8","src/lib.rs":"dc69f8a48cc28fe73ea1be88d77cd1aba98947d5a673019e61c630cc04c537ad","src/single.rs":"610671ffb6f3b3bc9d375b99f4e004c61eece74caa29c2a3af6977d4764185f4","src/sync.rs":"7dc9bba96eda875ee3a1e5b808e4e2317cdd03293a38492a214e26e538159eef","src/unbounded.rs":"e90ea841f3f1eac5503b1c3cd2949de64956fc6a164ca65150c6c2bba02d0e16","tests/bounded.rs":"07a357eae995a79c5b6ac586037a86ed49df754ef3893d16891dc3c686299c6b","tests/loom.rs":"63e40d2598f80c97cada351c8db9c8d5e79d97bae870bdf9fe510d2b21510616","tests/single.rs":"7866f94d1c350e9a860aab550165806a8422649845ac6e9c95045886ce3e7659","tests/unbounded.rs":"3f49e41c33c14ab7ac255ef48c0af4f0f1cfcc9352fc73f21918df3039ff10d9"},"package":"4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"}
\ No newline at end of file
### external/vendor/concurrent-queue/.cargo_vcs_info.json
@@ -1,6 +0,0 @@
-{
- "git": {
- "sha1": "e874f701f8413de01948c4903f894e5c845d8950"
- },
- "path_in_vcs": ""
-}
\ No newline at end of file
### external/vendor/concurrent-queue/CHANGELOG.md
@@ -1,69 +0,0 @@
-# Version 2.5.0
-
-- Add a `force_push` method that can be used to add an element to the queue by displacing another. (#58)
-- Make `ConcurrentQueue::unbounded()` into a `const` function. (#67)
-- Fix a compilation error in the Loom implementation. (#65)
-
-# Version 2.4.0
-
-- Remove unnecessary heap allocations from inside of the `ConcurrentQueue` type. (#53)
-
-# Version 2.3.0
-
-- Implement `UnwindSafe` without libstd. (#49)
-- Bump `fastrand` to `v2.0.0`. (#43)
-- Use inline assembly in the `full_fence` funtion. (#47)
-
-# Version 2.2.0
-
-- Add the try_iter method. (#36)
-
-# Version 2.1.0
-
-- Update `portable-atomic` to 1.0. (#33)
-
-# Version 2.0.0
-
-- Add support for the `portable-atomic` and `loom` crates. (#27)
-- **Breaking:** Add an `std` feature that can be disabled to use this crate on `no_std` platforms. (#22)
-- Replace usage of `cache-padded` with `crossbeam-utils`. (#26)
-
-# Version 1.2.4
-
-- Fix fence on x86 and miri. (#18)
-- Revert 1.2.3. (#18)
-
-# Version 1.2.3
-
-**Note:** This release has been yanked, see #17 for details.
-
-- Fix fence on non-x86 architectures and miri. (#16)
-
-# Version 1.2.2
-
-- Add a special, efficient `bounded(1)` implementation.
-
-# Version 1.2.1
-
-- In the bounded queue, use boxed slice instead of raw pointers.
-
-# Version 1.2.0
-
-- Update dependencies.
-- Implement `UnwindSafe` and `RefUnwindSafe` for `ConcurrentQueue`.
-
-# Version 1.1.2
-
-- Optimize `SeqCst` fences.
-
-# Version 1.1.1
-
-- Clarify errors in docs.
-
-# Version 1.1.0
-
-- Add extra methods to error types.
-
-# Version 1.0.0
-
-- Initial version
### external/vendor/concurrent-queue/Cargo.toml
@@ -1,72 +0,0 @@
-# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
-#
-# When uploading crates to the registry Cargo will automatically
-# "normalize" Cargo.toml files for maximal compatibility
-# with all versions of Cargo and also rewrite `path` dependencies
-# to registry (e.g., crates.io) dependencies.
-#
-# If you are reading this file be aware that the original Cargo.toml
-# will likely look very different (and much more reasonable).
-# See Cargo.toml.orig for the original contents.
-
-[package]
-edition = "2021"
-rust-version = "1.60"
-name = "concurrent-queue"
-version = "2.5.0"
-authors = [
- "Stjepan Glavina <stjepang@gmail.com>",
- "Taiki Endo <te316e89@gmail.com>",
- "John Nunley <dev@notgull.net>",
-]
-exclude = ["/.*"]
-description = "Concurrent multi-producer multi-consumer queue"
-readme = "README.md"
-keywords = [
- "channel",
- "mpmc",
- "spsc",
- "spmc",
- "mpsc",
-]
-categories = ["concurrency"]
-license = "Apache-2.0 OR MIT"
-repository = "https://github.com/smol-rs/concurrent-queue"
-
-[lib]
-bench = false
-
-[[bench]]
-name = "bench"
-harness = false
-
-[dependencies.crossbeam-utils]
-version = "0.8.11"
-default-features = false
-
-[dependencies.portable-atomic]
-version = "1"
-optional = true
-default-features = false
-
-[dev-dependencies.criterion]
-version = "0.5"
-features = ["cargo_bench_support"]
-default-features = false
-
-[dev-dependencies.easy-parallel]
-version = "3.1.0"
-
-[dev-dependencies.fastrand]
-version = "2.0.0"
-
-[features]
-default = ["std"]
-std = []
-
-[target."cfg(loom)".dependencies.loom]
-version = "0.7"
-optional = true
-
-[target."cfg(target_family = \"wasm\")".dev-dependencies.wasm-bindgen-test]
-version = "0.3"
### external/vendor/concurrent-queue/Cargo.toml.orig
@@ -1,47 +0,0 @@
-[package]
-name = "concurrent-queue"
-# When publishing a new version:
-# - Update CHANGELOG.md
-# - Create "v2.x.y" git tag
-version = "2.5.0"
-authors = [
- "Stjepan Glavina <stjepang@gmail.com>",
- "Taiki Endo <te316e89@gmail.com>",
- "John Nunley <dev@notgull.net>"
-]
-edition = "2021"
-rust-version = "1.60"
-description = "Concurrent multi-producer multi-consumer queue"
-license = "Apache-2.0 OR MIT"
-repository = "https://github.com/smol-rs/concurrent-queue"
-keywords = ["channel", "mpmc", "spsc", "spmc", "mpsc"]
-categories = ["concurrency"]
-exclude = ["/.*"]
-
-[lib]
-bench = false
-
-[dependencies]
-crossbeam-utils = { version = "0.8.11", default-features = false }
-portable-atomic = { version = "1", default-features = false, optional = true }
-
-# Enables loom testing. This feature is permanently unstable and the API may
-# change at any time.
-[target.'cfg(loom)'.dependencies]
-loom = { version = "0.7", optional = true }
-
-[[bench]]
-name = "bench"
-harness = false
-
-[dev-dependencies]
-criterion = { version = "0.5", features = ["cargo_bench_support"], default-features = false }
-easy-parallel = "3.1.0"
-fastrand = "2.0.0"
-
-[target.'cfg(target_family = "wasm")'.dev-dependencies]
-wasm-bindgen-test = "0.3"
-
-[features]
-default = ["std"]
-std = []
### external/vendor/concurrent-queue/LICENSE-APACHE
@@ -1,201 +0,0 @@
- 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.
### external/vendor/concurrent-queue/LICENSE-MIT
@@ -1,23 +0,0 @@
-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.
### external/vendor/concurrent-queue/README.md
@@ -1,51 +0,0 @@
-# concurrent-queue
-
-[](
-https://github.com/smol-rs/concurrent-queue/actions)
-[](
-https://github.com/smol-rs/concurrent-queue)
-[](
-https://crates.io/crates/concurrent-queue)
-[](
-https://docs.rs/concurrent-queue)
-
-A concurrent multi-producer multi-consumer queue.
-
-There are two kinds of queues:
-
-1. Bounded queue with limited capacity.
-2. Unbounded queue with unlimited capacity.
-
-Queues also have the capability to get closed at any point. When closed, no more items can be
-pushed into the queue, although the remaining items can still be popped.
-
-These features make it easy to build channels similar to `std::sync::mpsc` on top of this
-crate.
-
-## Examples
-
-```rust
-use concurrent_queue::ConcurrentQueue;
-
-let q = ConcurrentQueue::unbounded();
-q.push(1).unwrap();
-q.push(2).unwrap();
-
-assert_eq!(q.pop(), Ok(1));
-assert_eq!(q.pop(), Ok(2));
-```
-
-## License
-
-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.
-
-#### Contribution
-
-Unless you explicitly state otherwise, any contribution intentionally submitted
-for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
-dual licensed as above, without any additional terms or conditions.
### external/vendor/concurrent-queue/benches/bench.rs
@@ -1,93 +0,0 @@
-use std::{any::type_name, fmt::Debug};
-
-use concurrent_queue::{ConcurrentQueue, PopError};
-use criterion::{black_box, criterion_group, criterion_main, Criterion};
-use easy_parallel::Parallel;
-
-const COUNT: usize = 100_000;
-const THREADS: usize = 7;
-
-fn spsc<T: Default + std::fmt::Debug + Send>(recv: &ConcurrentQueue<T>, send: &ConcurrentQueue<T>) {
- Parallel::new()
- .add(|| loop {
- match recv.pop() {
- Ok(_) => (),
- Err(PopError::Empty) => (),
- Err(PopError::Closed) => break,
- }
- })
- .add(|| {
- for _ in 0..COUNT {
- send.push(T::default()).unwrap();
- }
- send.close();
- })
- .run();
-}
-
-fn mpsc<T: Default + std::fmt::Debug + Send>(recv: &ConcurrentQueue<T>, send: &ConcurrentQueue<T>) {
- Parallel::new()
- .each(0..THREADS, |_| {
- for _ in 0..COUNT {
- send.push(T::default()).unwrap();
- }
- })
- .add(|| {
- let mut recieved = 0;
- while recieved < THREADS * COUNT {
- match recv.pop() {
- Ok(_) => recieved += 1,
- Err(PopError::Empty) => (),
- Err(PopError::Closed) => unreachable!(),
- }
- }
- })
- .run();
-}
-
-fn single_thread<T: Default + std::fmt::Debug>(
- recv: &ConcurrentQueue<T>,
- send: &ConcurrentQueue<T>,
-) {
- for _ in 0..COUNT {
- send.push(T::default()).unwrap();
- }
- for _ in 0..COUNT {
- recv.pop().unwrap();
- }
-}
-
-// Because we can't pass generic functions as const parameters.
-macro_rules! bench_all(
- ($name:ident, $f:ident) => {
- fn $name(c: &mut Criterion) {
- fn helper<T: Default + Debug + Send>(c: &mut Criterion) {
- let name = format!("unbounded_{}_{}", stringify!($f), type_name::<T>());
-
- c.bench_function(&name, |b| b.iter(|| {
- let q = ConcurrentQueue::unbounded();
- $f::<T>(black_box(&q), black_box(&q));
- }));
-
- let name = format!("bounded_{}_{}", stringify!($f), type_name::<T>());
-
- c.bench_function(&name, |b| b.iter(|| {
- let q = ConcurrentQueue::bounded(THREADS * COUNT);
- $f::<T>(black_box(&q), black_box(&q));
- }));
- }
- helper::<u8>(c);
- helper::<u16>(c);
- helper::<u32>(c);
- helper::<u64>(c);
- helper::<u128>(c);
- }
- }
-);
-
-bench_all!(bench_spsc, spsc);
-bench_all!(bench_mpsc, mpsc);
-bench_all!(bench_single_thread, single_thread);
-
-criterion_group!(generic_group, bench_single_thread, bench_spsc, bench_mpsc);
-criterion_main!(generic_group);
### external/vendor/concurrent-queue/src/bounded.rs
@@ -1,408 +0,0 @@
-use alloc::{boxed::Box, vec::Vec};
-use core::mem::MaybeUninit;
-
-use crossbeam_utils::CachePadded;
-
-use crate::sync::atomic::{AtomicUsize, Ordering};
-use crate::sync::cell::UnsafeCell;
-#[allow(unused_imports)]
-use crate::sync::prelude::*;
-use crate::{busy_wait, ForcePushError, PopError, PushError};
-
-/// A slot in a queue.
-struct Slot<T> {
- /// The current stamp.
- stamp: AtomicUsize,
-
- /// The value in this slot.
- value: UnsafeCell<MaybeUninit<T>>,
-}
-
-/// A bounded queue.
-pub struct Bounded<T> {
- /// The head of the queue.
- ///
- /// This value is a "stamp" consisting of an index into the buffer, a mark bit, and a lap, but
- /// packed into a single `usize`. The lower bits represent the index, while the upper bits
- /// represent the lap. The mark bit in the head is always zero.
- ///
- /// Values are popped from the head of the queue.
- head: CachePadded<AtomicUsize>,
-
- /// The tail of the queue.
- ///
- /// This value is a "stamp" consisting of an index into the buffer, a mark bit, and a lap, but
- /// packed into a single `usize`. The lower bits represent the index, while the upper bits
- /// represent the lap. The mark bit indicates that the queue is closed.
- ///
- /// Values are pushed into the tail of the queue.
- tail: CachePadded<AtomicUsize>,
-
- /// The buffer holding slots.
- buffer: Box<[Slot<T>]>,
-
- /// A stamp with the value of `{ lap: 1, mark: 0, index: 0 }`.
- one_lap: usize,
-
- /// If this bit is set in the tail, that means the queue is closed.
- mark_bit: usize,
-}
-
-impl<T> Bounded<T> {
- /// Creates a new bounded queue.
- pub fn new(cap: usize) -> Bounded<T> {
- assert!(cap > 0, "capacity must be positive");
-
- // Head is initialized to `{ lap: 0, mark: 0, index: 0 }`.
- let head = 0;
- // Tail is initialized to `{ lap: 0, mark: 0, index: 0 }`.
- let tail = 0;
-
- // Allocate a buffer of `cap` slots initialized with stamps.
- let mut buffer = Vec::with_capacity(cap);
- for i in 0..cap {
- // Set the stamp to `{ lap: 0, mark: 0, index: i }`.
- buffer.push(Slot {
- stamp: AtomicUsize::new(i),
- value: UnsafeCell::new(MaybeUninit::uninit()),
- });
- }
-
- // Compute constants `mark_bit` and `one_lap`.
- let mark_bit = (cap + 1).next_power_of_two();
- let one_lap = mark_bit * 2;
-
- Bounded {
- buffer: buffer.into(),
- one_lap,
- mark_bit,
- head: CachePadded::new(AtomicUsize::new(head)),
- tail: CachePadded::new(AtomicUsize::new(tail)),
- }
- }
-
- /// Attempts to push an item into the queue.
- pub fn push(&self, value: T) -> Result<(), PushError<T>> {
- self.push_or_else(value, |value, tail, _, _| {
- let head = self.head.load(Ordering::Relaxed);
-
- // If the head lags one lap behind the tail as well...
- if head.wrapping_add(self.one_lap) == tail {
- // ...then the queue is full.
- Err(PushError::Full(value))
- } else {
- Ok(value)
- }
- })
- }
-
- /// Pushes an item into the queue, displacing another item if needed.
- pub fn force_push(&self, value: T) -> Result<Option<T>, ForcePushError<T>> {
- let result = self.push_or_else(value, |value, tail, new_tail, slot| {
- let head = tail.wrapping_sub(self.one_lap);
- let new_head = new_tail.wrapping_sub(self.one_lap);
-
- // Try to move the head.
- if self
- .head
- .compare_exchange_weak(head, new_head, Ordering::SeqCst, Ordering::Relaxed)
- .is_ok()
- {
- // Move the tail.
- self.tail.store(new_tail, Ordering::SeqCst);
-
- // Swap out the old value.
- // SAFETY: We know this is initialized, since it's covered by the current queue.
- let old = unsafe {
- slot.value
- .with_mut(|slot| slot.replace(MaybeUninit::new(value)).assume_init())
- };
-
- // Update the stamp.
- slot.stamp.store(tail + 1, Ordering::Release);
-
- // Return a PushError.
- Err(PushError::Full(old))
- } else {
- Ok(value)
- }
- });
-
- match result {
- Ok(()) => Ok(None),
- Err(PushError::Full(old_value)) => Ok(Some(old_value)),
- Err(PushError::Closed(value)) => Err(ForcePushError(value)),
- }
- }
-
- /// Attempts to push an item into the queue, running a closure on failure.
- ///
- /// `fail` is run when there is no more room left in the tail of the queue. The parameters of
- /// this function are as follows:
- ///
- /// - The item that failed to push.
- /// - The value of `self.tail` before the new value would be inserted.
- /// - The value of `self.tail` after the new value would be inserted.
- /// - The slot that we attempted to push into.
- ///
- /// If `fail` returns `Ok(val)`, we will try pushing `val` to the head of the queue. Otherwise,
- /// this function will return the error.
- fn push_or_else<F>(&self, mut value: T, mut fail: F) -> Result<(), PushError<T>>
- where
- F: FnMut(T, usize, usize, &Slot<T>) -> Result<T, PushError<T>>,
- {
- let mut tail = self.tail.load(Ordering::Relaxed);
-
- loop {
- // Check if the queue is closed.
- if tail & self.mark_bit != 0 {
- return Err(PushError::Closed(value));
- }
-
- // Deconstruct the tail.
- let index = tail & (self.mark_bit - 1);
- let lap = tail & !(self.one_lap - 1);
-
- // Calculate the new location of the tail.
- let new_tail = if index + 1 < self.buffer.len() {
- // Same lap, incremented index.
- // Set to `{ lap: lap, mark: 0, index: index + 1 }`.
- tail + 1
- } else {
- // One lap forward, index wraps around to zero.
- // Set to `{ lap: lap.wrapping_add(1), mark: 0, index: 0 }`.
- lap.wrapping_add(self.one_lap)
- };
-
- // Inspect the corresponding slot.
- let slot = &self.buffer[index];
- let stamp = slot.stamp.load(Ordering::Acquire);
-
- // If the tail and the stamp match, we may attempt to push.
- if tail == stamp {
- // Try moving the tail.
- match self.tail.compare_exchange_weak(
- tail,
- new_tail,
- Ordering::SeqCst,
- Ordering::Relaxed,
- ) {
- Ok(_) => {
- // Write the value into the slot and update the stamp.
- slot.value.with_mut(|slot| unsafe {
- slot.write(MaybeUninit::new(value));
- });
- slot.stamp.store(tail + 1, Ordering::Release);
- return Ok(());
- }
- Err(t) => {
- tail = t;
- }
- }
- } else if stamp.wrapping_add(self.one_lap) == tail + 1 {
- crate::full_fence();
-
- // We've failed to push; run our failure closure.
- value = fail(value, tail, new_tail, slot)?;
-
- // Loom complains if there isn't an explicit busy wait here.
- #[cfg(loom)]
- busy_wait();
-
- tail = self.tail.load(Ordering::Relaxed);
- } else {
- // Yield because we need to wait for the stamp to get updated.
- busy_wait();
- tail = self.tail.load(Ordering::Relaxed);
- }
- }
- }
-
- /// Attempts to pop an item from the queue.
- pub fn pop(&self) -> Result<T, PopError> {
- let mut head = self.head.load(Ordering::Relaxed);
-
- loop {
- // Deconstruct the head.
- let index = head & (self.mark_bit - 1);
- let lap = head & !(self.one_lap - 1);
-
- // Inspect the corresponding slot.
- let slot = &self.buffer[index];
- let stamp = slot.stamp.load(Ordering::Acquire);
-
- // If the the stamp is ahead of the head by 1, we may attempt to pop.
- if head + 1 == stamp {
- let new = if index + 1 < self.buffer.len() {
- // Same lap, incremented index.
- // Set to `{ lap: lap, mark: 0, index: index + 1 }`.
- head + 1
- } else {
- // One lap forward, index wraps around to zero.
- // Set to `{ lap: lap.wrapping_add(1), mark: 0, index: 0 }`.
- lap.wrapping_add(self.one_lap)
- };
-
- // Try moving the head.
- match self.head.compare_exchange_weak(
- head,
- new,
- Ordering::SeqCst,
- Ordering::Relaxed,
- ) {
- Ok(_) => {
- // Read the value from the slot and update the stamp.
- let value = slot
- .value
- .with_mut(|slot| unsafe { slot.read().assume_init() });
- slot.stamp
- .store(head.wrapping_add(self.one_lap), Ordering::Release);
- return Ok(value);
- }
- Err(h) => {
- head = h;
- }
- }
- } else if stamp == head {
- crate::full_fence();
- let tail = self.tail.load(Ordering::Relaxed);
-
- // If the tail equals the head, that means the queue is empty.
- if (tail & !self.mark_bit) == head {
- // Check if the queue is closed.
- if tail & self.mark_bit != 0 {
- return Err(PopError::Closed);
- } else {
- return Err(PopError::Empty);
- }
- }
-
- // Loom complains if there isn't a busy-wait here.
- #[cfg(loom)]
- busy_wait();
-
- head = self.head.load(Ordering::Relaxed);
- } else {
- // Yield because we need to wait for the stamp to get updated.
- busy_wait();
- head = self.head.load(Ordering::Relaxed);
- }
- }
- }
-
- /// Returns the number of items in the queue.
- pub fn len(&self) -> usize {
- loop {
- // Load the tail, then load the head.
- let tail = self.tail.load(Ordering::SeqCst);
- let head = self.head.load(Ordering::SeqCst);
-
- // If the tail didn't change, we've got consistent values to work with.
- if self.tail.load(Ordering::SeqCst) == tail {
- let hix = head & (self.mark_bit - 1);
- let tix = tail & (self.mark_bit - 1);
-
- return if hix < tix {
- tix - hix
- } else if hix > tix {
- self.buffer.len() - hix + tix
- } else if (tail & !self.mark_bit) == head {
- 0
- } else {
- self.buffer.len()
- };
- }
- }
- }
-
- /// Returns `true` if the queue is empty.
- pub fn is_empty(&self) -> bool {
- let head = self.head.load(Ordering::SeqCst);
- let tail = self.tail.load(Ordering::SeqCst);
-
- // Is the tail equal to the head?
- //
- // Note: If the head changes just before we load the tail, that means there was a moment
- // when the queue was not empty, so it is safe to just return `false`.
- (tail & !self.mark_bit) == head
- }
-
- /// Returns `true` if the queue is full.
- pub fn is_full(&self) -> bool {
- let tail = self.tail.load(Ordering::SeqCst);
- let head = self.head.load(Ordering::SeqCst);
-
- // Is the head lagging one lap behind tail?
- //
- // Note: If the tail changes just before we load the head, that means there was a moment
- // when the queue was not full, so it is safe to just return `false`.
- head.wrapping_add(self.one_lap) == tail & !self.mark_bit
- }
-
- /// Returns the capacity of the queue.
- pub fn capacity(&self) -> usize {
- self.buffer.len()
- }
-
- /// Closes the queue.
- ///
- /// Returns `true` if this call closed the queue.
- pub fn close(&self) -> bool {
- let tail = self.tail.fetch_or(self.mark_bit, Ordering::SeqCst);
- tail & self.mark_bit == 0
- }
-
- /// Returns `true` if the queue is closed.
- pub fn is_closed(&self) -> bool {
- self.tail.load(Ordering::SeqCst) & self.mark_bit != 0
- }
-}
-
-impl<T> Drop for Bounded<T> {
- fn drop(&mut self) {
- // Get the index of the head.
- let Self {
- head,
- tail,
- buffer,
- mark_bit,
- ..
- } = self;
-
- let mark_bit = *mark_bit;
-
- head.with_mut(|&mut head| {
- tail.with_mut(|&mut tail| {
- let hix = head & (mark_bit - 1);
- let tix = tail & (mark_bit - 1);
-
- let len = if hix < tix {
- tix - hix
- } else if hix > tix {
- buffer.len() - hix + tix
- } else if (tail & !mark_bit) == head {
- 0
- } else {
- buffer.len()
- };
-
- // Loop over all slots that hold a value and drop them.
- for i in 0..len {
- // Compute the index of the next slot holding a value.
- let index = if hix + i < buffer.len() {
- hix + i
- } else {
- hix + i - buffer.len()
- };
-
- // Drop the value in the slot.
- let slot = &buffer[index];
- slot.value.with_mut(|slot| unsafe {
- let value = &mut *slot;
- value.as_mut_ptr().drop_in_place();
- });
- }
- });
- });
- }
-}
### external/vendor/concurrent-queue/src/lib.rs
@@ -1,660 +0,0 @@
-//! A concurrent multi-producer multi-consumer queue.
-//!
-//! There are two kinds of queues:
-//!
-//! 1. [Bounded] queue with limited capacity.
-//! 2. [Unbounded] queue with unlimited capacity.
-//!
-//! Queues also have the capability to get [closed] at any point. When closed, no more items can be
-//! pushed into the queue, although the remaining items can still be popped.
-//!
-//! These features make it easy to build channels similar to [`std::sync::mpsc`] on top of this
-//! crate.
-//!
-//! # Examples
-//!
-//! ```
-//! use concurrent_queue::ConcurrentQueue;
-//!
-//! let q = ConcurrentQueue::unbounded();
-//! q.push(1).unwrap();
-//! q.push(2).unwrap();
-//!
-//! assert_eq!(q.pop(), Ok(1));
-//! assert_eq!(q.pop(), Ok(2));
-//! ```
-//!
-//! # Features
-//!
-//! `concurrent-queue` uses an `std` default feature. With this feature enabled, this crate will
-//! use [`std::thread::yield_now`] to avoid busy waiting in tight loops. However, with this
-//! feature disabled, [`core::hint::spin_loop`] will be used instead. Disabling `std` will allow
-//! this crate to be used on `no_std` platforms at the potential expense of more busy waiting.
-//!
-//! There is also a `portable-atomic` feature, which uses a polyfill from the
-//! [`portable-atomic`] crate to provide atomic operations on platforms that do not support them.
-//! See the [`README`] for the [`portable-atomic`] crate for more information on how to use it.
-//! Note that even with this feature enabled, `concurrent-queue` still requires a global allocator
-//! to be available. See the documentation for the [`std::alloc::GlobalAlloc`] trait for more
-//! information.
-//!
-//! [Bounded]: `ConcurrentQueue::bounded()`
-//! [Unbounded]: `ConcurrentQueue::unbounded()`
-//! [closed]: `ConcurrentQueue::close()`
-//! [`portable-atomic`]: https://crates.io/crates/portable-atomic
-//! [`README`]: https://github.com/taiki-e/portable-atomic/blob/main/README.md#optional-cfg
-
-#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
-#![no_std]
-#![doc(
- html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
-)]
-#![doc(
- html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
-)]
-
-extern crate alloc;
-#[cfg(feature = "std")]
-extern crate std;
-
-use core::fmt;
-use core::panic::{RefUnwindSafe, UnwindSafe};
-use sync::atomic::{self, Ordering};
-
-#[cfg(feature = "std")]
-use std::error;
-
-use crate::bounded::Bounded;
-use crate::single::Single;
-use crate::sync::busy_wait;
-use crate::unbounded::Unbounded;
-
-mod bounded;
-mod single;
-mod unbounded;
-
-mod sync;
-
-/// Make the given function const if the given condition is true.
-macro_rules! const_fn {
- (
- const_if: #[cfg($($cfg:tt)+)];
- $(#[$($attr:tt)*])*
- $vis:vis const fn $($rest:tt)*
- ) => {
- #[cfg($($cfg)+)]
- $(#[$($attr)*])*
- $vis const fn $($rest)*
- #[cfg(not($($cfg)+))]
- $(#[$($attr)*])*
- $vis fn $($rest)*
- };
-}
-
-pub(crate) use const_fn;
-
-/// A concurrent queue.
-///
-/// # Examples
-///
-/// ```
-/// use concurrent_queue::{ConcurrentQueue, PopError, PushError};
-///
-/// let q = ConcurrentQueue::bounded(2);
-///
-/// assert_eq!(q.push('a'), Ok(()));
-/// assert_eq!(q.push('b'), Ok(()));
-/// assert_eq!(q.push('c'), Err(PushError::Full('c')));
-///
-/// assert_eq!(q.pop(), Ok('a'));
-/// assert_eq!(q.pop(), Ok('b'));
-/// assert_eq!(q.pop(), Err(PopError::Empty));
-/// ```
-pub struct ConcurrentQueue<T>(Inner<T>);
-
-unsafe impl<T: Send> Send for ConcurrentQueue<T> {}
-unsafe impl<T: Send> Sync for ConcurrentQueue<T> {}
-
-impl<T> UnwindSafe for ConcurrentQueue<T> {}
-impl<T> RefUnwindSafe for ConcurrentQueue<T> {}
-
-#[allow(clippy::large_enum_variant)]
-enum Inner<T> {
- Single(Single<T>),
- Bounded(Bounded<T>),
- Unbounded(Unbounded<T>),
-}
-
-impl<T> ConcurrentQueue<T> {
- /// Creates a new bounded queue.
- ///
- /// The queue allocates enough space for `cap` items.
- ///
- /// # Panics
- ///
- /// If the capacity is zero, this constructor will panic.
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::ConcurrentQueue;
- ///
- /// let q = ConcurrentQueue::<i32>::bounded(100);
- /// ```
- pub fn bounded(cap: usize) -> ConcurrentQueue<T> {
- if cap == 1 {
- ConcurrentQueue(Inner::Single(Single::new()))
- } else {
- ConcurrentQueue(Inner::Bounded(Bounded::new(cap)))
- }
- }
-
- const_fn!(
- const_if: #[cfg(not(loom))];
- /// Creates a new unbounded queue.
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::ConcurrentQueue;
- ///
- /// let q = ConcurrentQueue::<i32>::unbounded();
- /// ```
- pub const fn unbounded() -> ConcurrentQueue<T> {
- ConcurrentQueue(Inner::Unbounded(Unbounded::new()))
- }
- );
-
- /// Attempts to push an item into the queue.
- ///
- /// If the queue is full or closed, the item is returned back as an error.
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::{ConcurrentQueue, PushError};
- ///
- /// let q = ConcurrentQueue::bounded(1);
- ///
- /// // Push succeeds because there is space in the queue.
- /// assert_eq!(q.push(10), Ok(()));
- ///
- /// // Push errors because the queue is now full.
- /// assert_eq!(q.push(20), Err(PushError::Full(20)));
- ///
- /// // Close the queue, which will prevent further pushes.
- /// q.close();
- ///
- /// // Pushing now errors indicating the queue is closed.
- /// assert_eq!(q.push(20), Err(PushError::Closed(20)));
- ///
- /// // Pop the single item in the queue.
- /// assert_eq!(q.pop(), Ok(10));
- ///
- /// // Even though there is space, no more items can be pushed.
- /// assert_eq!(q.push(20), Err(PushError::Closed(20)));
- /// ```
- pub fn push(&self, value: T) -> Result<(), PushError<T>> {
- match &self.0 {
- Inner::Single(q) => q.push(value),
- Inner::Bounded(q) => q.push(value),
- Inner::Unbounded(q) => q.push(value),
- }
- }
-
- /// Push an element into the queue, potentially displacing another element.
- ///
- /// Attempts to push an element into the queue. If the queue is full, one item from the
- /// queue is replaced with the provided item. The displaced item is returned as `Some(T)`.
- /// If the queue is closed, an error is returned.
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::{ConcurrentQueue, ForcePushError, PushError};
- ///
- /// let q = ConcurrentQueue::bounded(3);
- ///
- /// // We can push to the queue.
- /// for i in 1..=3 {
- /// assert_eq!(q.force_push(i), Ok(None));
- /// }
- ///
- /// // Push errors because the queue is now full.
- /// assert_eq!(q.push(4), Err(PushError::Full(4)));
- ///
- /// // Pushing a new value replaces the old ones.
- /// assert_eq!(q.force_push(5), Ok(Some(1)));
- /// assert_eq!(q.force_push(6), Ok(Some(2)));
- ///
- /// // Close the queue to stop further pushes.
- /// q.close();
- ///
- /// // Pushing will return an error.
- /// assert_eq!(q.force_push(7), Err(ForcePushError(7)));
- ///
- /// // Popping items will return the force-pushed ones.
- /// assert_eq!(q.pop(), Ok(3));
- /// assert_eq!(q.pop(), Ok(5));
- /// assert_eq!(q.pop(), Ok(6));
- /// ```
- pub fn force_push(&self, value: T) -> Result<Option<T>, ForcePushError<T>> {
- match &self.0 {
- Inner::Single(q) => q.force_push(value),
- Inner::Bounded(q) => q.force_push(value),
- Inner::Unbounded(q) => match q.push(value) {
- Ok(()) => Ok(None),
- Err(PushError::Closed(value)) => Err(ForcePushError(value)),
- Err(PushError::Full(_)) => unreachable!(),
- },
- }
- }
-
- /// Attempts to pop an item from the queue.
- ///
- /// If the queue is empty, an error is returned.
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::{ConcurrentQueue, PopError};
- ///
- /// let q = ConcurrentQueue::bounded(1);
- ///
- /// // Pop errors when the queue is empty.
- /// assert_eq!(q.pop(), Err(PopError::Empty));
- ///
- /// // Push one item and close the queue.
- /// assert_eq!(q.push(10), Ok(()));
- /// q.close();
- ///
- /// // Remaining items can be popped.
- /// assert_eq!(q.pop(), Ok(10));
- ///
- /// // Again, pop errors when the queue is empty,
- /// // but now also indicates that the queue is closed.
- /// assert_eq!(q.pop(), Err(PopError::Closed));
- /// ```
- pub fn pop(&self) -> Result<T, PopError> {
- match &self.0 {
- Inner::Single(q) => q.pop(),
- Inner::Bounded(q) => q.pop(),
- Inner::Unbounded(q) => q.pop(),
- }
- }
-
- /// Get an iterator over the items in the queue.
- ///
- /// The iterator will continue until the queue is empty or closed. It will never block;
- /// if the queue is empty, the iterator will return `None`. If new items are pushed into
- /// the queue, the iterator may return `Some` in the future after returning `None`.
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::ConcurrentQueue;
- ///
- /// let q = ConcurrentQueue::bounded(5);
- /// q.push(1).unwrap();
- /// q.push(2).unwrap();
- /// q.push(3).unwrap();
- ///
- /// let mut iter = q.try_iter();
- /// assert_eq!(iter.by_ref().sum::<i32>(), 6);
- /// assert_eq!(iter.next(), None);
- ///
- /// // Pushing more items will make them available to the iterator.
- /// q.push(4).unwrap();
- /// assert_eq!(iter.next(), Some(4));
- /// assert_eq!(iter.next(), None);
- /// ```
- pub fn try_iter(&self) -> TryIter<'_, T> {
- TryIter { queue: self }
- }
-
- /// Returns `true` if the queue is empty.
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::ConcurrentQueue;
- ///
- /// let q = ConcurrentQueue::<i32>::unbounded();
- ///
- /// assert!(q.is_empty());
- /// q.push(1).unwrap();
- /// assert!(!q.is_empty());
- /// ```
- pub fn is_empty(&self) -> bool {
- match &self.0 {
- Inner::Single(q) => q.is_empty(),
- Inner::Bounded(q) => q.is_empty(),
- Inner::Unbounded(q) => q.is_empty(),
- }
- }
-
- /// Returns `true` if the queue is full.
- ///
- /// An unbounded queue is never full.
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::ConcurrentQueue;
- ///
- /// let q = ConcurrentQueue::bounded(1);
- ///
- /// assert!(!q.is_full());
- /// q.push(1).unwrap();
- /// assert!(q.is_full());
- /// ```
- pub fn is_full(&self) -> bool {
- match &self.0 {
- Inner::Single(q) => q.is_full(),
- Inner::Bounded(q) => q.is_full(),
- Inner::Unbounded(q) => q.is_full(),
- }
- }
-
- /// Returns the number of items in the queue.
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::ConcurrentQueue;
- ///
- /// let q = ConcurrentQueue::unbounded();
- /// assert_eq!(q.len(), 0);
- ///
- /// assert_eq!(q.push(10), Ok(()));
- /// assert_eq!(q.len(), 1);
- ///
- /// assert_eq!(q.push(20), Ok(()));
- /// assert_eq!(q.len(), 2);
- /// ```
- pub fn len(&self) -> usize {
- match &self.0 {
- Inner::Single(q) => q.len(),
- Inner::Bounded(q) => q.len(),
- Inner::Unbounded(q) => q.len(),
- }
- }
-
- /// Returns the capacity of the queue.
- ///
- /// Unbounded queues have infinite capacity, represented as [`None`].
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::ConcurrentQueue;
- ///
- /// let q = ConcurrentQueue::<i32>::bounded(7);
- /// assert_eq!(q.capacity(), Some(7));
- ///
- /// let q = ConcurrentQueue::<i32>::unbounded();
- /// assert_eq!(q.capacity(), None);
- /// ```
- pub fn capacity(&self) -> Option<usize> {
- match &self.0 {
- Inner::Single(_) => Some(1),
- Inner::Bounded(q) => Some(q.capacity()),
- Inner::Unbounded(_) => None,
- }
- }
-
- /// Closes the queue.
- ///
- /// Returns `true` if this call closed the queue, or `false` if it was already closed.
- ///
- /// When a queue is closed, no more items can be pushed but the remaining items can still be
- /// popped.
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::{ConcurrentQueue, PopError, PushError};
- ///
- /// let q = ConcurrentQueue::unbounded();
- /// assert_eq!(q.push(10), Ok(()));
- ///
- /// assert!(q.close()); // `true` because this call closes the queue.
- /// assert!(!q.close()); // `false` because the queue is already closed.
- ///
- /// // Cannot push any more items when closed.
- /// assert_eq!(q.push(20), Err(PushError::Closed(20)));
- ///
- /// // Remaining items can still be popped.
- /// assert_eq!(q.pop(), Ok(10));
- ///
- /// // When no more items are present, the error is `Closed`.
- /// assert_eq!(q.pop(), Err(PopError::Closed));
- /// ```
- pub fn close(&self) -> bool {
- match &self.0 {
- Inner::Single(q) => q.close(),
- Inner::Bounded(q) => q.close(),
- Inner::Unbounded(q) => q.close(),
- }
- }
-
- /// Returns `true` if the queue is closed.
- ///
- /// # Examples
- ///
- /// ```
- /// use concurrent_queue::ConcurrentQueue;
- ///
- /// let q = ConcurrentQueue::<i32>::unbounded();
- ///
- /// assert!(!q.is_closed());
- /// q.close();
- /// assert!(q.is_closed());
- /// ```
- pub fn is_closed(&self) -> bool {
- match &self.0 {
- Inner::Single(q) => q.is_closed(),
- Inner::Bounded(q) => q.is_closed(),
- Inner::Unbounded(q) => q.is_closed(),
- }
- }
-}
-
-impl<T> fmt::Debug for ConcurrentQueue<T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("ConcurrentQueue")
- .field("len", &self.len())
- .field("capacity", &self.capacity())
- .field("is_closed", &self.is_closed())
- .finish()
- }
-}
-
-/// An iterator that pops items from a [`ConcurrentQueue`].
-///
-/// This iterator will never block; it will return `None` once the queue has
-/// been exhausted. Calling `next` after `None` may yield `Some(item)` if more items
-/// are pushed to the queue.
-#[must_use = "iterators are lazy and do nothing unless consumed"]
-#[derive(Clone)]
-pub struct TryIter<'a, T> {
- queue: &'a ConcurrentQueue<T>,
-}
-
-impl<T> fmt::Debug for TryIter<'_, T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_tuple("Iter").field(&self.queue).finish()
- }
-}
-
-impl<T> Iterator for TryIter<'_, T> {
- type Item = T;
-
- fn next(&mut self) -> Option<Self::Item> {
- self.queue.pop().ok()
- }
-}
-
-/// Error which occurs when popping from an empty queue.
-#[derive(Clone, Copy, Eq, PartialEq)]
-pub enum PopError {
- /// The queue is empty but not closed.
- Empty,
-
- /// The queue is empty and closed.
- Closed,
-}
-
-impl PopError {
- /// Returns `true` if the queue is empty but not closed.
- pub fn is_empty(&self) -> bool {
- match self {
- PopError::Empty => true,
- PopError::Closed => false,
- }
- }
-
- /// Returns `true` if the queue is empty and closed.
- pub fn is_closed(&self) -> bool {
- match self {
- PopError::Empty => false,
- PopError::Closed => true,
- }
- }
-}
-
-#[cfg(feature = "std")]
-impl error::Error for PopError {}
-
-impl fmt::Debug for PopError {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- PopError::Empty => write!(f, "Empty"),
- PopError::Closed => write!(f, "Closed"),
- }
- }
-}
-
-impl fmt::Display for PopError {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- PopError::Empty => write!(f, "Empty"),
- PopError::Closed => write!(f, "Closed"),
- }
- }
-}
-
-/// Error which occurs when pushing into a full or closed queue.
-#[derive(Clone, Copy, Eq, PartialEq)]
-pub enum PushError<T> {
- /// The queue is full but not closed.
- Full(T),
-
- /// The queue is closed.
- Closed(T),
-}
-
-impl<T> PushError<T> {
- /// Unwraps the item that couldn't be pushed.
- pub fn into_inner(self) -> T {
- match self {
- PushError::Full(t) => t,
- PushError::Closed(t) => t,
- }
- }
-
- /// Returns `true` if the queue is full but not closed.
- pub fn is_full(&self) -> bool {
- match self {
- PushError::Full(_) => true,
- PushError::Closed(_) => false,
- }
- }
-
- /// Returns `true` if the queue is closed.
- pub fn is_closed(&self) -> bool {
- match self {
- PushError::Full(_) => false,
- PushError::Closed(_) => true,
- }
- }
-}
-
-#[cfg(feature = "std")]
-impl<T: fmt::Debug> error::Error for PushError<T> {}
-
-impl<T: fmt::Debug> fmt::Debug for PushError<T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- PushError::Full(t) => f.debug_tuple("Full").field(t).finish(),
- PushError::Closed(t) => f.debug_tuple("Closed").field(t).finish(),
- }
- }
-}
-
-impl<T> fmt::Display for PushError<T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- PushError::Full(_) => write!(f, "Full"),
- PushError::Closed(_) => write!(f, "Closed"),
- }
- }
-}
-
-/// Error that occurs when force-pushing into a full queue.
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub struct ForcePushError<T>(pub T);
-
-impl<T> ForcePushError<T> {
- /// Return the inner value that failed to be force-pushed.
- pub fn into_inner(self) -> T {
- self.0
- }
-}
-
-impl<T: fmt::Debug> fmt::Debug for ForcePushError<T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_tuple("ForcePushError").field(&self.0).finish()
- }
-}
-
-impl<T> fmt::Display for ForcePushError<T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "Closed")
- }
-}
-
-#[cfg(feature = "std")]
-impl<T: fmt::Debug> error::Error for ForcePushError<T> {}
-
-/// Equivalent to `atomic::fence(Ordering::SeqCst)`, but in some cases faster.
-#[inline]
-fn full_fence() {
- #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), not(miri), not(loom)))]
- {
- use core::{arch::asm, cell::UnsafeCell};
- // HACK(stjepang): On x86 architectures there are two different ways of executing
- // a `SeqCst` fence.
- //
- // 1. `atomic::fence(SeqCst)`, which compiles into a `mfence` instruction.
- // 2. A `lock <op>` instruction.
- //
- // Both instructions have the effect of a full barrier, but empirical benchmarks have shown
- // that the second one is sometimes a bit faster.
- let a = UnsafeCell::new(0_usize);
- // It is common to use `lock or` here, but when using a local variable, `lock not`, which
- // does not change the flag, should be slightly more efficient.
- // Refs: https://www.felixcloutier.com/x86/not
- unsafe {
- #[cfg(target_pointer_width = "64")]
- asm!("lock not qword ptr [{0}]", in(reg) a.get(), options(nostack, preserves_flags));
- #[cfg(target_pointer_width = "32")]
- asm!("lock not dword ptr [{0:e}]", in(reg) a.get(), options(nostack, preserves_flags));
- }
- return;
- }
- #[allow(unreachable_code)]
- {
- atomic::fence(Ordering::SeqCst);
- }
-}
### external/vendor/concurrent-queue/src/single.rs
@@ -1,187 +0,0 @@
-use core::mem::MaybeUninit;
-use core::ptr;
-
-use crate::sync::atomic::{AtomicUsize, Ordering};
-use crate::sync::cell::UnsafeCell;
-#[allow(unused_imports)]
-use crate::sync::prelude::*;
-use crate::{busy_wait, ForcePushError, PopError, PushError};
-
-const LOCKED: usize = 1 << 0;
-const PUSHED: usize = 1 << 1;
-const CLOSED: usize = 1 << 2;
-
-/// A single-element queue.
-pub struct Single<T> {
- state: AtomicUsize,
- slot: UnsafeCell<MaybeUninit<T>>,
-}
-
-impl<T> Single<T> {
- /// Creates a new single-element queue.
- pub fn new() -> Single<T> {
- Single {
- state: AtomicUsize::new(0),
- slot: UnsafeCell::new(MaybeUninit::uninit()),
- }
- }
-
- /// Attempts to push an item into the queue.
- pub fn push(&self, value: T) -> Result<(), PushError<T>> {
- // Lock and fill the slot.
- let state = self
- .state
- .compare_exchange(0, LOCKED | PUSHED, Ordering::SeqCst, Ordering::SeqCst)
- .unwrap_or_else(|x| x);
-
- if state == 0 {
- // Write the value and unlock.
- self.slot.with_mut(|slot| unsafe {
- slot.write(MaybeUninit::new(value));
- });
- self.state.fetch_and(!LOCKED, Ordering::Release);
- Ok(())
- } else if state & CLOSED != 0 {
- Err(PushError::Closed(value))
- } else {
- Err(PushError::Full(value))
- }
- }
-
- /// Attempts to push an item into the queue, displacing another if necessary.
- pub fn force_push(&self, value: T) -> Result<Option<T>, ForcePushError<T>> {
- // Attempt to lock the slot.
- let mut state = 0;
-
- loop {
- // Lock the slot.
- let prev = self
- .state
- .compare_exchange(state, LOCKED | PUSHED, Ordering::SeqCst, Ordering::SeqCst)
- .unwrap_or_else(|x| x);
-
- if prev & CLOSED != 0 {
- return Err(ForcePushError(value));
- }
-
- if prev == state {
- // If the value was pushed, swap out the value.
- let prev_value = if prev & PUSHED == 0 {
- // SAFETY: write is safe because we have locked the state.
- self.slot.with_mut(|slot| unsafe {
- slot.write(MaybeUninit::new(value));
- });
- None
- } else {
- // SAFETY: replace is safe because we have locked the state, and
- // assume_init is safe because we have checked that the value was pushed.
- let prev_value = unsafe {
- self.slot.with_mut(move |slot| {
- ptr::replace(slot, MaybeUninit::new(value)).assume_init()
- })
- };
- Some(prev_value)
- };
-
- // We can unlock the slot now.
- self.state.fetch_and(!LOCKED, Ordering::Release);
-
- // Return the old value.
- return Ok(prev_value);
- }
-
- // Try to go for the current (pushed) state.
- if prev & LOCKED == 0 {
- state = prev;
- } else {
- // State is locked.
- busy_wait();
- state = prev & !LOCKED;
- }
- }
- }
-
- /// Attempts to pop an item from the queue.
- pub fn pop(&self) -> Result<T, PopError> {
- let mut state = PUSHED;
- loop {
- // Lock and empty the slot.
- let prev = self
- .state
- .compare_exchange(
- state,
- (state | LOCKED) & !PUSHED,
- Ordering::SeqCst,
- Ordering::SeqCst,
- )
- .unwrap_or_else(|x| x);
-
- if prev == state {
- // Read the value and unlock.
- let value = self
- .slot
- .with_mut(|slot| unsafe { slot.read().assume_init() });
- self.state.fetch_and(!LOCKED, Ordering::Release);
- return Ok(value);
- }
-
- if prev & PUSHED == 0 {
- if prev & CLOSED == 0 {
- return Err(PopError::Empty);
- } else {
- return Err(PopError::Closed);
- }
- }
-
- if prev & LOCKED == 0 {
- state = prev;
- } else {
- busy_wait();
- state = prev & !LOCKED;
- }
- }
- }
-
- /// Returns the number of items in the queue.
- pub fn len(&self) -> usize {
- usize::from(self.state.load(Ordering::SeqCst) & PUSHED != 0)
- }
-
- /// Returns `true` if the queue is empty.
- pub fn is_empty(&self) -> bool {
- self.len() == 0
- }
-
- /// Returns `true` if the queue is full.
- pub fn is_full(&self) -> bool {
- self.len() == 1
- }
-
- /// Closes the queue.
- ///
- /// Returns `true` if this call closed the queue.
- pub fn close(&self) -> bool {
- let state = self.state.fetch_or(CLOSED, Ordering::SeqCst);
- state & CLOSED == 0
- }
-
- /// Returns `true` if the queue is closed.
- pub fn is_closed(&self) -> bool {
- self.state.load(Ordering::SeqCst) & CLOSED != 0
- }
-}
-
-impl<T> Drop for Single<T> {
- fn drop(&mut self) {
- // Drop the value in the slot.
- let Self { state, slot } = self;
- state.with_mut(|state| {
- if *state & PUSHED != 0 {
- slot.with_mut(|slot| unsafe {
- let value = &mut *slot;
- value.as_mut_ptr().drop_in_place();
- });
- }
- });
- }
-}
### external/vendor/concurrent-queue/src/sync.rs
@@ -1,114 +0,0 @@
-//! Synchronization facade to choose between `core` primitives and `loom` primitives.
-
-#[cfg(all(feature = "portable-atomic", not(loom)))]
-mod sync_impl {
- pub(crate) use core::cell;
- pub(crate) use portable_atomic as atomic;
-
- #[cfg(not(feature = "std"))]
- pub(crate) use atomic::hint::spin_loop;
-
- #[cfg(feature = "std")]
- pub(crate) use std::thread::yield_now;
-}
-
-#[cfg(all(not(feature = "portable-atomic"), not(loom)))]
-mod sync_impl {
- pub(crate) use core::cell;
- pub(crate) use core::sync::atomic;
-
- #[cfg(not(feature = "std"))]
- #[inline]
- pub(crate) fn spin_loop() {
- #[allow(deprecated)]
- atomic::spin_loop_hint();
- }
-
- #[cfg(feature = "std")]
- pub(crate) use std::thread::yield_now;
-}
-
-#[cfg(loom)]
-mod sync_impl {
- pub(crate) use loom::cell;
-
- pub(crate) mod atomic {
- pub(crate) use loom::sync::atomic::*;
- }
-
- #[cfg(not(feature = "std"))]
- pub(crate) use loom::hint::spin_loop;
- #[cfg(feature = "std")]
- pub(crate) use loom::thread::yield_now;
-}
-
-pub(crate) use sync_impl::*;
-
-/// Notify the CPU that we are currently busy-waiting.
-#[inline]
-pub(crate) fn busy_wait() {
- #[cfg(feature = "std")]
- yield_now();
-
- #[cfg(not(feature = "std"))]
- spin_loop();
-}
-
-#[cfg(loom)]
-pub(crate) mod prelude {}
-
-#[cfg(not(loom))]
-pub(crate) mod prelude {
- use super::{atomic, cell};
-
- /// Emulate `loom::UnsafeCell`'s API.
- pub(crate) trait UnsafeCellExt {
- type Value;
-
- fn with_mut<R, F>(&self, f: F) -> R
- where
- F: FnOnce(*mut Self::Value) -> R;
- }
-
- impl<T> UnsafeCellExt for cell::UnsafeCell<T> {
- type Value = T;
-
- fn with_mut<R, F>(&self, f: F) -> R
- where
- F: FnOnce(*mut Self::Value) -> R,
- {
- f(self.get())
- }
- }
-
- /// Emulate `loom::Atomic*`'s API.
- pub(crate) trait AtomicExt {
- type Value;
-
- fn with_mut<R, F>(&mut self, f: F) -> R
- where
- F: FnOnce(&mut Self::Value) -> R;
- }
-
- impl AtomicExt for atomic::AtomicUsize {
- type Value = usize;
-
- fn with_mut<R, F>(&mut self, f: F) -> R
- where
- F: FnOnce(&mut Self::Value) -> R,
- {
- f(self.get_mut())
- }
- }
-
- impl<T> AtomicExt for atomic::AtomicPtr<T> {
- type Value = *mut T;
-
- fn with_mut<R, F>(&mut self, f: F) -> R
- where
- F: FnOnce(&mut Self::Value) -> R,
- {
- f(self.get_mut())
- }
- }
-}
### external/vendor/concurrent-queue/src/unbounded.rs
@@ -1,452 +0,0 @@
-use alloc::boxed::Box;
-use core::mem::MaybeUninit;
-use core::ptr;
-
-use crossbeam_utils::CachePadded;
-
-use crate::const_fn;
-use crate::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
-use crate::sync::cell::UnsafeCell;
-#[allow(unused_imports)]
-use crate::sync::prelude::*;
-use crate::{busy_wait, PopError, PushError};
-
-// Bits indicating the state of a slot:
-// * If a value has been written into the slot, `WRITE` is set.
-// * If a value has been read from the slot, `READ` is set.
-// * If the block is being destroyed, `DESTROY` is set.
-const WRITE: usize = 1;
-const READ: usize = 2;
-const DESTROY: usize = 4;
-
-// Each block covers one "lap" of indices.
-const LAP: usize = 32;
-// The maximum number of items a block can hold.
-const BLOCK_CAP: usize = LAP - 1;
-// How many lower bits are reserved for metadata.
-const SHIFT: usize = 1;
-// Has two different purposes:
-// * If set in head, indicates that the block is not the last one.
-// * If set in tail, indicates that the queue is closed.
-const MARK_BIT: usize = 1;
-
-/// A slot in a block.
-struct Slot<T> {
- /// The value.
- value: UnsafeCell<MaybeUninit<T>>,
-
- /// The state of the slot.
- state: AtomicUsize,
-}
-
-impl<T> Slot<T> {
- #[cfg(not(loom))]
- const UNINIT: Slot<T> = Slot {
- value: UnsafeCell::new(MaybeUninit::uninit()),
- state: AtomicUsize::new(0),
- };
-
- #[cfg(not(loom))]
- fn uninit_block() -> [Slot<T>; BLOCK_CAP] {
- [Self::UNINIT; BLOCK_CAP]
- }
-
- #[cfg(loom)]
- fn uninit_block() -> [Slot<T>; BLOCK_CAP] {
- // Repeat this expression 31 times.
- // Update if we change BLOCK_CAP
- macro_rules! repeat_31 {
- ($e: expr) => {
- [
- $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e,
- $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e,
- ]
- };
- }
-
- repeat_31!(Slot {
- value: UnsafeCell::new(MaybeUninit::uninit()),
- state: AtomicUsize::new(0),
- })
- }
-
- /// Waits until a value is written into the slot.
- fn wait_write(&self) {
- while self.state.load(Ordering::Acquire) & WRITE == 0 {
- busy_wait();
- }
- }
-}
-
-/// A block in a linked list.
-///
-/// Each block in the list can hold up to `BLOCK_CAP` values.
-struct Block<T> {
- /// The next block in the linked list.
- next: AtomicPtr<Block<T>>,
-
- /// Slots for values.
- slots: [Slot<T>; BLOCK_CAP],
-}
-
-impl<T> Block<T> {
- /// Creates an empty block.
- fn new() -> Block<T> {
- Block {
- next: AtomicPtr::new(ptr::null_mut()),
- slots: Slot::uninit_block(),
- }
- }
-
- /// Waits until the next pointer is set.
- fn wait_next(&self) -> *mut Block<T> {
- loop {
- let next = self.next.load(Ordering::Acquire);
- if !next.is_null() {
- return next;
- }
- busy_wait();
- }
- }
-
- /// Sets the `DESTROY` bit in slots starting from `start` and destroys the block.
- unsafe fn destroy(this: *mut Block<T>, start: usize) {
- // It is not necessary to set the `DESTROY` bit in the last slot because that slot has
- // begun destruction of the block.
- for i in start..BLOCK_CAP - 1 {
- let slot = (*this).slots.get_unchecked(i);
-
- // Mark the `DESTROY` bit if a thread is still using the slot.
- if slot.state.load(Ordering::Acquire) & READ == 0
- && slot.state.fetch_or(DESTROY, Ordering::AcqRel) & READ == 0
- {
- // If a thread is still using the slot, it will continue destruction of the block.
- return;
- }
- }
-
- // No thread is using the block, now it is safe to destroy it.
- drop(Box::from_raw(this));
- }
-}
-
-/// A position in a queue.
-struct Position<T> {
- /// The index in the queue.
- index: AtomicUsize,
-
- /// The block in the linked list.
- block: AtomicPtr<Block<T>>,
-}
-
-/// An unbounded queue.
-pub struct Unbounded<T> {
- /// The head of the queue.
- head: CachePadded<Position<T>>,
-
- /// The tail of the queue.
- tail: CachePadded<Position<T>>,
-}
-
-impl<T> Unbounded<T> {
- const_fn!(
- const_if: #[cfg(not(loom))];
- /// Creates a new unbounded queue.
- pub const fn new() -> Unbounded<T> {
- Unbounded {
- head: CachePadded::new(Position {
- block: AtomicPtr::new(ptr::null_mut()),
- index: AtomicUsize::new(0),
- }),
- tail: CachePadded::new(Position {
- block: AtomicPtr::new(ptr::null_mut()),
- index: AtomicUsize::new(0),
- }),
- }
- }
- );
-
- /// Pushes an item into the queue.
- pub fn push(&self, value: T) -> Result<(), PushError<T>> {
- let mut tail = self.tail.index.load(Ordering::Acquire);
- let mut block = self.tail.block.load(Ordering::Acquire);
- let mut next_block = None;
-
- loop {
- // Check if the queue is closed.
- if tail & MARK_BIT != 0 {
- return Err(PushError::Closed(value));
- }
-
- // Calculate the offset of the index into the block.
- let offset = (tail >> SHIFT) % LAP;
-
- // If we reached the end of the block, wait until the next one is installed.
- if offset == BLOCK_CAP {
- busy_wait();
- tail = self.tail.index.load(Ordering::Acquire);
- block = self.tail.block.load(Ordering::Acquire);
- continue;
- }
-
- // If we're going to have to install the next block, allocate it in advance in order to
- // make the wait for other threads as short as possible.
- if offset + 1 == BLOCK_CAP && next_block.is_none() {
- next_block = Some(Box::new(Block::<T>::new()));
- }
-
- // If this is the first value to be pushed into the queue, we need to allocate the
- // first block and install it.
- if block.is_null() {
- let new = Box::into_raw(Box::new(Block::<T>::new()));
-
- if self
- .tail
- .block
- .compare_exchange(block, new, Ordering::Release, Ordering::Relaxed)
- .is_ok()
- {
- self.head.block.store(new, Ordering::Release);
- block = new;
- } else {
- next_block = unsafe { Some(Box::from_raw(new)) };
- tail = self.tail.index.load(Ordering::Acquire);
- block = self.tail.block.load(Ordering::Acquire);
- continue;
- }
- }
-
- let new_tail = tail + (1 << SHIFT);
-
- // Try advancing the tail forward.
- match self.tail.index.compare_exchange_weak(
- tail,
- new_tail,
- Ordering::SeqCst,
- Ordering::Acquire,
- ) {
- Ok(_) => unsafe {
- // If we've reached the end of the block, install the next one.
- if offset + 1 == BLOCK_CAP {
- let next_block = Box::into_raw(next_block.unwrap());
- self.tail.block.store(next_block, Ordering::Release);
- self.tail.index.fetch_add(1 << SHIFT, Ordering::Release);
- (*block).next.store(next_block, Ordering::Release);
- }
-
- // Write the value into the slot.
- let slot = (*block).slots.get_unchecked(offset);
- slot.value.with_mut(|slot| {
- slot.write(MaybeUninit::new(value));
- });
- slot.state.fetch_or(WRITE, Ordering::Release);
- return Ok(());
- },
- Err(t) => {
- tail = t;
- block = self.tail.block.load(Ordering::Acquire);
- }
- }
- }
- }
-
- /// Pops an item from the queue.
- pub fn pop(&self) -> Result<T, PopError> {
- let mut head = self.head.index.load(Ordering::Acquire);
- let mut block = self.head.block.load(Ordering::Acquire);
-
- loop {
- // Calculate the offset of the index into the block.
- let offset = (head >> SHIFT) % LAP;
-
- // If we reached the end of the block, wait until the next one is installed.
- if offset == BLOCK_CAP {
- busy_wait();
- head = self.head.index.load(Ordering::Acquire);
- block = self.head.block.load(Ordering::Acquire);
- continue;
- }
-
- let mut new_head = head + (1 << SHIFT);
-
- if new_head & MARK_BIT == 0 {
- crate::full_fence();
- let tail = self.tail.index.load(Ordering::Relaxed);
-
- // If the tail equals the head, that means the queue is empty.
- if head >> SHIFT == tail >> SHIFT {
- // Check if the queue is closed.
- if tail & MARK_BIT != 0 {
- return Err(PopError::Closed);
- } else {
- return Err(PopError::Empty);
- }
- }
-
- // If head and tail are not in the same block, set `MARK_BIT` in head.
- if (head >> SHIFT) / LAP != (tail >> SHIFT) / LAP {
- new_head |= MARK_BIT;
- }
- }
-
- // The block can be null here only if the first push operation is in progress.
- if block.is_null() {
- busy_wait();
- head = self.head.index.load(Ordering::Acquire);
- block = self.head.block.load(Ordering::Acquire);
- continue;
- }
-
- // Try moving the head index forward.
- match self.head.index.compare_exchange_weak(
- head,
- new_head,
- Ordering::SeqCst,
- Ordering::Acquire,
- ) {
- Ok(_) => unsafe {
- // If we've reached the end of the block, move to the next one.
- if offset + 1 == BLOCK_CAP {
- let next = (*block).wait_next();
- let mut next_index = (new_head & !MARK_BIT).wrapping_add(1 << SHIFT);
- if !(*next).next.load(Ordering::Relaxed).is_null() {
- next_index |= MARK_BIT;
- }
-
- self.head.block.store(next, Ordering::Release);
- self.head.index.store(next_index, Ordering::Release);
- }
-
- // Read the value.
- let slot = (*block).slots.get_unchecked(offset);
- slot.wait_write();
- let value = slot.value.with_mut(|slot| slot.read().assume_init());
-
- // Destroy the block if we've reached the end, or if another thread wanted to
- // destroy but couldn't because we were busy reading from the slot.
- if offset + 1 == BLOCK_CAP {
- Block::destroy(block, 0);
- } else if slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0 {
- Block::destroy(block, offset + 1);
- }
-
- return Ok(value);
- },
- Err(h) => {
- head = h;
- block = self.head.block.load(Ordering::Acquire);
- }
- }
- }
- }
-
- /// Returns the number of items in the queue.
- pub fn len(&self) -> usize {
- loop {
- // Load the tail index, then load the head index.
- let mut tail = self.tail.index.load(Ordering::SeqCst);
- let mut head = self.head.index.load(Ordering::SeqCst);
-
- // If the tail index didn't change, we've got consistent indices to work with.
- if self.tail.index.load(Ordering::SeqCst) == tail {
- // Erase the lower bits.
- tail &= !((1 << SHIFT) - 1);
- head &= !((1 << SHIFT) - 1);
-
- // Fix up indices if they fall onto block ends.
- if (tail >> SHIFT) & (LAP - 1) == LAP - 1 {
- tail = tail.wrapping_add(1 << SHIFT);
- }
- if (head >> SHIFT) & (LAP - 1) == LAP - 1 {
- head = head.wrapping_add(1 << SHIFT);
- }
-
- // Rotate indices so that head falls into the first block.
- let lap = (head >> SHIFT) / LAP;
- tail = tail.wrapping_sub((lap * LAP) << SHIFT);
- head = head.wrapping_sub((lap * LAP) << SHIFT);
-
- // Remove the lower bits.
- tail >>= SHIFT;
- head >>= SHIFT;
-
- // Return the difference minus the number of blocks between tail and head.
- return tail - head - tail / LAP;
- }
- }
- }
-
- /// Returns `true` if the queue is empty.
- pub fn is_empty(&self) -> bool {
- let head = self.head.index.load(Ordering::SeqCst);
- let tail = self.tail.index.load(Ordering::SeqCst);
- head >> SHIFT == tail >> SHIFT
- }
-
- /// Returns `true` if the queue is full.
- pub fn is_full(&self) -> bool {
- false
- }
-
- /// Closes the queue.
- ///
- /// Returns `true` if this call closed the queue.
- pub fn close(&self) -> bool {
- let tail = self.tail.index.fetch_or(MARK_BIT, Ordering::SeqCst);
- tail & MARK_BIT == 0
- }
-
- /// Returns `true` if the queue is closed.
- pub fn is_closed(&self) -> bool {
- self.tail.index.load(Ordering::SeqCst) & MARK_BIT != 0
- }
-}
-
-impl<T> Drop for Unbounded<T> {
- fn drop(&mut self) {
- let Self { head, tail } = self;
- let Position { index: head, block } = &mut **head;
-
- head.with_mut(|&mut mut head| {
- tail.index.with_mut(|&mut mut tail| {
- // Erase the lower bits.
- head &= !((1 << SHIFT) - 1);
- tail &= !((1 << SHIFT) - 1);
-
- unsafe {
- // Drop all values between `head` and `tail` and deallocate the heap-allocated blocks.
- while head != tail {
- let offset = (head >> SHIFT) % LAP;
-
- if offset < BLOCK_CAP {
- // Drop the value in the slot.
- block.with_mut(|block| {
- let slot = (**block).slots.get_unchecked(offset);
- slot.value.with_mut(|slot| {
- let value = &mut *slot;
- value.as_mut_ptr().drop_in_place();
- });
- });
- } else {
- // Deallocate the block and move to the next one.
- block.with_mut(|block| {
- let next_block = (**block).next.with_mut(|next| *next);
- drop(Box::from_raw(*block));
- *block = next_block;
- });
- }
-
- head = head.wrapping_add(1 << SHIFT);
- }
-
- // Deallocate the last remaining block.
- block.with_mut(|block| {
- if !block.is_null() {
- drop(Box::from_raw(*block));
- }
- });
- }
- });
- });
- }
-}
### external/vendor/concurrent-queue/tests/bounded.rs
@@ -1,371 +0,0 @@
-#![allow(clippy::bool_assert_comparison)]
-
-use concurrent_queue::{ConcurrentQueue, ForcePushError, PopError, PushError};
-
-#[cfg(not(target_family = "wasm"))]
-use easy_parallel::Parallel;
-#[cfg(not(target_family = "wasm"))]
-use std::sync::atomic::{AtomicUsize, Ordering};
-
-#[cfg(target_family = "wasm")]
-use wasm_bindgen_test::wasm_bindgen_test as test;
-
-#[test]
-fn smoke() {
- let q = ConcurrentQueue::bounded(2);
-
- q.push(7).unwrap();
- assert_eq!(q.pop(), Ok(7));
-
- q.push(8).unwrap();
- assert_eq!(q.pop(), Ok(8));
- assert!(q.pop().is_err());
-}
-
-#[test]
-fn capacity() {
- for i in 1..10 {
- let q = ConcurrentQueue::<i32>::bounded(i);
- assert_eq!(q.capacity(), Some(i));
- }
-}
-
-#[test]
-#[should_panic(expected = "capacity must be positive")]
-fn zero_capacity() {
- let _ = ConcurrentQueue::<i32>::bounded(0);
-}
-
-#[test]
-fn len_empty_full() {
- let q = ConcurrentQueue::bounded(2);
-
- assert_eq!(q.len(), 0);
- assert_eq!(q.is_empty(), true);
- assert_eq!(q.is_full(), false);
-
- q.push(()).unwrap();
-
- assert_eq!(q.len(), 1);
- assert_eq!(q.is_empty(), false);
- assert_eq!(q.is_full(), false);
-
- q.push(()).unwrap();
-
- assert_eq!(q.len(), 2);
- assert_eq!(q.is_empty(), false);
- assert_eq!(q.is_full(), true);
-
- q.pop().unwrap();
-
- assert_eq!(q.len(), 1);
- assert_eq!(q.is_empty(), false);
- assert_eq!(q.is_full(), false);
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn len() {
- const COUNT: usize = if cfg!(miri) { 50 } else { 25_000 };
- const CAP: usize = if cfg!(miri) { 50 } else { 1000 };
-
- let q = ConcurrentQueue::bounded(CAP);
- assert_eq!(q.len(), 0);
-
- for _ in 0..CAP / 10 {
- for i in 0..50 {
- q.push(i).unwrap();
- assert_eq!(q.len(), i + 1);
- }
-
- for i in 0..50 {
- q.pop().unwrap();
- assert_eq!(q.len(), 50 - i - 1);
- }
- }
- assert_eq!(q.len(), 0);
-
- for i in 0..CAP {
- q.push(i).unwrap();
- assert_eq!(q.len(), i + 1);
- }
-
- for _ in 0..CAP {
- q.pop().unwrap();
- }
- assert_eq!(q.len(), 0);
-
- Parallel::new()
- .add(|| {
- for i in 0..COUNT {
- loop {
- if let Ok(x) = q.pop() {
- assert_eq!(x, i);
- break;
- }
- }
- let len = q.len();
- assert!(len <= CAP);
- }
- })
- .add(|| {
- for i in 0..COUNT {
- while q.push(i).is_err() {}
- let len = q.len();
- assert!(len <= CAP);
- }
- })
- .run();
-
- assert_eq!(q.len(), 0);
-}
-
-#[test]
-fn close() {
- let q = ConcurrentQueue::bounded(2);
- assert_eq!(q.push(10), Ok(()));
-
- assert!(!q.is_closed());
- assert!(q.close());
-
- assert!(q.is_closed());
- assert!(!q.close());
-
- assert_eq!(q.push(20), Err(PushError::Closed(20)));
- assert_eq!(q.pop(), Ok(10));
- assert_eq!(q.pop(), Err(PopError::Closed));
-}
-
-#[test]
-fn force_push() {
- let q = ConcurrentQueue::<i32>::bounded(5);
-
- for i in 1..=5 {
- assert_eq!(q.force_push(i), Ok(None));
- }
-
- assert!(!q.is_closed());
- for i in 6..=10 {
- assert_eq!(q.force_push(i), Ok(Some(i - 5)));
- }
- assert_eq!(q.pop(), Ok(6));
- assert_eq!(q.force_push(11), Ok(None));
- for i in 12..=15 {
- assert_eq!(q.force_push(i), Ok(Some(i - 5)));
- }
-
- assert!(q.close());
- assert_eq!(q.force_push(40), Err(ForcePushError(40)));
- for i in 11..=15 {
- assert_eq!(q.pop(), Ok(i));
- }
- assert_eq!(q.pop(), Err(PopError::Closed));
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn spsc() {
- const COUNT: usize = if cfg!(miri) { 100 } else { 100_000 };
-
- let q = ConcurrentQueue::bounded(3);
-
- Parallel::new()
- .add(|| {
- for i in 0..COUNT {
- loop {
- if let Ok(x) = q.pop() {
- assert_eq!(x, i);
- break;
- }
- }
- }
- assert!(q.pop().is_err());
- })
- .add(|| {
- for i in 0..COUNT {
- while q.push(i).is_err() {}
- }
- })
- .run();
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn mpmc() {
- const COUNT: usize = if cfg!(miri) { 100 } else { 25_000 };
- const THREADS: usize = 4;
-
- let q = ConcurrentQueue::<usize>::bounded(3);
- let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::<Vec<_>>();
-
- Parallel::new()
- .each(0..THREADS, |_| {
- for _ in 0..COUNT {
- let n = loop {
- if let Ok(x) = q.pop() {
- break x;
- }
- };
- v[n].fetch_add(1, Ordering::SeqCst);
- }
- })
- .each(0..THREADS, |_| {
- for i in 0..COUNT {
- while q.push(i).is_err() {}
- }
- })
- .run();
-
- for c in v {
- assert_eq!(c.load(Ordering::SeqCst), THREADS);
- }
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn drops() {
- const RUNS: usize = if cfg!(miri) { 10 } else { 100 };
- const STEPS: usize = if cfg!(miri) { 100 } else { 10_000 };
-
- static DROPS: AtomicUsize = AtomicUsize::new(0);
-
- #[derive(Debug, PartialEq)]
- struct DropCounter;
-
- impl Drop for DropCounter {
- fn drop(&mut self) {
- DROPS.fetch_add(1, Ordering::SeqCst);
- }
- }
-
- for _ in 0..RUNS {
- let steps = fastrand::usize(..STEPS);
- let additional = fastrand::usize(..50);
-
- DROPS.store(0, Ordering::SeqCst);
- let q = ConcurrentQueue::bounded(50);
-
- Parallel::new()
- .add(|| {
- for _ in 0..steps {
- while q.pop().is_err() {}
- }
- })
- .add(|| {
- for _ in 0..steps {
- while q.push(DropCounter).is_err() {
- DROPS.fetch_sub(1, Ordering::SeqCst);
- }
- }
- })
- .run();
-
- for _ in 0..additional {
- q.push(DropCounter).unwrap();
- }
-
- assert_eq!(DROPS.load(Ordering::SeqCst), steps);
- drop(q);
- assert_eq!(DROPS.load(Ordering::SeqCst), steps + additional);
- }
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn linearizable() {
- const COUNT: usize = if cfg!(miri) { 500 } else { 25_000 };
- const THREADS: usize = 4;
-
- let q = ConcurrentQueue::bounded(THREADS);
-
- Parallel::new()
- .each(0..THREADS / 2, |_| {
- for _ in 0..COUNT {
- while q.push(0).is_err() {}
- q.pop().unwrap();
- }
- })
- .each(0..THREADS / 2, |_| {
- for _ in 0..COUNT {
- if q.force_push(0).unwrap().is_none() {
- q.pop().unwrap();
- }
- }
- })
- .run();
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn spsc_ring_buffer() {
- const COUNT: usize = if cfg!(miri) { 200 } else { 100_000 };
-
- let t = AtomicUsize::new(1);
- let q = ConcurrentQueue::<usize>::bounded(3);
- let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::<Vec<_>>();
-
- Parallel::new()
- .add(|| loop {
- match t.load(Ordering::SeqCst) {
- 0 if q.is_empty() => break,
-
- _ => {
- while let Ok(n) = q.pop() {
- v[n].fetch_add(1, Ordering::SeqCst);
- }
- }
- }
- })
- .add(|| {
- for i in 0..COUNT {
- if let Ok(Some(n)) = q.force_push(i) {
- v[n].fetch_add(1, Ordering::SeqCst);
- }
- }
-
- t.fetch_sub(1, Ordering::SeqCst);
- })
- .run();
-
- for c in v {
- assert_eq!(c.load(Ordering::SeqCst), 1);
- }
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn mpmc_ring_buffer() {
- const COUNT: usize = if cfg!(miri) { 100 } else { 25_000 };
- const THREADS: usize = 4;
-
- let t = AtomicUsize::new(THREADS);
- let q = ConcurrentQueue::<usize>::bounded(3);
- let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::<Vec<_>>();
-
- Parallel::new()
- .each(0..THREADS, |_| loop {
- match t.load(Ordering::SeqCst) {
- 0 if q.is_empty() => break,
-
- _ => {
- while let Ok(n) = q.pop() {
- v[n].fetch_add(1, Ordering::SeqCst);
- }
- }
- }
- })
- .each(0..THREADS, |_| {
- for i in 0..COUNT {
- if let Ok(Some(n)) = q.force_push(i) {
- v[n].fetch_add(1, Ordering::SeqCst);
- }
- }
-
- t.fetch_sub(1, Ordering::SeqCst);
- })
- .run();
-
- for c in v {
- assert_eq!(c.load(Ordering::SeqCst), THREADS);
- }
-}
### external/vendor/concurrent-queue/tests/loom.rs
@@ -1,307 +0,0 @@
-#![cfg(loom)]
-
-use concurrent_queue::{ConcurrentQueue, ForcePushError, PopError, PushError};
-use loom::sync::atomic::{AtomicUsize, Ordering};
-use loom::sync::{Arc, Condvar, Mutex};
-use loom::thread;
-
-#[cfg(target_family = "wasm")]
-use wasm_bindgen_test::wasm_bindgen_test as test;
-
-/// A basic MPMC channel based on a ConcurrentQueue and loom primitives.
-struct Channel<T> {
- /// The queue used to contain items.
- queue: ConcurrentQueue<T>,
-
- /// The number of senders.
- senders: AtomicUsize,
-
- /// The number of receivers.
- receivers: AtomicUsize,
-
- /// The event that is signaled when a new item is pushed.
- push_event: Event,
-
- /// The event that is signaled when a new item is popped.
- pop_event: Event,
-}
-
-/// The sending side of a channel.
-struct Sender<T> {
- /// The channel.
- channel: Arc<Channel<T>>,
-}
-
-/// The receiving side of a channel.
-struct Receiver<T> {
- /// The channel.
- channel: Arc<Channel<T>>,
-}
-
-/// Create a new pair of senders/receivers based on a queue.
-fn pair<T>(queue: ConcurrentQueue<T>) -> (Sender<T>, Receiver<T>) {
- let channel = Arc::new(Channel {
- queue,
- senders: AtomicUsize::new(1),
- receivers: AtomicUsize::new(1),
- push_event: Event::new(),
- pop_event: Event::new(),
- });
-
- (
- Sender {
- channel: channel.clone(),
- },
- Receiver { channel },
- )
-}
-
-impl<T> Clone for Sender<T> {
- fn clone(&self) -> Self {
- self.channel.senders.fetch_add(1, Ordering::SeqCst);
- Sender {
- channel: self.channel.clone(),
- }
- }
-}
-
-impl<T> Drop for Sender<T> {
- fn drop(&mut self) {
- if self.channel.senders.fetch_sub(1, Ordering::SeqCst) == 1 {
- // Close the channel and notify the receivers.
- self.channel.queue.close();
- self.channel.push_event.signal_all();
- }
- }
-}
-
-impl<T> Clone for Receiver<T> {
- fn clone(&self) -> Self {
- self.channel.receivers.fetch_add(1, Ordering::SeqCst);
- Receiver {
- channel: self.channel.clone(),
- }
- }
-}
-
-impl<T> Drop for Receiver<T> {
- fn drop(&mut self) {
- if self.channel.receivers.fetch_sub(1, Ordering::SeqCst) == 1 {
- // Close the channel and notify the senders.
- self.channel.queue.close();
- self.channel.pop_event.signal_all();
- }
- }
-}
-
-impl<T> Sender<T> {
- /// Send a value.
- ///
- /// Returns an error with the value if the channel is closed.
- fn send(&self, mut value: T) -> Result<(), T> {
- loop {
- match self.channel.queue.push(value) {
- Ok(()) => {
- // Notify a single receiver.
- self.channel.push_event.signal();
- return Ok(());
- }
- Err(PushError::Closed(val)) => return Err(val),
- Err(PushError::Full(val)) => {
- // Wait for a receiver to pop an item.
- value = val;
- self.channel.pop_event.wait();
- }
- }
- }
- }
-
- /// Send a value forcefully.
- fn force_send(&self, value: T) -> Result<Option<T>, T> {
- match self.channel.queue.force_push(value) {
- Ok(bumped) => {
- self.channel.push_event.signal();
- Ok(bumped)
- }
-
- Err(ForcePushError(val)) => Err(val),
- }
- }
-}
-
-impl<T> Receiver<T> {
- /// Channel capacity.
- fn capacity(&self) -> Option<usize> {
- self.channel.queue.capacity()
- }
-
- /// Receive a value.
- ///
- /// Returns an error if the channel is closed.
- fn recv(&self) -> Result<T, ()> {
- loop {
- match self.channel.queue.pop() {
- Ok(value) => {
- // Notify a single sender.
- self.channel.pop_event.signal();
- return Ok(value);
- }
- Err(PopError::Closed) => return Err(()),
- Err(PopError::Empty) => {
- // Wait for a sender to push an item.
- self.channel.push_event.wait();
- }
- }
- }
- }
-}
-
-/// An event that can be waited on and then signaled.
-struct Event {
- /// The condition variable used to wait on the event.
- condvar: Condvar,
-
- /// The mutex used to protect the event.
- ///
- /// Inside is the event's state. The first bit is used to indicate if the
- /// notify_one method was called. The second bit is used to indicate if the
- /// notify_all method was called.
- mutex: Mutex<usize>,
-}
-
-impl Event {
- /// Create a new event.
- fn new() -> Self {
- Self {
- condvar: Condvar::new(),
- mutex: Mutex::new(0),
- }
- }
-
- /// Wait for the event to be signaled.
- fn wait(&self) {
- let mut state = self.mutex.lock().unwrap();
-
- loop {
- if *state & 0b11 != 0 {
- // The event was signaled.
- *state &= !0b01;
- return;
- }
-
- // Wait for the event to be signaled.
- state = self.condvar.wait(state).unwrap();
- }
- }
-
- /// Signal the event.
- fn signal(&self) {
- let mut state = self.mutex.lock().unwrap();
- *state |= 1;
- drop(state);
-
- self.condvar.notify_one();
- }
-
- /// Signal the event, but notify all waiters.
- fn signal_all(&self) {
- let mut state = self.mutex.lock().unwrap();
- *state |= 3;
- drop(state);
-
- self.condvar.notify_all();
- }
-}
-
-/// Wrapper to run tests on all three queues.
-fn run_test<F: Fn(ConcurrentQueue<usize>, usize) + Send + Sync + Clone + 'static>(f: F) {
- // The length of a loom test seems to increase exponentially the higher this number is.
- const LIMIT: usize = 4;
-
- let fc = f.clone();
- loom::model(move || {
- fc(ConcurrentQueue::bounded(1), LIMIT);
- });
-
- let fc = f.clone();
- loom::model(move || {
- fc(ConcurrentQueue::bounded(LIMIT / 2), LIMIT);
- });
-
- loom::model(move || {
- f(ConcurrentQueue::unbounded(), LIMIT);
- });
-}
-
-#[test]
-fn spsc() {
- run_test(|q, limit| {
- // Create a new pair of senders/receivers.
- let (tx, rx) = pair(q);
-
- // Push each onto a thread and run them.
- let handle = thread::spawn(move || {
- for i in 0..limit {
- if tx.send(i).is_err() {
- break;
- }
- }
- });
-
- let mut recv_values = vec![];
-
- loop {
- match rx.recv() {
- Ok(value) => recv_values.push(value),
- Err(()) => break,
- }
- }
-
- // Values may not be in order.
- recv_values.sort_unstable();
- assert_eq!(recv_values, (0..limit).collect::<Vec<_>>());
-
- // Join the handle before we exit.
- handle.join().unwrap();
- });
-}
-
-#[test]
-fn spsc_force() {
- run_test(|q, limit| {
- // Create a new pair of senders/receivers.
- let (tx, rx) = pair(q);
-
- // Push each onto a thread and run them.
- let handle = thread::spawn(move || {
- for i in 0..limit {
- if tx.force_send(i).is_err() {
- break;
- }
- }
- });
-
- let mut recv_values = vec![];
-
- loop {
- match rx.recv() {
- Ok(value) => recv_values.push(value),
- Err(()) => break,
- }
- }
-
- // Values may not be in order.
- recv_values.sort_unstable();
- let cap = rx.capacity().unwrap_or(usize::MAX);
- for (left, right) in (0..limit)
- .rev()
- .take(cap)
- .zip(recv_values.into_iter().rev())
- {
- assert_eq!(left, right);
- }
-
- // Join the handle before we exit.
- handle.join().unwrap();
- });
-}
### external/vendor/concurrent-queue/tests/single.rs
@@ -1,289 +0,0 @@
-#![allow(clippy::bool_assert_comparison)]
-
-use concurrent_queue::{ConcurrentQueue, ForcePushError, PopError, PushError};
-
-#[cfg(not(target_family = "wasm"))]
-use easy_parallel::Parallel;
-#[cfg(not(target_family = "wasm"))]
-use std::sync::atomic::{AtomicUsize, Ordering};
-
-#[cfg(target_family = "wasm")]
-use wasm_bindgen_test::wasm_bindgen_test as test;
-
-#[test]
-fn smoke() {
- let q = ConcurrentQueue::bounded(1);
-
- q.push(7).unwrap();
- assert_eq!(q.pop(), Ok(7));
-
- q.push(8).unwrap();
- assert_eq!(q.pop(), Ok(8));
- assert!(q.pop().is_err());
-}
-
-#[test]
-fn capacity() {
- let q = ConcurrentQueue::<i32>::bounded(1);
- assert_eq!(q.capacity(), Some(1));
-}
-
-#[test]
-fn len_empty_full() {
- let q = ConcurrentQueue::bounded(1);
-
- assert_eq!(q.len(), 0);
- assert_eq!(q.is_empty(), true);
- assert_eq!(q.is_full(), false);
-
- q.push(()).unwrap();
-
- assert_eq!(q.len(), 1);
- assert_eq!(q.is_empty(), false);
- assert_eq!(q.is_full(), true);
-
- q.pop().unwrap();
-
- assert_eq!(q.len(), 0);
- assert_eq!(q.is_empty(), true);
- assert_eq!(q.is_full(), false);
-}
-
-#[test]
-fn close() {
- let q = ConcurrentQueue::<i32>::bounded(1);
- assert_eq!(q.push(10), Ok(()));
-
- assert!(!q.is_closed());
- assert!(q.close());
-
- assert!(q.is_closed());
- assert!(!q.close());
-
- assert_eq!(q.push(20), Err(PushError::Closed(20)));
- assert_eq!(q.pop(), Ok(10));
- assert_eq!(q.pop(), Err(PopError::Closed));
-}
-
-#[test]
-fn force_push() {
- let q = ConcurrentQueue::<i32>::bounded(1);
- assert_eq!(q.force_push(10), Ok(None));
-
- assert!(!q.is_closed());
- assert_eq!(q.force_push(20), Ok(Some(10)));
- assert_eq!(q.force_push(30), Ok(Some(20)));
-
- assert!(q.close());
- assert_eq!(q.force_push(40), Err(ForcePushError(40)));
- assert_eq!(q.pop(), Ok(30));
- assert_eq!(q.pop(), Err(PopError::Closed));
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn spsc() {
- const COUNT: usize = if cfg!(miri) { 100 } else { 100_000 };
-
- let q = ConcurrentQueue::bounded(1);
-
- Parallel::new()
- .add(|| {
- for i in 0..COUNT {
- loop {
- if let Ok(x) = q.pop() {
- assert_eq!(x, i);
- break;
- }
- }
- }
- assert!(q.pop().is_err());
- })
- .add(|| {
- for i in 0..COUNT {
- while q.push(i).is_err() {}
- }
- })
- .run();
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn mpmc() {
- const COUNT: usize = if cfg!(miri) { 100 } else { 25_000 };
- const THREADS: usize = 1;
-
- let q = ConcurrentQueue::<usize>::bounded(THREADS);
- let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::<Vec<_>>();
-
- Parallel::new()
- .each(0..THREADS, |_| {
- for _ in 0..COUNT {
- let n = loop {
- if let Ok(x) = q.pop() {
- break x;
- }
- };
- v[n].fetch_add(1, Ordering::SeqCst);
- }
- })
- .each(0..THREADS, |_| {
- for i in 0..COUNT {
- while q.push(i).is_err() {}
- }
- })
- .run();
-
- for c in v {
- assert_eq!(c.load(Ordering::SeqCst), THREADS);
- }
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn drops() {
- const RUNS: usize = if cfg!(miri) { 20 } else { 100 };
- const STEPS: usize = if cfg!(miri) { 100 } else { 10_000 };
-
- static DROPS: AtomicUsize = AtomicUsize::new(0);
-
- #[derive(Debug, PartialEq)]
- struct DropCounter;
-
- impl Drop for DropCounter {
- fn drop(&mut self) {
- DROPS.fetch_add(1, Ordering::SeqCst);
- }
- }
-
- for _ in 0..RUNS {
- let steps = fastrand::usize(..STEPS);
- let additional = fastrand::usize(0..=1);
-
- DROPS.store(0, Ordering::SeqCst);
- let q = ConcurrentQueue::bounded(1);
-
- Parallel::new()
- .add(|| {
- for _ in 0..steps {
- while q.pop().is_err() {}
- }
- })
- .add(|| {
- for _ in 0..steps {
- while q.push(DropCounter).is_err() {
- DROPS.fetch_sub(1, Ordering::SeqCst);
- }
- }
- })
- .run();
-
- for _ in 0..additional {
- q.push(DropCounter).unwrap();
- }
-
- assert_eq!(DROPS.load(Ordering::SeqCst), steps);
- drop(q);
- assert_eq!(DROPS.load(Ordering::SeqCst), steps + additional);
- }
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn linearizable() {
- const COUNT: usize = if cfg!(miri) { 500 } else { 25_000 };
- const THREADS: usize = 4;
-
- let q = ConcurrentQueue::bounded(1);
-
- Parallel::new()
- .each(0..THREADS / 2, |_| {
- for _ in 0..COUNT {
- while q.push(0).is_err() {}
- q.pop().unwrap();
- }
- })
- .each(0..THREADS / 2, |_| {
- for _ in 0..COUNT {
- if q.force_push(0).unwrap().is_none() {
- q.pop().unwrap();
- }
- }
- })
- .run();
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn spsc_ring_buffer() {
- const COUNT: usize = if cfg!(miri) { 200 } else { 100_000 };
-
- let t = AtomicUsize::new(1);
- let q = ConcurrentQueue::<usize>::bounded(1);
- let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::<Vec<_>>();
-
- Parallel::new()
- .add(|| loop {
- match t.load(Ordering::SeqCst) {
- 0 if q.is_empty() => break,
-
- _ => {
- while let Ok(n) = q.pop() {
- v[n].fetch_add(1, Ordering::SeqCst);
- }
- }
- }
- })
- .add(|| {
- for i in 0..COUNT {
- if let Ok(Some(n)) = q.force_push(i) {
- v[n].fetch_add(1, Ordering::SeqCst);
- }
- }
-
- t.fetch_sub(1, Ordering::SeqCst);
- })
- .run();
-
- for c in v {
- assert_eq!(c.load(Ordering::SeqCst), 1);
- }
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn mpmc_ring_buffer() {
- const COUNT: usize = if cfg!(miri) { 100 } else { 25_000 };
- const THREADS: usize = 4;
-
- let t = AtomicUsize::new(THREADS);
- let q = ConcurrentQueue::<usize>::bounded(1);
- let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::<Vec<_>>();
-
- Parallel::new()
- .each(0..THREADS, |_| loop {
- match t.load(Ordering::SeqCst) {
- 0 if q.is_empty() => break,
-
- _ => {
- while let Ok(n) = q.pop() {
- v[n].fetch_add(1, Ordering::SeqCst);
- }
- }
- }
- })
- .each(0..THREADS, |_| {
- for i in 0..COUNT {
- if let Ok(Some(n)) = q.force_push(i) {
- v[n].fetch_add(1, Ordering::SeqCst);
- }
- }
-
- t.fetch_sub(1, Ordering::SeqCst);
- })
- .run();
-
- for c in v {
- assert_eq!(c.load(Ordering::SeqCst), THREADS);
- }
-}
### external/vendor/concurrent-queue/tests/unbounded.rs
@@ -1,181 +0,0 @@
-#![allow(clippy::bool_assert_comparison)]
-
-use concurrent_queue::{ConcurrentQueue, PopError, PushError};
-
-#[cfg(not(target_family = "wasm"))]
-use easy_parallel::Parallel;
-#[cfg(not(target_family = "wasm"))]
-use std::sync::atomic::{AtomicUsize, Ordering};
-
-#[cfg(target_family = "wasm")]
-use wasm_bindgen_test::wasm_bindgen_test as test;
-
-#[test]
-fn smoke() {
- let q = ConcurrentQueue::unbounded();
- q.push(7).unwrap();
- assert_eq!(q.pop(), Ok(7));
-
- q.push(8).unwrap();
- assert_eq!(q.pop(), Ok(8));
- assert!(q.pop().is_err());
-}
-
-#[test]
-fn len_empty_full() {
- let q = ConcurrentQueue::unbounded();
-
- assert_eq!(q.len(), 0);
- assert_eq!(q.is_empty(), true);
-
- q.push(()).unwrap();
-
- assert_eq!(q.len(), 1);
- assert_eq!(q.is_empty(), false);
-
- q.pop().unwrap();
-
- assert_eq!(q.len(), 0);
- assert_eq!(q.is_empty(), true);
-}
-
-#[test]
-fn len() {
- let q = ConcurrentQueue::unbounded();
-
- assert_eq!(q.len(), 0);
-
- for i in 0..50 {
- q.push(i).unwrap();
- assert_eq!(q.len(), i + 1);
- }
-
- for i in 0..50 {
- q.pop().unwrap();
- assert_eq!(q.len(), 50 - i - 1);
- }
-
- assert_eq!(q.len(), 0);
-}
-
-#[test]
-fn close() {
- let q = ConcurrentQueue::unbounded();
- assert_eq!(q.push(10), Ok(()));
-
- assert!(!q.is_closed());
- assert!(q.close());
-
- assert!(q.is_closed());
- assert!(!q.close());
-
- assert_eq!(q.push(20), Err(PushError::Closed(20)));
- assert_eq!(q.pop(), Ok(10));
- assert_eq!(q.pop(), Err(PopError::Closed));
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn spsc() {
- const COUNT: usize = if cfg!(miri) { 100 } else { 100_000 };
-
- let q = ConcurrentQueue::unbounded();
-
- Parallel::new()
- .add(|| {
- for i in 0..COUNT {
- loop {
- if let Ok(x) = q.pop() {
- assert_eq!(x, i);
- break;
- }
- }
- }
- assert!(q.pop().is_err());
- })
- .add(|| {
- for i in 0..COUNT {
- q.push(i).unwrap();
- }
- })
- .run();
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn mpmc() {
- const COUNT: usize = if cfg!(miri) { 100 } else { 25_000 };
- const THREADS: usize = 4;
-
- let q = ConcurrentQueue::<usize>::unbounded();
- let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::<Vec<_>>();
-
- Parallel::new()
- .each(0..THREADS, |_| {
- for _ in 0..COUNT {
- let n = loop {
- if let Ok(x) = q.pop() {
- break x;
- }
- };
- v[n].fetch_add(1, Ordering::SeqCst);
- }
- })
- .each(0..THREADS, |_| {
- for i in 0..COUNT {
- q.push(i).unwrap();
- }
- })
- .run();
-
- for c in v {
- assert_eq!(c.load(Ordering::SeqCst), THREADS);
- }
-}
-
-#[cfg(not(target_family = "wasm"))]
-#[test]
-fn drops() {
- const RUNS: usize = if cfg!(miri) { 20 } else { 100 };
- const STEPS: usize = if cfg!(miri) { 100 } else { 10_000 };
-
- static DROPS: AtomicUsize = AtomicUsize::new(0);
-
- #[derive(Debug, PartialEq)]
- struct DropCounter;
-
- impl Drop for DropCounter {
- fn drop(&mut self) {
- DROPS.fetch_add(1, Ordering::SeqCst);
- }
- }
-
- for _ in 0..RUNS {
- let steps = fastrand::usize(0..STEPS);
- let additional = fastrand::usize(0..1000);
-
- DROPS.store(0, Ordering::SeqCst);
- let q = ConcurrentQueue::unbounded();
-
- Parallel::new()
- .add(|| {
- for _ in 0..steps {
- while q.pop().is_err() {}
- }
- })
- .add(|| {
- for _ in 0..steps {
- q.push(DropCounter).unwrap();
- }
- })
- .run();
-
- for _ in 0..additional {
- q.push(DropCounter).unwrap();
- }
-
- assert_eq!(DROPS.load(Ordering::SeqCst), steps);
- drop(q);
- assert_eq!(DROPS.load(Ordering::SeqCst), steps + additional);
- }
-}
### external/vendor/crossbeam-utils/.cargo-checksum.json
@@ -1 +0,0 @@
-{"files":{".cargo_vcs_info.json":"d43f49dbbe655cb91dcd62c862552f2ca4520eaff2e4bee391e01b0df968e358","CHANGELOG.md":"366caba01b88f421c71b97f61b9806abbf05e1ba0d24e4bf034191c1f8aa03b8","Cargo.toml":"961aa297754d8fdbae9e23d15bbbcfdcd2b50b2db56becddb84e8cba4f730713","Cargo.toml.orig":"6697cafee3a273f8c04e25c8606621b2fff8a779e3e1d01f9c08d225a0f36fc5","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"3c82bbb994f54ab76a9ed30a42dfd095c6e636258d379b9be3fbf66324310e71","benches/atomic_cell.rs":"c927eb3cd1e5ecc4b91adbc3bde98af15ffab4086190792ba64d5cde0e24df3d","build-common.rs":"502cb7494549bed6fa10ac7bea36e880eeb60290dc69b679ac5c92b376469562","build.rs":"7a7f9e56ea7fb4f78c4e532b84b9d27be719d600e85eaeb3a2f4b79a4f0b419c","no_atomic.rs":"fc1baa4489d9842988bacaaa545a7d7d0e2f8b93cfa0b7d1ae31f21256e4cb0a","src/atomic/atomic_cell.rs":"6d8b83b65c73644abc10ec88a1442c8db531ae140de79197901510fcaea45966","src/atomic/consume.rs":"381c2a8b13312ca0525d53ca1b7d0d4f525ddb154951fa3e216b061ad22012ff","src/atomic/mod.rs":"712e2337e710c07116e977154ea4247a1c065bf5599e6bf368138e715b403f6d","src/atomic/seq_lock.rs":"27182e6b87a9db73c5f6831759f8625f9fcdec3c2828204c444aef04f427735a","src/atomic/seq_lock_wide.rs":"9888dd03116bb89ca36d4ab8d5a0b5032107a2983a7eb8024454263b09080088","src/backoff.rs":"8715f0303ec91d1847c8ac3fc24bcc002a22a7284ade610e5eff4181f85827c7","src/cache_padded.rs":"b6ff04ecf6de9124c0069c014d35f37de543cff1c4bfc1f260586aa49a5af6d8","src/lib.rs":"060dabc6dc07de92a7afa57dcbc47222a95ef5819d543ad854858c3b329d6637","src/sync/mod.rs":"eca73c04f821859b8434d2b93db87d160dc6a3f65498ca201cd40d732ca4c134","src/sync/once_lock.rs":"aa8f957604d1119c4fc7038a18c14a6281230e81005f31201c099acff284ad4b","src/sync/parker.rs":"698996e7530da1f3815df11c89df7d916155229cbfd022cccbd555f1d1d31985","src/sync/sharded_lock.rs":"f96d536f5622fe2a0a0f7d8117be31e4b1ed607544c52c7e2ffcd1f51a6b93a1","src/sync/wait_group.rs":"3e339aab014f50e214fea535c841755113ea058153378ed54e50a4acb403c937","src/thread.rs":"04610787ba88f1f59549874a13fc037f2dcf4d8b5f1daaf08378f05c2b3c0039","tests/atomic_cell.rs":"716c864d4e103039dc5cd8bf6110da4cbabafc7e4e03819aa197828e8fb0a9c7","tests/cache_padded.rs":"1bfaff8354c8184e1ee1f902881ca9400b60effb273b0d3f752801a483d2b66d","tests/parker.rs":"6def4721287d9d70b1cfd63ebb34e1c83fbb3376edbad2bc8aac6ef69dd99d20","tests/sharded_lock.rs":"314adeb8a651a28935f7a49c9a261b8fa1fd82bf6a16c865a5aced6216d7e40b","tests/thread.rs":"9a7d7d3028c552fd834c68598b04a1cc252a816bc20ab62cec060d6cd09cab10","tests/wait_group.rs":"2a41533a5f7f113d19cd2bdafcc2abf86509109652274156efdd74abd00896b6"},"package":"d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"}
\ No newline at end of file
### external/vendor/crossbeam-utils/.cargo_vcs_info.json
@@ -1,6 +0,0 @@
-{
- "git": {
- "sha1": "ccd83ac4108a2a1b41e9c6e79c87267167d18dfa"
- },
- "path_in_vcs": "crossbeam-utils"
-}
\ No newline at end of file
### external/vendor/crossbeam-utils/CHANGELOG.md
@@ -1,243 +0,0 @@
-# Version 0.8.21
-
-- Improve implementation of `CachePadded`. (#1152)
-
-# Version 0.8.20
-
-- Implement `Display` for `CachePadded`. (#1097)
-
-# Version 0.8.19
-
-- Remove dependency on `cfg-if`. (#1072)
-
-# Version 0.8.18
-
-- Relax the minimum supported Rust version to 1.60. (#1056)
-- Improve scalability of `AtomicCell` fallback. (#1055)
-
-# Version 0.8.17
-
-- Bump the minimum supported Rust version to 1.61. (#1037)
-- Improve support for targets without atomic CAS or 64-bit atomic. (#1037)
-- Always implement `UnwindSafe` and `RefUnwindSafe` for `AtomicCell`. (#1045)
-- Improve compatibility with Miri, TSan, and loom. (#995, #1003)
-- Improve compatibility with unstable `oom=panic`. (#1045)
-- Improve implementation of `CachePadded`. (#1014, #1025)
-- Update `loom` dependency to 0.7.
-
-# Version 0.8.16
-
-- Improve implementation of `CachePadded`. (#967)
-
-# Version 0.8.15
-
-- Add `#[clippy::has_significant_drop]` to `ShardedLock{Read,Write}Guard`. (#958)
-- Improve handling of very large timeout. (#953)
-- Soft-deprecate `thread::scope()` in favor of the more efficient `std::thread::scope` that stabilized in Rust 1.63. (#954)
-
-# Version 0.8.14
-
-- Fix build script bug introduced in 0.8.13. (#932)
-
-# Version 0.8.13
-
-**Note:** This release has been yanked due to regression fixed in 0.8.14.
-
-- Improve support for custom targets. (#922)
-
-# Version 0.8.12
-
-- Removes the dependency on the `once_cell` crate to restore the MSRV. (#913)
-- Work around [rust-lang#98302](https://github.com/rust-lang/rust/issues/98302), which causes compile error on windows-gnu when LTO is enabled. (#913)
-
-# Version 0.8.11
-
-- Bump the minimum supported Rust version to 1.38. (#877)
-
-# Version 0.8.10
-
-- Fix unsoundness of `AtomicCell` on types containing niches. (#834)
- This fix contains breaking changes, but they are allowed because this is a soundness bug fix. See #834 for more.
-
-# Version 0.8.9
-
-- Replace lazy_static with once_cell. (#817)
-
-# Version 0.8.8
-
-- Fix a bug when unstable `loom` support is enabled. (#787)
-
-# Version 0.8.7
-
-- Add `AtomicCell<{i*,u*}>::{fetch_max,fetch_min}`. (#785)
-- Add `AtomicCell<{i*,u*,bool}>::fetch_nand`. (#785)
-- Fix unsoundness of `AtomicCell<{i,u}64>` arithmetics on 32-bit targets that support `Atomic{I,U}64` (#781)
-
-# Version 0.8.6
-
-**Note:** This release has been yanked. See [GHSA-qc84-gqf4-9926](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-qc84-gqf4-9926) for details.
-
-- Re-add `AtomicCell<{i,u}64>::{fetch_add,fetch_sub,fetch_and,fetch_or,fetch_xor}` that were accidentally removed in 0.8.0 on targets that do not support `Atomic{I,U}64`. (#767)
-- Re-add `AtomicCell<{i,u}128>::{fetch_add,fetch_sub,fetch_and,fetch_or,fetch_xor}` that were accidentally removed in 0.8.0. (#767)
-
-# Version 0.8.5
-
-**Note:** This release has been yanked. See [GHSA-qc84-gqf4-9926](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-qc84-gqf4-9926) for details.
-
-- Add `AtomicCell::fetch_update`. (#704)
-- Support targets that do not have atomic CAS on stable Rust. (#698)
-
-# Version 0.8.4
-
-**Note:** This release has been yanked. See [GHSA-qc84-gqf4-9926](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-qc84-gqf4-9926) for details.
-
-- Bump `loom` dependency to version 0.5. (#686)
-
-# Version 0.8.3
-
-**Note:** This release has been yanked. See [GHSA-qc84-gqf4-9926](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-qc84-gqf4-9926) for details.
-
-- Make `loom` dependency optional. (#666)
-
-# Version 0.8.2
-
-**Note:** This release has been yanked. See [GHSA-qc84-gqf4-9926](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-qc84-gqf4-9926) for details.
-
-- Deprecate `AtomicCell::compare_and_swap`. Use `AtomicCell::compare_exchange` instead. (#619)
-- Add `Parker::park_deadline`. (#563)
-- Improve implementation of `CachePadded`. (#636)
-- Add unstable support for `loom`. (#487)
-
-# Version 0.8.1
-
-**Note:** This release has been yanked. See [GHSA-qc84-gqf4-9926](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-qc84-gqf4-9926) for details.
-
-- Make `AtomicCell::is_lock_free` always const fn. (#600)
-- Fix a bug in `seq_lock_wide`. (#596)
-- Remove `const_fn` dependency. (#600)
-- `crossbeam-utils` no longer fails to compile if unable to determine rustc version. Instead, it now displays a warning. (#604)
-
-# Version 0.8.0
-
-**Note:** This release has been yanked. See [GHSA-qc84-gqf4-9926](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-qc84-gqf4-9926) for details.
-
-- Bump the minimum supported Rust version to 1.36.
-- Remove deprecated `AtomicCell::get_mut()` and `Backoff::is_complete()` methods.
-- Remove `alloc` feature.
-- Make `CachePadded::new()` const function.
-- Make `AtomicCell::is_lock_free()` const function at 1.46+.
-- Implement `From<T>` for `AtomicCell<T>`.
-
-# Version 0.7.2
-
-- Fix bug in release (yanking 0.7.1)
-
-# Version 0.7.1
-
-- Bump `autocfg` dependency to version 1.0. (#460)
-- Make `AtomicCell` lockfree for u8, u16, u32, u64 sized values at 1.34+. (#454)
-
-# Version 0.7.0
-
-- Bump the minimum required version to 1.28.
-- Fix breakage with nightly feature due to rust-lang/rust#65214.
-- Apply `#[repr(transparent)]` to `AtomicCell`.
-- Make `AtomicCell::new()` const function at 1.31+.
-
-# Version 0.6.6
-
-- Add `UnwindSafe` and `RefUnwindSafe` impls for `AtomicCell`.
-- Add `AtomicCell::as_ptr()`.
-- Add `AtomicCell::take()`.
-- Fix a bug in `AtomicCell::compare_exchange()` and `AtomicCell::compare_and_swap()`.
-- Various documentation improvements.
-
-# Version 0.6.5
-
-- Rename `Backoff::is_complete()` to `Backoff::is_completed()`.
-
-# Version 0.6.4
-
-- Add `WaitGroup`, `ShardedLock`, and `Backoff`.
-- Add `fetch_*` methods for `AtomicCell<i128>` and `AtomicCell<u128>`.
-- Expand documentation.
-
-# Version 0.6.3
-
-- Add `AtomicCell`.
-- Improve documentation.
-
-# Version 0.6.2
-
-- Add `Parker`.
-- Improve documentation.
-
-# Version 0.6.1
-
-- Fix a soundness bug in `Scope::spawn()`.
-- Remove the `T: 'scope` bound on `ScopedJoinHandle`.
-
-# Version 0.6.0
-
-- Move `AtomicConsume` to `atomic` module.
-- `scope()` returns a `Result` of thread joins.
-- Remove `spawn_unchecked`.
-- Fix a soundness bug due to incorrect lifetimes.
-- Improve documentation.
-- Support nested scoped spawns.
-- Implement `Copy`, `Hash`, `PartialEq`, and `Eq` for `CachePadded`.
-- Add `CachePadded::into_inner()`.
-
-# Version 0.5.0
-
-- Reorganize sub-modules and rename functions.
-
-# Version 0.4.1
-
-- Fix a documentation link.
-
-# Version 0.4.0
-
-- `CachePadded` supports types bigger than 64 bytes.
-- Fix a bug in scoped threads where unitialized memory was being dropped.
-- Minimum required Rust version is now 1.25.
-
-# Version 0.3.2
-
-- Mark `load_consume` with `#[inline]`.
-
-# Version 0.3.1
-
-- `load_consume` on ARM and AArch64.
-
-# Version 0.3.0
-
-- Add `join` for scoped thread API.
-- Add `load_consume` for atomic load-consume memory ordering.
-- Remove `AtomicOption`.
-
-# Version 0.2.2
-
-- Support Rust 1.12.1.
-- Call `T::clone` when cloning a `CachePadded<T>`.
-
-# Version 0.2.1
-
-- Add `use_std` feature.
-
-# Version 0.2.0
-
-- Add `nightly` feature.
-- Use `repr(align(64))` on `CachePadded` with the `nightly` feature.
-- Implement `Drop` for `CachePadded<T>`.
-- Implement `Clone` for `CachePadded<T>`.
-- Implement `From<T>` for `CachePadded<T>`.
-- Implement better `Debug` for `CachePadded<T>`.
-- Write more tests.
-- Add this changelog.
-- Change cache line length to 64 bytes.
-- Remove `ZerosValid`.
-
-# Version 0.1.0
-
-- Old implementation of `CachePadded` from `crossbeam` version 0.3.0
### external/vendor/crossbeam-utils/Cargo.toml
@@ -1,101 +0,0 @@
-# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
-#
-# When uploading crates to the registry Cargo will automatically
-# "normalize" Cargo.toml files for maximal compatibility
-# with all versions of Cargo and also rewrite `path` dependencies
-# to registry (e.g., crates.io) dependencies.
-#
-# If you are reading this file be aware that the original Cargo.toml
-# will likely look very different (and much more reasonable).
-# See Cargo.toml.orig for the original contents.
-
-[package]
-edition = "2021"
-rust-version = "1.60"
-name = "crossbeam-utils"
-version = "0.8.21"
-build = "build.rs"
-autolib = false
-autobins = false
-autoexamples = false
-autotests = false
-autobenches = false
-description = "Utilities for concurrent programming"
-homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-utils"
-readme = "README.md"
-keywords = [
- "scoped",
- "thread",
- "atomic",
- "cache",
-]
-categories = [
- "algorithms",
- "concurrency",
- "data-structures",
- "no-std",
-]
-license = "MIT OR Apache-2.0"
-repository = "https://github.com/crossbeam-rs/crossbeam"
-
-[lib]
-name = "crossbeam_utils"
-path = "src/lib.rs"
-
-[[test]]
-name = "atomic_cell"
-path = "tests/atomic_cell.rs"
-
-[[test]]
-name = "cache_padded"
-path = "tests/cache_padded.rs"
-
-[[test]]
-name = "parker"
-path = "tests/parker.rs"
-
-[[test]]
-name = "sharded_lock"
-path = "tests/sharded_lock.rs"
-
-[[test]]
-name = "thread"
-path = "tests/thread.rs"
-
-[[test]]
-name = "wait_group"
-path = "tests/wait_group.rs"
-
-[[bench]]
-name = "atomic_cell"
-path = "benches/atomic_cell.rs"
-
-[dependencies]
-
-[dev-dependencies.rand]
-version = "0.8"
-
-[features]
-default = ["std"]
-nightly = []
-std = []
-
-[target."cfg(crossbeam_loom)".dependencies.loom]
-version = "0.7.1"
-optional = true
-
-[lints.clippy.declare_interior_mutable_const]
-level = "allow"
-priority = 1
-
-[lints.clippy.lint_groups_priority]
-level = "allow"
-priority = 1
-
-[lints.rust.unexpected_cfgs]
-level = "warn"
-priority = 0
-check-cfg = [
- "cfg(crossbeam_loom)",
- "cfg(crossbeam_sanitize)",
-]
### external/vendor/crossbeam-utils/Cargo.toml.orig
@@ -1,46 +0,0 @@
-[package]
-name = "crossbeam-utils"
-# When publishing a new version:
-# - Update CHANGELOG.md
-# - Update README.md (when increasing major or minor version)
-# - Run './tools/publish.sh crossbeam-utils <version>'
-version = "0.8.21"
-edition = "2021"
-rust-version = "1.60"
-license = "MIT OR Apache-2.0"
-repository = "https://github.com/crossbeam-rs/crossbeam"
-homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-utils"
-description = "Utilities for concurrent programming"
-keywords = ["scoped", "thread", "atomic", "cache"]
-categories = ["algorithms", "concurrency", "data-structures", "no-std"]
-
-[features]
-default = ["std"]
-
-# Enable to use APIs that require `std`.
-# This is enabled by default.
-std = []
-
-# These features are no longer used.
-# TODO: remove in the next major version.
-# Enable to use of unstable functionality.
-# This is disabled by default and requires recent nightly compiler.
-#
-# NOTE: This feature is outside of the normal semver guarantees and minor or
-# patch versions of crossbeam may make breaking changes to them at any time.
-nightly = []
-
-[dependencies]
-
-# Enable the use of loom for concurrency testing.
-#
-# NOTE: This feature is outside of the normal semver guarantees and minor or
-# patch versions of crossbeam may make breaking changes to them at any time.
-[target.'cfg(crossbeam_loom)'.dependencies]
-loom = { version = "0.7.1", optional = true }
-
-[dev-dependencies]
-rand = "0.8"
-
-[lints]
-workspace = true
### external/vendor/crossbeam-utils/LICENSE-APACHE
@@ -1,201 +0,0 @@
- 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.
### external/vendor/crossbeam-utils/LICENSE-MIT
@@ -1,27 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2019 The Crossbeam Project Developers
-
-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.
### external/vendor/crossbeam-utils/README.md
@@ -1,73 +0,0 @@
-# Crossbeam Utils
-
-[](
-https://github.com/crossbeam-rs/crossbeam/actions)
-[](
-https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-utils#license)
-[](
-https://crates.io/crates/crossbeam-utils)
-[](
-https://docs.rs/crossbeam-utils)
-[](
-https://www.rust-lang.org)
-[](https://discord.com/invite/JXYwgWZ)
-
-This crate provides miscellaneous tools for concurrent programming:
-
-#### Atomics
-
-* [`AtomicCell`], a thread-safe mutable memory location.<sup>(no_std)</sup>
-* [`AtomicConsume`], for reading from primitive atomic types with "consume" ordering.<sup>(no_std)</sup>
-
-#### Thread synchronization
-
-* [`Parker`], a thread parking primitive.
-* [`ShardedLock`], a sharded reader-writer lock with fast concurrent reads.
-* [`WaitGroup`], for synchronizing the beginning or end of some computation.
-
-#### Utilities
-
-* [`Backoff`], for exponential backoff in spin loops.<sup>(no_std)</sup>
-* [`CachePadded`], for padding and aligning a value to the length of a cache line.<sup>(no_std)</sup>
-* [`scope`], for spawning threads that borrow local variables from the stack.
-
-*Features marked with <sup>(no_std)</sup> can be used in `no_std` environments.*<br/>
-
-[`AtomicCell`]: https://docs.rs/crossbeam-utils/*/crossbeam_utils/atomic/struct.AtomicCell.html
-[`AtomicConsume`]: https://docs.rs/crossbeam-utils/*/crossbeam_utils/atomic/trait.AtomicConsume.html
-[`Parker`]: https://docs.rs/crossbeam-utils/*/crossbeam_utils/sync/struct.Parker.html
-[`ShardedLock`]: https://docs.rs/crossbeam-utils/*/crossbeam_utils/sync/struct.ShardedLock.html
-[`WaitGroup`]: https://docs.rs/crossbeam-utils/*/crossbeam_utils/sync/struct.WaitGroup.html
-[`Backoff`]: https://docs.rs/crossbeam-utils/*/crossbeam_utils/struct.Backoff.html
-[`CachePadded`]: https://docs.rs/crossbeam-utils/*/crossbeam_utils/struct.CachePadded.html
-[`scope`]: https://docs.rs/crossbeam-utils/*/crossbeam_utils/thread/fn.scope.html
-
-## Usage
-
-Add this to your `Cargo.toml`:
-
-```toml
-[dependencies]
-crossbeam-utils = "0.8"
-```
-
-## Compatibility
-
-Crossbeam Utils supports stable Rust releases going back at least six months,
-and every time the minimum supported Rust version is increased, a new minor
-version is released. Currently, the minimum supported Rust version is 1.60.
-
-## License
-
-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.
-
-#### Contribution
-
-Unless you explicitly state otherwise, any contribution intentionally submitted
-for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
-dual licensed as above, without any additional terms or conditions.
### external/vendor/crossbeam-utils/benches/atomic_cell.rs
@@ -1,156 +0,0 @@
-#![feature(test)]
-
-extern crate test;
-
-use std::sync::Barrier;
-
-use crossbeam_utils::atomic::AtomicCell;
-use crossbeam_utils::thread;
-
-#[bench]
-fn load_u8(b: &mut test::Bencher) {
- let a = AtomicCell::new(0u8);
- let mut sum = 0;
- b.iter(|| sum += a.load());
- test::black_box(sum);
-}
-
-#[bench]
-fn store_u8(b: &mut test::Bencher) {
- let a = AtomicCell::new(0u8);
- b.iter(|| a.store(1));
-}
-
-#[bench]
-fn fetch_add_u8(b: &mut test::Bencher) {
- let a = AtomicCell::new(0u8);
- b.iter(|| a.fetch_add(1));
-}
-
-#[bench]
-fn compare_exchange_u8(b: &mut test::Bencher) {
- let a = AtomicCell::new(0u8);
- let mut i = 0;
- b.iter(|| {
- let _ = a.compare_exchange(i, i.wrapping_add(1));
- i = i.wrapping_add(1);
- });
-}
-
-#[bench]
-fn concurrent_load_u8(b: &mut test::Bencher) {
- const THREADS: usize = 2;
- const STEPS: usize = 1_000_000;
-
- let start = Barrier::new(THREADS + 1);
- let end = Barrier::new(THREADS + 1);
- let exit = AtomicCell::new(false);
-
- let a = AtomicCell::new(0u8);
-
- thread::scope(|scope| {
- for _ in 0..THREADS {
- scope.spawn(|_| loop {
- start.wait();
-
- let mut sum = 0;
- for _ in 0..STEPS {
- sum += a.load();
- }
- test::black_box(sum);
-
- end.wait();
- if exit.load() {
- break;
- }
- });
- }
-
- start.wait();
- end.wait();
-
- b.iter(|| {
- start.wait();
- end.wait();
- });
-
- start.wait();
- exit.store(true);
- end.wait();
- })
- .unwrap();
-}
-
-#[bench]
-fn load_usize(b: &mut test::Bencher) {
- let a = AtomicCell::new(0usize);
- let mut sum = 0;
- b.iter(|| sum += a.load());
- test::black_box(sum);
-}
-
-#[bench]
-fn store_usize(b: &mut test::Bencher) {
- let a = AtomicCell::new(0usize);
- b.iter(|| a.store(1));
-}
-
-#[bench]
-fn fetch_add_usize(b: &mut test::Bencher) {
- let a = AtomicCell::new(0usize);
- b.iter(|| a.fetch_add(1));
-}
-
-#[bench]
-fn compare_exchange_usize(b: &mut test::Bencher) {
- let a = AtomicCell::new(0usize);
- let mut i = 0;
- b.iter(|| {
- let _ = a.compare_exchange(i, i.wrapping_add(1));
- i = i.wrapping_add(1);
- });
-}
-
-#[bench]
-fn concurrent_load_usize(b: &mut test::Bencher) {
- const THREADS: usize = 2;
- const STEPS: usize = 1_000_000;
-
- let start = Barrier::new(THREADS + 1);
- let end = Barrier::new(THREADS + 1);
- let exit = AtomicCell::new(false);
-
- let a = AtomicCell::new(0usize);
-
- thread::scope(|scope| {
- for _ in 0..THREADS {
- scope.spawn(|_| loop {
- start.wait();
-
- let mut sum = 0;
- for _ in 0..STEPS {
- sum += a.load();
- }
- test::black_box(sum);
-
- end.wait();
- if exit.load() {
- break;
- }
- });
- }
-
- start.wait();
- end.wait();
-
- b.iter(|| {
- start.wait();
- end.wait();
- });
-
- start.wait();
- exit.store(true);
- end.wait();
- })
- .unwrap();
-}
### external/vendor/crossbeam-utils/build-common.rs
@@ -1,13 +0,0 @@
-// The target triplets have the form of 'arch-vendor-system'.
-//
-// When building for Linux (e.g. the 'system' part is
-// 'linux-something'), replace the vendor with 'unknown'
-// so that mapping to rust standard targets happens correctly.
-fn convert_custom_linux_target(target: String) -> String {
- let mut parts: Vec<&str> = target.split('-').collect();
- let system = parts.get(2);
- if system == Some(&"linux") {
- parts[1] = "unknown";
- };
- parts.join("-")
-}
### external/vendor/crossbeam-utils/build.rs
@@ -1,48 +0,0 @@
-// The rustc-cfg listed below are considered public API, but it is *unstable*
-// and outside of the normal semver guarantees:
-//
-// - `crossbeam_no_atomic`
-// Assume the target does *not* support any atomic operations.
-// This is usually detected automatically by the build script, but you may
-// need to enable it manually when building for custom targets or using
-// non-cargo build systems that don't run the build script.
-//
-// With the exceptions mentioned above, the rustc-cfg emitted by the build
-// script are *not* public API.
-
-#![warn(rust_2018_idioms)]
-
-use std::env;
-
-include!("no_atomic.rs");
-include!("build-common.rs");
-
-fn main() {
- println!("cargo:rerun-if-changed=no_atomic.rs");
- println!("cargo:rustc-check-cfg=cfg(crossbeam_no_atomic,crossbeam_sanitize_thread)");
-
- let target = match env::var("TARGET") {
- Ok(target) => convert_custom_linux_target(target),
- Err(e) => {
- println!(
- "cargo:warning={}: unable to get TARGET environment variable: {}",
- env!("CARGO_PKG_NAME"),
- e
- );
- return;
- }
- };
-
- // Note that this is `no_`*, not `has_*`. This allows treating as the latest
- // stable rustc is used when the build script doesn't run. This is useful
- // for non-cargo build systems that don't run the build script.
- if NO_ATOMIC.contains(&&*target) {
- println!("cargo:rustc-cfg=crossbeam_no_atomic");
- }
-
- // `cfg(sanitize = "..")` is not stabilized.
- let sanitize = env::var("CARGO_CFG_SANITIZE").unwrap_or_default();
- if sanitize.contains("thread") {
- println!("cargo:rustc-cfg=crossbeam_sanitize_thread");
- }
-}
### external/vendor/crossbeam-utils/no_atomic.rs
@@ -1,9 +0,0 @@
-// This file is @generated by no_atomic.sh.
-// It is not intended for manual editing.
-
-const NO_ATOMIC: &[&str] = &[
- "bpfeb-unknown-none",
- "bpfel-unknown-none",
- "mipsel-sony-psx",
- "msp430-none-elf",
-];
### external/vendor/crossbeam-utils/src/atomic/atomic_cell.rs
@@ -1,1182 +0,0 @@
-// Necessary for implementing atomic methods for `AtomicUnit`
-#![allow(clippy::unit_arg)]
-
-use crate::primitive::sync::atomic::{self, Ordering};
-use crate::CachePadded;
-use core::cell::UnsafeCell;
-use core::cmp;
-use core::fmt;
-use core::mem::{self, ManuallyDrop, MaybeUninit};
-use core::panic::{RefUnwindSafe, UnwindSafe};
-use core::ptr;
-
-use super::seq_lock::SeqLock;
-
-/// A thread-safe mutable memory location.
-///
-/// This type is equivalent to [`Cell`], except it can also be shared among multiple threads.
-///
-/// Operations on `AtomicCell`s use atomic instructions whenever possible, and synchronize using
-/// global locks otherwise. You can call [`AtomicCell::<T>::is_lock_free()`] to check whether
-/// atomic instructions or locks will be used.
-///
-/// Atomic loads use the [`Acquire`] ordering and atomic stores use the [`Release`] ordering.
-///
-/// [`Cell`]: std::cell::Cell
-/// [`AtomicCell::<T>::is_lock_free()`]: AtomicCell::is_lock_free
-/// [`Acquire`]: std::sync::atomic::Ordering::Acquire
-/// [`Release`]: std::sync::atomic::Ordering::Release
-#[repr(transparent)]
-pub struct AtomicCell<T> {
- /// The inner value.
- ///
- /// If this value can be transmuted into a primitive atomic type, it will be treated as such.
- /// Otherwise, all potentially concurrent operations on this data will be protected by a global
- /// lock.
- ///
- /// Using MaybeUninit to prevent code outside the cell from observing partially initialized state:
- /// <https://github.com/crossbeam-rs/crossbeam/issues/833>
- /// (This rustc bug has been fixed in Rust 1.64.)
- ///
- /// Note:
- /// - we'll never store uninitialized `T` due to our API only using initialized `T`.
- /// - this `MaybeUninit` does *not* fix <https://github.com/crossbeam-rs/crossbeam/issues/315>.
- value: UnsafeCell<MaybeUninit<T>>,
-}
-
-unsafe impl<T: Send> Send for AtomicCell<T> {}
-unsafe impl<T: Send> Sync for AtomicCell<T> {}
-
-impl<T> UnwindSafe for AtomicCell<T> {}
-impl<T> RefUnwindSafe for AtomicCell<T> {}
-
-impl<T> AtomicCell<T> {
- /// Creates a new atomic cell initialized with `val`.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(7);
- /// ```
- pub const fn new(val: T) -> AtomicCell<T> {
- AtomicCell {
- value: UnsafeCell::new(MaybeUninit::new(val)),
- }
- }
-
- /// Consumes the atomic and returns the contained value.
- ///
- /// This is safe because passing `self` by value guarantees that no other threads are
- /// concurrently accessing the atomic data.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(7);
- /// let v = a.into_inner();
- ///
- /// assert_eq!(v, 7);
- /// ```
- pub fn into_inner(self) -> T {
- let this = ManuallyDrop::new(self);
- // SAFETY:
- // - passing `self` by value guarantees that no other threads are concurrently
- // accessing the atomic data
- // - the raw pointer passed in is valid because we got it from an owned value.
- // - `ManuallyDrop` prevents double dropping `T`
- unsafe { this.as_ptr().read() }
- }
-
- /// Returns `true` if operations on values of this type are lock-free.
- ///
- /// If the compiler or the platform doesn't support the necessary atomic instructions,
- /// `AtomicCell<T>` will use global locks for every potentially concurrent atomic operation.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// // This type is internally represented as `AtomicUsize` so we can just use atomic
- /// // operations provided by it.
- /// assert_eq!(AtomicCell::<usize>::is_lock_free(), true);
- ///
- /// // A wrapper struct around `isize`.
- /// struct Foo {
- /// bar: isize,
- /// }
- /// // `AtomicCell<Foo>` will be internally represented as `AtomicIsize`.
- /// assert_eq!(AtomicCell::<Foo>::is_lock_free(), true);
- ///
- /// // Operations on zero-sized types are always lock-free.
- /// assert_eq!(AtomicCell::<()>::is_lock_free(), true);
- ///
- /// // Very large types cannot be represented as any of the standard atomic types, so atomic
- /// // operations on them will have to use global locks for synchronization.
- /// assert_eq!(AtomicCell::<[u8; 1000]>::is_lock_free(), false);
- /// ```
- pub const fn is_lock_free() -> bool {
- atomic_is_lock_free::<T>()
- }
-
- /// Stores `val` into the atomic cell.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(7);
- ///
- /// assert_eq!(a.load(), 7);
- /// a.store(8);
- /// assert_eq!(a.load(), 8);
- /// ```
- pub fn store(&self, val: T) {
- if mem::needs_drop::<T>() {
- drop(self.swap(val));
- } else {
- unsafe {
- atomic_store(self.as_ptr(), val);
- }
- }
- }
-
- /// Stores `val` into the atomic cell and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(7);
- ///
- /// assert_eq!(a.load(), 7);
- /// assert_eq!(a.swap(8), 7);
- /// assert_eq!(a.load(), 8);
- /// ```
- pub fn swap(&self, val: T) -> T {
- unsafe { atomic_swap(self.as_ptr(), val) }
- }
-
- /// Returns a raw pointer to the underlying data in this atomic cell.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(5);
- ///
- /// let ptr = a.as_ptr();
- /// ```
- #[inline]
- pub fn as_ptr(&self) -> *mut T {
- self.value.get().cast::<T>()
- }
-}
-
-impl<T: Default> AtomicCell<T> {
- /// Takes the value of the atomic cell, leaving `Default::default()` in its place.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(5);
- /// let five = a.take();
- ///
- /// assert_eq!(five, 5);
- /// assert_eq!(a.into_inner(), 0);
- /// ```
- pub fn take(&self) -> T {
- self.swap(Default::default())
- }
-}
-
-impl<T: Copy> AtomicCell<T> {
- /// Loads a value from the atomic cell.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(7);
- ///
- /// assert_eq!(a.load(), 7);
- /// ```
- pub fn load(&self) -> T {
- unsafe { atomic_load(self.as_ptr()) }
- }
-}
-
-impl<T: Copy + Eq> AtomicCell<T> {
- /// If the current value equals `current`, stores `new` into the atomic cell.
- ///
- /// The return value is always the previous value. If it is equal to `current`, then the value
- /// was updated.
- ///
- /// # Examples
- ///
- /// ```
- /// # #![allow(deprecated)]
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(1);
- ///
- /// assert_eq!(a.compare_and_swap(2, 3), 1);
- /// assert_eq!(a.load(), 1);
- ///
- /// assert_eq!(a.compare_and_swap(1, 2), 1);
- /// assert_eq!(a.load(), 2);
- /// ```
- // TODO: remove in the next major version.
- #[deprecated(note = "Use `compare_exchange` instead")]
- pub fn compare_and_swap(&self, current: T, new: T) -> T {
- match self.compare_exchange(current, new) {
- Ok(v) => v,
- Err(v) => v,
- }
- }
-
- /// If the current value equals `current`, stores `new` into the atomic cell.
- ///
- /// The return value is a result indicating whether the new value was written and containing
- /// the previous value. On success this value is guaranteed to be equal to `current`.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(1);
- ///
- /// assert_eq!(a.compare_exchange(2, 3), Err(1));
- /// assert_eq!(a.load(), 1);
- ///
- /// assert_eq!(a.compare_exchange(1, 2), Ok(1));
- /// assert_eq!(a.load(), 2);
- /// ```
- pub fn compare_exchange(&self, current: T, new: T) -> Result<T, T> {
- unsafe { atomic_compare_exchange_weak(self.as_ptr(), current, new) }
- }
-
- /// Fetches the value, and applies a function to it that returns an optional
- /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
- /// `Err(previous_value)`.
- ///
- /// Note: This may call the function multiple times if the value has been changed from other threads in
- /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
- /// only once to the stored value.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(7);
- /// assert_eq!(a.fetch_update(|_| None), Err(7));
- /// assert_eq!(a.fetch_update(|a| Some(a + 1)), Ok(7));
- /// assert_eq!(a.fetch_update(|a| Some(a + 1)), Ok(8));
- /// assert_eq!(a.load(), 9);
- /// ```
- #[inline]
- pub fn fetch_update<F>(&self, mut f: F) -> Result<T, T>
- where
- F: FnMut(T) -> Option<T>,
- {
- let mut prev = self.load();
- while let Some(next) = f(prev) {
- match self.compare_exchange(prev, next) {
- x @ Ok(_) => return x,
- Err(next_prev) => prev = next_prev,
- }
- }
- Err(prev)
- }
-}
-
-// `MaybeUninit` prevents `T` from being dropped, so we need to implement `Drop`
-// for `AtomicCell` to avoid leaks of non-`Copy` types.
-impl<T> Drop for AtomicCell<T> {
- fn drop(&mut self) {
- if mem::needs_drop::<T>() {
- // SAFETY:
- // - the mutable reference guarantees that no other threads are concurrently accessing the atomic data
- // - the raw pointer passed in is valid because we got it from a reference
- // - `MaybeUninit` prevents double dropping `T`
- unsafe {
- self.as_ptr().drop_in_place();
- }
- }
- }
-}
-
-macro_rules! atomic {
- // If values of type `$t` can be transmuted into values of the primitive atomic type `$atomic`,
- // declares variable `$a` of type `$atomic` and executes `$atomic_op`, breaking out of the loop.
- (@check, $t:ty, $atomic:ty, $a:ident, $atomic_op:expr) => {
- if can_transmute::<$t, $atomic>() {
- let $a: &$atomic;
- break $atomic_op;
- }
- };
-
- // If values of type `$t` can be transmuted into values of a primitive atomic type, declares
- // variable `$a` of that type and executes `$atomic_op`. Otherwise, just executes
- // `$fallback_op`.
- ($t:ty, $a:ident, $atomic_op:expr, $fallback_op:expr) => {
- loop {
- atomic!(@check, $t, AtomicUnit, $a, $atomic_op);
-
- atomic!(@check, $t, atomic::AtomicU8, $a, $atomic_op);
- atomic!(@check, $t, atomic::AtomicU16, $a, $atomic_op);
- atomic!(@check, $t, atomic::AtomicU32, $a, $atomic_op);
- #[cfg(target_has_atomic = "64")]
- atomic!(@check, $t, atomic::AtomicU64, $a, $atomic_op);
- // TODO: AtomicU128 is unstable
- // atomic!(@check, $t, atomic::AtomicU128, $a, $atomic_op);
-
- break $fallback_op;
- }
- };
-}
-
-macro_rules! impl_arithmetic {
- ($t:ty, fallback, $example:tt) => {
- impl AtomicCell<$t> {
- /// Increments the current value by `val` and returns the previous value.
- ///
- /// The addition wraps on overflow.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_add(3), 7);
- /// assert_eq!(a.load(), 10);
- /// ```
- #[inline]
- pub fn fetch_add(&self, val: $t) -> $t {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value = value.wrapping_add(val);
- old
- }
-
- /// Decrements the current value by `val` and returns the previous value.
- ///
- /// The subtraction wraps on overflow.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_sub(3), 7);
- /// assert_eq!(a.load(), 4);
- /// ```
- #[inline]
- pub fn fetch_sub(&self, val: $t) -> $t {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value = value.wrapping_sub(val);
- old
- }
-
- /// Applies bitwise "and" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_and(3), 7);
- /// assert_eq!(a.load(), 3);
- /// ```
- #[inline]
- pub fn fetch_and(&self, val: $t) -> $t {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value &= val;
- old
- }
-
- /// Applies bitwise "nand" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_nand(3), 7);
- /// assert_eq!(a.load(), !(7 & 3));
- /// ```
- #[inline]
- pub fn fetch_nand(&self, val: $t) -> $t {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value = !(old & val);
- old
- }
-
- /// Applies bitwise "or" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_or(16), 7);
- /// assert_eq!(a.load(), 23);
- /// ```
- #[inline]
- pub fn fetch_or(&self, val: $t) -> $t {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value |= val;
- old
- }
-
- /// Applies bitwise "xor" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_xor(2), 7);
- /// assert_eq!(a.load(), 5);
- /// ```
- #[inline]
- pub fn fetch_xor(&self, val: $t) -> $t {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value ^= val;
- old
- }
-
- /// Compares and sets the maximum of the current value and `val`,
- /// and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_max(2), 7);
- /// assert_eq!(a.load(), 7);
- /// ```
- #[inline]
- pub fn fetch_max(&self, val: $t) -> $t {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value = cmp::max(old, val);
- old
- }
-
- /// Compares and sets the minimum of the current value and `val`,
- /// and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_min(2), 7);
- /// assert_eq!(a.load(), 2);
- /// ```
- #[inline]
- pub fn fetch_min(&self, val: $t) -> $t {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value = cmp::min(old, val);
- old
- }
- }
- };
- ($t:ty, $atomic:ident, $example:tt) => {
- impl AtomicCell<$t> {
- /// Increments the current value by `val` and returns the previous value.
- ///
- /// The addition wraps on overflow.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_add(3), 7);
- /// assert_eq!(a.load(), 10);
- /// ```
- #[inline]
- pub fn fetch_add(&self, val: $t) -> $t {
- atomic! {
- $t, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::$atomic) };
- a.fetch_add(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value = value.wrapping_add(val);
- old
- }
- }
- }
-
- /// Decrements the current value by `val` and returns the previous value.
- ///
- /// The subtraction wraps on overflow.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_sub(3), 7);
- /// assert_eq!(a.load(), 4);
- /// ```
- #[inline]
- pub fn fetch_sub(&self, val: $t) -> $t {
- atomic! {
- $t, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::$atomic) };
- a.fetch_sub(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value = value.wrapping_sub(val);
- old
- }
- }
- }
-
- /// Applies bitwise "and" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_and(3), 7);
- /// assert_eq!(a.load(), 3);
- /// ```
- #[inline]
- pub fn fetch_and(&self, val: $t) -> $t {
- atomic! {
- $t, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::$atomic) };
- a.fetch_and(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value &= val;
- old
- }
- }
- }
-
- /// Applies bitwise "nand" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_nand(3), 7);
- /// assert_eq!(a.load(), !(7 & 3));
- /// ```
- #[inline]
- pub fn fetch_nand(&self, val: $t) -> $t {
- atomic! {
- $t, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::$atomic) };
- a.fetch_nand(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value = !(old & val);
- old
- }
- }
- }
-
- /// Applies bitwise "or" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_or(16), 7);
- /// assert_eq!(a.load(), 23);
- /// ```
- #[inline]
- pub fn fetch_or(&self, val: $t) -> $t {
- atomic! {
- $t, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::$atomic) };
- a.fetch_or(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value |= val;
- old
- }
- }
- }
-
- /// Applies bitwise "xor" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_xor(2), 7);
- /// assert_eq!(a.load(), 5);
- /// ```
- #[inline]
- pub fn fetch_xor(&self, val: $t) -> $t {
- atomic! {
- $t, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::$atomic) };
- a.fetch_xor(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value ^= val;
- old
- }
- }
- }
-
- /// Compares and sets the maximum of the current value and `val`,
- /// and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_max(9), 7);
- /// assert_eq!(a.load(), 9);
- /// ```
- #[inline]
- pub fn fetch_max(&self, val: $t) -> $t {
- atomic! {
- $t, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::$atomic) };
- a.fetch_max(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value = cmp::max(old, val);
- old
- }
- }
- }
-
- /// Compares and sets the minimum of the current value and `val`,
- /// and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- #[doc = $example]
- ///
- /// assert_eq!(a.fetch_min(2), 7);
- /// assert_eq!(a.load(), 2);
- /// ```
- #[inline]
- pub fn fetch_min(&self, val: $t) -> $t {
- atomic! {
- $t, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::$atomic) };
- a.fetch_min(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value = cmp::min(old, val);
- old
- }
- }
- }
- }
- };
-}
-
-impl_arithmetic!(u8, AtomicU8, "let a = AtomicCell::new(7u8);");
-impl_arithmetic!(i8, AtomicI8, "let a = AtomicCell::new(7i8);");
-impl_arithmetic!(u16, AtomicU16, "let a = AtomicCell::new(7u16);");
-impl_arithmetic!(i16, AtomicI16, "let a = AtomicCell::new(7i16);");
-
-impl_arithmetic!(u32, AtomicU32, "let a = AtomicCell::new(7u32);");
-impl_arithmetic!(i32, AtomicI32, "let a = AtomicCell::new(7i32);");
-
-#[cfg(target_has_atomic = "64")]
-impl_arithmetic!(u64, AtomicU64, "let a = AtomicCell::new(7u64);");
-#[cfg(target_has_atomic = "64")]
-impl_arithmetic!(i64, AtomicI64, "let a = AtomicCell::new(7i64);");
-#[cfg(not(target_has_atomic = "64"))]
-impl_arithmetic!(u64, fallback, "let a = AtomicCell::new(7u64);");
-#[cfg(not(target_has_atomic = "64"))]
-impl_arithmetic!(i64, fallback, "let a = AtomicCell::new(7i64);");
-
-// TODO: AtomicU128 is unstable
-// impl_arithmetic!(u128, AtomicU128, "let a = AtomicCell::new(7u128);");
-// impl_arithmetic!(i128, AtomicI128, "let a = AtomicCell::new(7i128);");
-impl_arithmetic!(u128, fallback, "let a = AtomicCell::new(7u128);");
-impl_arithmetic!(i128, fallback, "let a = AtomicCell::new(7i128);");
-
-impl_arithmetic!(usize, AtomicUsize, "let a = AtomicCell::new(7usize);");
-impl_arithmetic!(isize, AtomicIsize, "let a = AtomicCell::new(7isize);");
-
-impl AtomicCell<bool> {
- /// Applies logical "and" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(true);
- ///
- /// assert_eq!(a.fetch_and(true), true);
- /// assert_eq!(a.load(), true);
- ///
- /// assert_eq!(a.fetch_and(false), true);
- /// assert_eq!(a.load(), false);
- /// ```
- #[inline]
- pub fn fetch_and(&self, val: bool) -> bool {
- atomic! {
- bool, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::AtomicBool) };
- a.fetch_and(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value &= val;
- old
- }
- }
- }
-
- /// Applies logical "nand" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(true);
- ///
- /// assert_eq!(a.fetch_nand(false), true);
- /// assert_eq!(a.load(), true);
- ///
- /// assert_eq!(a.fetch_nand(true), true);
- /// assert_eq!(a.load(), false);
- ///
- /// assert_eq!(a.fetch_nand(false), false);
- /// assert_eq!(a.load(), true);
- /// ```
- #[inline]
- pub fn fetch_nand(&self, val: bool) -> bool {
- atomic! {
- bool, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::AtomicBool) };
- a.fetch_nand(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value = !(old & val);
- old
- }
- }
- }
-
- /// Applies logical "or" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(false);
- ///
- /// assert_eq!(a.fetch_or(false), false);
- /// assert_eq!(a.load(), false);
- ///
- /// assert_eq!(a.fetch_or(true), false);
- /// assert_eq!(a.load(), true);
- /// ```
- #[inline]
- pub fn fetch_or(&self, val: bool) -> bool {
- atomic! {
- bool, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::AtomicBool) };
- a.fetch_or(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value |= val;
- old
- }
- }
- }
-
- /// Applies logical "xor" to the current value and returns the previous value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::atomic::AtomicCell;
- ///
- /// let a = AtomicCell::new(true);
- ///
- /// assert_eq!(a.fetch_xor(false), true);
- /// assert_eq!(a.load(), true);
- ///
- /// assert_eq!(a.fetch_xor(true), true);
- /// assert_eq!(a.load(), false);
- /// ```
- #[inline]
- pub fn fetch_xor(&self, val: bool) -> bool {
- atomic! {
- bool, _a,
- {
- let a = unsafe { &*(self.as_ptr() as *const atomic::AtomicBool) };
- a.fetch_xor(val, Ordering::AcqRel)
- },
- {
- let _guard = lock(self.as_ptr() as usize).write();
- let value = unsafe { &mut *(self.as_ptr()) };
- let old = *value;
- *value ^= val;
- old
- }
- }
- }
-}
-
-impl<T: Default> Default for AtomicCell<T> {
- fn default() -> AtomicCell<T> {
- AtomicCell::new(T::default())
- }
-}
-
-impl<T> From<T> for AtomicCell<T> {
- #[inline]
- fn from(val: T) -> AtomicCell<T> {
- AtomicCell::new(val)
- }
-}
-
-impl<T: Copy + fmt::Debug> fmt::Debug for AtomicCell<T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("AtomicCell")
- .field("value", &self.load())
- .finish()
- }
-}
-
-/// Returns `true` if values of type `A` can be transmuted into values of type `B`.
-const fn can_transmute<A, B>() -> bool {
- // Sizes must be equal, but alignment of `A` must be greater or equal than that of `B`.
- (mem::size_of::<A>() == mem::size_of::<B>()) & (mem::align_of::<A>() >= mem::align_of::<B>())
-}
-
-/// Returns a reference to the global lock associated with the `AtomicCell` at address `addr`.
-///
-/// This function is used to protect atomic data which doesn't fit into any of the primitive atomic
-/// types in `std::sync::atomic`. Operations on such atomics must therefore use a global lock.
-///
-/// However, there is not only one global lock but an array of many locks, and one of them is
-/// picked based on the given address. Having many locks reduces contention and improves
-/// scalability.
-#[inline]
-#[must_use]
-fn lock(addr: usize) -> &'static SeqLock {
- // The number of locks is a prime number because we want to make sure `addr % LEN` gets
- // dispersed across all locks.
- //
- // Note that addresses are always aligned to some power of 2, depending on type `T` in
- // `AtomicCell<T>`. If `LEN` was an even number, then `addr % LEN` would be an even number,
- // too, which means only half of the locks would get utilized!
- //
- // It is also possible for addresses to accidentally get aligned to a number that is not a
- // power of 2. Consider this example:
- //
- // ```
- // #[repr(C)]
- // struct Foo {
- // a: AtomicCell<u8>,
- // b: u8,
- // c: u8,
- // }
- // ```
- //
- // Now, if we have a slice of type `&[Foo]`, it is possible that field `a` in all items gets
- // stored at addresses that are multiples of 3. It'd be too bad if `LEN` was divisible by 3.
- // In order to protect from such cases, we simply choose a large prime number for `LEN`.
- const LEN: usize = 67;
- const L: CachePadded<SeqLock> = CachePadded::new(SeqLock::new());
- static LOCKS: [CachePadded<SeqLock>; LEN] = [L; LEN];
-
- // If the modulus is a constant number, the compiler will use crazy math to transform this into
- // a sequence of cheap arithmetic operations rather than using the slow modulo instruction.
- &LOCKS[addr % LEN]
-}
-
-/// An atomic `()`.
-///
-/// All operations are noops.
-struct AtomicUnit;
-
-impl AtomicUnit {
- #[inline]
- fn load(&self, _order: Ordering) {}
-
- #[inline]
- fn store(&self, _val: (), _order: Ordering) {}
-
- #[inline]
- fn swap(&self, _val: (), _order: Ordering) {}
-
- #[inline]
- fn compare_exchange_weak(
- &self,
- _current: (),
- _new: (),
- _success: Ordering,
- _failure: Ordering,
- ) -> Result<(), ()> {
- Ok(())
- }
-}
-
-/// Returns `true` if operations on `AtomicCell<T>` are lock-free.
-const fn atomic_is_lock_free<T>() -> bool {
- atomic! { T, _a, true, false }
-}
-
-/// Atomically reads data from `src`.
-///
-/// This operation uses the `Acquire` ordering. If possible, an atomic instructions is used, and a
-/// global lock otherwise.
-unsafe fn atomic_load<T>(src: *mut T) -> T
-where
- T: Copy,
-{
- atomic! {
- T, a,
- {
- a = &*(src as *const _ as *const _);
- mem::transmute_copy(&a.load(Ordering::Acquire))
- },
- {
- let lock = lock(src as usize);
-
- // Try doing an optimistic read first.
- if let Some(stamp) = lock.optimistic_read() {
- // We need a volatile read here because other threads might concurrently modify the
- // value. In theory, data races are *always* UB, even if we use volatile reads and
- // discard the data when a data race is detected. The proper solution would be to
- // do atomic reads and atomic writes, but we can't atomically read and write all
- // kinds of data since `AtomicU8` is not available on stable Rust yet.
- // Load as `MaybeUninit` because we may load a value that is not valid as `T`.
- let val = ptr::read_volatile(src.cast::<MaybeUninit<T>>());
-
- if lock.validate_read(stamp) {
- return val.assume_init();
- }
- }
-
- // Grab a regular write lock so that writers don't starve this load.
- let guard = lock.write();
- let val = ptr::read(src);
- // The value hasn't been changed. Drop the guard without incrementing the stamp.
- guard.abort();
- val
- }
- }
-}
-
-/// Atomically writes `val` to `dst`.
-///
-/// This operation uses the `Release` ordering. If possible, an atomic instructions is used, and a
-/// global lock otherwise.
-unsafe fn atomic_store<T>(dst: *mut T, val: T) {
- atomic! {
- T, a,
- {
- a = &*(dst as *const _ as *const _);
- a.store(mem::transmute_copy(&val), Ordering::Release);
- mem::forget(val);
- },
- {
- let _guard = lock(dst as usize).write();
- ptr::write(dst, val);
- }
- }
-}
-
-/// Atomically swaps data at `dst` with `val`.
-///
-/// This operation uses the `AcqRel` ordering. If possible, an atomic instructions is used, and a
-/// global lock otherwise.
-unsafe fn atomic_swap<T>(dst: *mut T, val: T) -> T {
- atomic! {
- T, a,
- {
- a = &*(dst as *const _ as *const _);
- let res = mem::transmute_copy(&a.swap(mem::transmute_copy(&val), Ordering::AcqRel));
- mem::forget(val);
- res
- },
- {
- let _guard = lock(dst as usize).write();
- ptr::replace(dst, val)
- }
- }
-}
-
-/// Atomically compares data at `dst` to `current` and, if equal byte-for-byte, exchanges data at
-/// `dst` with `new`.
-///
-/// Returns the old value on success, or the current value at `dst` on failure.
-///
-/// This operation uses the `AcqRel` ordering. If possible, an atomic instructions is used, and a
-/// global lock otherwise.
-#[allow(clippy::let_unit_value)]
-unsafe fn atomic_compare_exchange_weak<T>(dst: *mut T, mut current: T, new: T) -> Result<T, T>
-where
- T: Copy + Eq,
-{
- atomic! {
- T, a,
- {
- a = &*(dst as *const _ as *const _);
- let mut current_raw = mem::transmute_copy(¤t);
- let new_raw = mem::transmute_copy(&new);
-
- loop {
- match a.compare_exchange_weak(
- current_raw,
- new_raw,
- Ordering::AcqRel,
- Ordering::Acquire,
- ) {
- Ok(_) => break Ok(current),
- Err(previous_raw) => {
- let previous = mem::transmute_copy(&previous_raw);
-
- if !T::eq(&previous, ¤t) {
- break Err(previous);
- }
-
- // The compare-exchange operation has failed and didn't store `new`. The
- // failure is either spurious, or `previous` was semantically equal to
- // `current` but not byte-equal. Let's retry with `previous` as the new
- // `current`.
- current = previous;
- current_raw = previous_raw;
- }
- }
- }
- },
- {
- let guard = lock(dst as usize).write();
-
- if T::eq(&*dst, ¤t) {
- Ok(ptr::replace(dst, new))
- } else {
- let val = ptr::read(dst);
- // The value hasn't been changed. Drop the guard without incrementing the stamp.
- guard.abort();
- Err(val)
- }
- }
- }
-}
### external/vendor/crossbeam-utils/src/atomic/consume.rs
@@ -1,111 +0,0 @@
-#[cfg(not(crossbeam_no_atomic))]
-use core::sync::atomic::Ordering;
-
-/// Trait which allows reading from primitive atomic types with "consume" ordering.
-pub trait AtomicConsume {
- /// Type returned by `load_consume`.
- type Val;
-
- /// Loads a value from the atomic using a "consume" memory ordering.
- ///
- /// This is similar to the "acquire" ordering, except that an ordering is
- /// only guaranteed with operations that "depend on" the result of the load.
- /// However consume loads are usually much faster than acquire loads on
- /// architectures with a weak memory model since they don't require memory
- /// fence instructions.
- ///
- /// The exact definition of "depend on" is a bit vague, but it works as you
- /// would expect in practice since a lot of software, especially the Linux
- /// kernel, rely on this behavior.
- ///
- /// This is currently only implemented on ARM and AArch64, where a fence
- /// can be avoided. On other architectures this will fall back to a simple
- /// `load(Ordering::Acquire)`.
- fn load_consume(&self) -> Self::Val;
-}
-
-#[cfg(not(crossbeam_no_atomic))]
-// Miri and Loom don't support "consume" ordering and ThreadSanitizer doesn't treat
-// load(Relaxed) + compiler_fence(Acquire) as "consume" load.
-// LLVM generates machine code equivalent to fence(Acquire) in compiler_fence(Acquire)
-// on PowerPC, MIPS, etc. (https://godbolt.org/z/hffvjvW7h), so for now the fence
-// can be actually avoided here only on ARM and AArch64. See also
-// https://github.com/rust-lang/rust/issues/62256.
-#[cfg(all(
- any(target_arch = "arm", target_arch = "aarch64"),
- not(any(miri, crossbeam_loom, crossbeam_sanitize_thread)),
-))]
-macro_rules! impl_consume {
- () => {
- #[inline]
- fn load_consume(&self) -> Self::Val {
- use crate::primitive::sync::atomic::compiler_fence;
- let result = self.load(Ordering::Relaxed);
- compiler_fence(Ordering::Acquire);
- result
- }
- };
-}
-
-#[cfg(not(crossbeam_no_atomic))]
-#[cfg(not(all(
- any(target_arch = "arm", target_arch = "aarch64"),
- not(any(miri, crossbeam_loom, crossbeam_sanitize_thread)),
-)))]
-macro_rules! impl_consume {
- () => {
- #[inline]
- fn load_consume(&self) -> Self::Val {
- self.load(Ordering::Acquire)
- }
- };
-}
-
-macro_rules! impl_atomic {
- ($atomic:ident, $val:ty) => {
- #[cfg(not(crossbeam_no_atomic))]
- impl AtomicConsume for core::sync::atomic::$atomic {
- type Val = $val;
- impl_consume!();
- }
- #[cfg(crossbeam_loom)]
- impl AtomicConsume for loom::sync::atomic::$atomic {
- type Val = $val;
- impl_consume!();
- }
- };
-}
-
-impl_atomic!(AtomicBool, bool);
-impl_atomic!(AtomicUsize, usize);
-impl_atomic!(AtomicIsize, isize);
-impl_atomic!(AtomicU8, u8);
-impl_atomic!(AtomicI8, i8);
-impl_atomic!(AtomicU16, u16);
-impl_atomic!(AtomicI16, i16);
-#[cfg(any(target_has_atomic = "32", not(target_pointer_width = "16")))]
-impl_atomic!(AtomicU32, u32);
-#[cfg(any(target_has_atomic = "32", not(target_pointer_width = "16")))]
-impl_atomic!(AtomicI32, i32);
-#[cfg(any(
- target_has_atomic = "64",
- not(any(target_pointer_width = "16", target_pointer_width = "32")),
-))]
-impl_atomic!(AtomicU64, u64);
-#[cfg(any(
- target_has_atomic = "64",
- not(any(target_pointer_width = "16", target_pointer_width = "32")),
-))]
-impl_atomic!(AtomicI64, i64);
-
-#[cfg(not(crossbeam_no_atomic))]
-impl<T> AtomicConsume for core::sync::atomic::AtomicPtr<T> {
- type Val = *mut T;
- impl_consume!();
-}
-
-#[cfg(crossbeam_loom)]
-impl<T> AtomicConsume for loom::sync::atomic::AtomicPtr<T> {
- type Val = *mut T;
- impl_consume!();
-}
### external/vendor/crossbeam-utils/src/atomic/mod.rs
@@ -1,32 +0,0 @@
-//! Atomic types.
-//!
-//! * [`AtomicCell`], a thread-safe mutable memory location.
-//! * [`AtomicConsume`], for reading from primitive atomic types with "consume" ordering.
-
-#[cfg(target_has_atomic = "ptr")]
-#[cfg(not(crossbeam_loom))]
-// Use "wide" sequence lock if the pointer width <= 32 for preventing its counter against wrap
-// around.
-//
-// In narrow architectures (pointer width <= 16), the counter is still <= 32-bit and may be
-// vulnerable to wrap around. But it's mostly okay, since in such a primitive hardware, the
-// counter will not be increased that fast.
-// Note that Rust (and C99) pointers must be at least 16-bit (i.e., 8-bit targets are impossible): https://github.com/rust-lang/rust/pull/49305
-#[cfg_attr(
- any(target_pointer_width = "16", target_pointer_width = "32"),
- path = "seq_lock_wide.rs"
-)]
-mod seq_lock;
-
-#[cfg(target_has_atomic = "ptr")]
-// We cannot provide AtomicCell under cfg(crossbeam_loom) because loom's atomic
-// types have a different in-memory representation than the underlying type.
-// TODO: The latest loom supports fences, so fallback using seqlock may be available.
-#[cfg(not(crossbeam_loom))]
-mod atomic_cell;
-#[cfg(target_has_atomic = "ptr")]
-#[cfg(not(crossbeam_loom))]
-pub use atomic_cell::AtomicCell;
-
-mod consume;
-pub use consume::AtomicConsume;
### external/vendor/crossbeam-utils/src/atomic/seq_lock.rs
@@ -1,112 +0,0 @@
-use core::mem;
-use core::sync::atomic::{self, AtomicUsize, Ordering};
-
-use crate::Backoff;
-
-/// A simple stamped lock.
-pub(crate) struct SeqLock {
- /// The current state of the lock.
- ///
- /// All bits except the least significant one hold the current stamp. When locked, the state
- /// equals 1 and doesn't contain a valid stamp.
- state: AtomicUsize,
-}
-
-impl SeqLock {
- pub(crate) const fn new() -> Self {
- Self {
- state: AtomicUsize::new(0),
- }
- }
-
- /// If not locked, returns the current stamp.
- ///
- /// This method should be called before optimistic reads.
- #[inline]
- pub(crate) fn optimistic_read(&self) -> Option<usize> {
- let state = self.state.load(Ordering::Acquire);
- if state == 1 {
- None
- } else {
- Some(state)
- }
- }
-
- /// Returns `true` if the current stamp is equal to `stamp`.
- ///
- /// This method should be called after optimistic reads to check whether they are valid. The
- /// argument `stamp` should correspond to the one returned by method `optimistic_read`.
- #[inline]
- pub(crate) fn validate_read(&self, stamp: usize) -> bool {
- atomic::fence(Ordering::Acquire);
- self.state.load(Ordering::Relaxed) == stamp
- }
-
- /// Grabs the lock for writing.
- #[inline]
- pub(crate) fn write(&'static self) -> SeqLockWriteGuard {
- let backoff = Backoff::new();
- loop {
- let previous = self.state.swap(1, Ordering::Acquire);
-
- if previous != 1 {
- atomic::fence(Ordering::Release);
-
- return SeqLockWriteGuard {
- lock: self,
- state: previous,
- };
- }
-
- backoff.snooze();
- }
- }
-}
-
-/// An RAII guard that releases the lock and increments the stamp when dropped.
-pub(crate) struct SeqLockWriteGuard {
- /// The parent lock.
- lock: &'static SeqLock,
-
- /// The stamp before locking.
- state: usize,
-}
-
-impl SeqLockWriteGuard {
- /// Releases the lock without incrementing the stamp.
- #[inline]
- pub(crate) fn abort(self) {
- self.lock.state.store(self.state, Ordering::Release);
-
- // We specifically don't want to call drop(), since that's
- // what increments the stamp.
- mem::forget(self);
- }
-}
-
-impl Drop for SeqLockWriteGuard {
- #[inline]
- fn drop(&mut self) {
- // Release the lock and increment the stamp.
- self.lock
- .state
- .store(self.state.wrapping_add(2), Ordering::Release);
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::SeqLock;
-
- #[test]
- fn test_abort() {
- static LK: SeqLock = SeqLock::new();
- let before = LK.optimistic_read().unwrap();
- {
- let guard = LK.write();
- guard.abort();
- }
- let after = LK.optimistic_read().unwrap();
- assert_eq!(before, after, "aborted write does not update the stamp");
- }
-}
### external/vendor/crossbeam-utils/src/atomic/seq_lock_wide.rs
@@ -1,155 +0,0 @@
-use core::mem;
-use core::sync::atomic::{self, AtomicUsize, Ordering};
-
-use crate::Backoff;
-
-/// A simple stamped lock.
-///
-/// The state is represented as two `AtomicUsize`: `state_hi` for high bits and `state_lo` for low
-/// bits.
-pub(crate) struct SeqLock {
- /// The high bits of the current state of the lock.
- state_hi: AtomicUsize,
-
- /// The low bits of the current state of the lock.
- ///
- /// All bits except the least significant one hold the current stamp. When locked, the state_lo
- /// equals 1 and doesn't contain a valid stamp.
- state_lo: AtomicUsize,
-}
-
-impl SeqLock {
- pub(crate) const fn new() -> Self {
- Self {
- state_hi: AtomicUsize::new(0),
- state_lo: AtomicUsize::new(0),
- }
- }
-
- /// If not locked, returns the current stamp.
- ///
- /// This method should be called before optimistic reads.
- #[inline]
- pub(crate) fn optimistic_read(&self) -> Option<(usize, usize)> {
- // The acquire loads from `state_hi` and `state_lo` synchronize with the release stores in
- // `SeqLockWriteGuard::drop`.
- //
- // As a consequence, we can make sure that (1) all writes within the era of `state_hi - 1`
- // happens before now; and therefore, (2) if `state_lo` is even, all writes within the
- // critical section of (`state_hi`, `state_lo`) happens before now.
- let state_hi = self.state_hi.load(Ordering::Acquire);
- let state_lo = self.state_lo.load(Ordering::Acquire);
- if state_lo == 1 {
- None
- } else {
- Some((state_hi, state_lo))
- }
- }
-
- /// Returns `true` if the current stamp is equal to `stamp`.
- ///
- /// This method should be called after optimistic reads to check whether they are valid. The
- /// argument `stamp` should correspond to the one returned by method `optimistic_read`.
- #[inline]
- pub(crate) fn validate_read(&self, stamp: (usize, usize)) -> bool {
- // Thanks to the fence, if we're noticing any modification to the data at the critical
- // section of `(a, b)`, then the critical section's write of 1 to state_lo should be
- // visible.
- atomic::fence(Ordering::Acquire);
-
- // So if `state_lo` coincides with `stamp.1`, then either (1) we're noticing no modification
- // to the data after the critical section of `(stamp.0, stamp.1)`, or (2) `state_lo` wrapped
- // around.
- //
- // If (2) is the case, the acquire ordering ensures we see the new value of `state_hi`.
- let state_lo = self.state_lo.load(Ordering::Acquire);
-
- // If (2) is the case and `state_hi` coincides with `stamp.0`, then `state_hi` also wrapped
- // around, which we give up to correctly validate the read.
- let state_hi = self.state_hi.load(Ordering::Relaxed);
-
- // Except for the case that both `state_hi` and `state_lo` wrapped around, the following
- // condition implies that we're noticing no modification to the data after the critical
- // section of `(stamp.0, stamp.1)`.
- (state_hi, state_lo) == stamp
- }
-
- /// Grabs the lock for writing.
- #[inline]
- pub(crate) fn write(&'static self) -> SeqLockWriteGuard {
- let backoff = Backoff::new();
- loop {
- let previous = self.state_lo.swap(1, Ordering::Acquire);
-
- if previous != 1 {
- // To synchronize with the acquire fence in `validate_read` via any modification to
- // the data at the critical section of `(state_hi, previous)`.
- atomic::fence(Ordering::Release);
-
- return SeqLockWriteGuard {
- lock: self,
- state_lo: previous,
- };
- }
-
- backoff.snooze();
- }
- }
-}
-
-/// An RAII guard that releases the lock and increments the stamp when dropped.
-pub(crate) struct SeqLockWriteGuard {
- /// The parent lock.
- lock: &'static SeqLock,
-
- /// The stamp before locking.
- state_lo: usize,
-}
-
-impl SeqLockWriteGuard {
- /// Releases the lock without incrementing the stamp.
- #[inline]
- pub(crate) fn abort(self) {
- self.lock.state_lo.store(self.state_lo, Ordering::Release);
- mem::forget(self);
- }
-}
-
-impl Drop for SeqLockWriteGuard {
- #[inline]
- fn drop(&mut self) {
- let state_lo = self.state_lo.wrapping_add(2);
-
- // Increase the high bits if the low bits wrap around.
- //
- // Release ordering for synchronizing with `optimistic_read`.
- if state_lo == 0 {
- let state_hi = self.lock.state_hi.load(Ordering::Relaxed);
- self.lock
- .state_hi
- .store(state_hi.wrapping_add(1), Ordering::Release);
- }
-
- // Release the lock and increment the stamp.
- //
- // Release ordering for synchronizing with `optimistic_read`.
- self.lock.state_lo.store(state_lo, Ordering::Release);
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::SeqLock;
-
- #[test]
- fn test_abort() {
- static LK: SeqLock = SeqLock::new();
- let before = LK.optimistic_read().unwrap();
- {
- let guard = LK.write();
- guard.abort();
- }
- let after = LK.optimistic_read().unwrap();
- assert_eq!(before, after, "aborted write does not update the stamp");
- }
-}
### external/vendor/crossbeam-utils/src/backoff.rs
@@ -1,287 +0,0 @@
-use crate::primitive::hint;
-use core::cell::Cell;
-use core::fmt;
-
-const SPIN_LIMIT: u32 = 6;
-const YIELD_LIMIT: u32 = 10;
-
-/// Performs exponential backoff in spin loops.
-///
-/// Backing off in spin loops reduces contention and improves overall performance.
-///
-/// This primitive can execute *YIELD* and *PAUSE* instructions, yield the current thread to the OS
-/// scheduler, and tell when is a good time to block the thread using a different synchronization
-/// mechanism. Each step of the back off procedure takes roughly twice as long as the previous
-/// step.
-///
-/// # Examples
-///
-/// Backing off in a lock-free loop:
-///
-/// ```
-/// use crossbeam_utils::Backoff;
-/// use std::sync::atomic::AtomicUsize;
-/// use std::sync::atomic::Ordering::SeqCst;
-///
-/// fn fetch_mul(a: &AtomicUsize, b: usize) -> usize {
-/// let backoff = Backoff::new();
-/// loop {
-/// let val = a.load(SeqCst);
-/// if a.compare_exchange(val, val.wrapping_mul(b), SeqCst, SeqCst).is_ok() {
-/// return val;
-/// }
-/// backoff.spin();
-/// }
-/// }
-/// ```
-///
-/// Waiting for an [`AtomicBool`] to become `true`:
-///
-/// ```
-/// use crossbeam_utils::Backoff;
-/// use std::sync::atomic::AtomicBool;
-/// use std::sync::atomic::Ordering::SeqCst;
-///
-/// fn spin_wait(ready: &AtomicBool) {
-/// let backoff = Backoff::new();
-/// while !ready.load(SeqCst) {
-/// backoff.snooze();
-/// }
-/// }
-/// ```
-///
-/// Waiting for an [`AtomicBool`] to become `true` and parking the thread after a long wait.
-/// Note that whoever sets the atomic variable to `true` must notify the parked thread by calling
-/// [`unpark()`]:
-///
-/// ```
-/// use crossbeam_utils::Backoff;
-/// use std::sync::atomic::AtomicBool;
-/// use std::sync::atomic::Ordering::SeqCst;
-/// use std::thread;
-///
-/// fn blocking_wait(ready: &AtomicBool) {
-/// let backoff = Backoff::new();
-/// while !ready.load(SeqCst) {
-/// if backoff.is_completed() {
-/// thread::park();
-/// } else {
-/// backoff.snooze();
-/// }
-/// }
-/// }
-/// ```
-///
-/// [`is_completed`]: Backoff::is_completed
-/// [`std::thread::park()`]: std::thread::park
-/// [`Condvar`]: std::sync::Condvar
-/// [`AtomicBool`]: std::sync::atomic::AtomicBool
-/// [`unpark()`]: std::thread::Thread::unpark
-pub struct Backoff {
- step: Cell<u32>,
-}
-
-impl Backoff {
- /// Creates a new `Backoff`.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::Backoff;
- ///
- /// let backoff = Backoff::new();
- /// ```
- #[inline]
- pub fn new() -> Self {
- Backoff { step: Cell::new(0) }
- }
-
- /// Resets the `Backoff`.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::Backoff;
- ///
- /// let backoff = Backoff::new();
- /// backoff.reset();
- /// ```
- #[inline]
- pub fn reset(&self) {
- self.step.set(0);
- }
-
- /// Backs off in a lock-free loop.
- ///
- /// This method should be used when we need to retry an operation because another thread made
- /// progress.
- ///
- /// The processor may yield using the *YIELD* or *PAUSE* instruction.
- ///
- /// # Examples
- ///
- /// Backing off in a lock-free loop:
- ///
- /// ```
- /// use crossbeam_utils::Backoff;
- /// use std::sync::atomic::AtomicUsize;
- /// use std::sync::atomic::Ordering::SeqCst;
- ///
- /// fn fetch_mul(a: &AtomicUsize, b: usize) -> usize {
- /// let backoff = Backoff::new();
- /// loop {
- /// let val = a.load(SeqCst);
- /// if a.compare_exchange(val, val.wrapping_mul(b), SeqCst, SeqCst).is_ok() {
- /// return val;
- /// }
- /// backoff.spin();
- /// }
- /// }
- ///
- /// let a = AtomicUsize::new(7);
- /// assert_eq!(fetch_mul(&a, 8), 7);
- /// assert_eq!(a.load(SeqCst), 56);
- /// ```
- #[inline]
- pub fn spin(&self) {
- for _ in 0..1 << self.step.get().min(SPIN_LIMIT) {
- hint::spin_loop();
- }
-
- if self.step.get() <= SPIN_LIMIT {
- self.step.set(self.step.get() + 1);
- }
- }
-
- /// Backs off in a blocking loop.
- ///
- /// This method should be used when we need to wait for another thread to make progress.
- ///
- /// The processor may yield using the *YIELD* or *PAUSE* instruction and the current thread
- /// may yield by giving up a timeslice to the OS scheduler.
- ///
- /// In `#[no_std]` environments, this method is equivalent to [`spin`].
- ///
- /// If possible, use [`is_completed`] to check when it is advised to stop using backoff and
- /// block the current thread using a different synchronization mechanism instead.
- ///
- /// [`spin`]: Backoff::spin
- /// [`is_completed`]: Backoff::is_completed
- ///
- /// # Examples
- ///
- /// Waiting for an [`AtomicBool`] to become `true`:
- ///
- /// ```
- /// use crossbeam_utils::Backoff;
- /// use std::sync::Arc;
- /// use std::sync::atomic::AtomicBool;
- /// use std::sync::atomic::Ordering::SeqCst;
- /// use std::thread;
- /// use std::time::Duration;
- ///
- /// fn spin_wait(ready: &AtomicBool) {
- /// let backoff = Backoff::new();
- /// while !ready.load(SeqCst) {
- /// backoff.snooze();
- /// }
- /// }
- ///
- /// let ready = Arc::new(AtomicBool::new(false));
- /// let ready2 = ready.clone();
- ///
- /// thread::spawn(move || {
- /// thread::sleep(Duration::from_millis(100));
- /// ready2.store(true, SeqCst);
- /// });
- ///
- /// assert_eq!(ready.load(SeqCst), false);
- /// spin_wait(&ready);
- /// assert_eq!(ready.load(SeqCst), true);
- /// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371
- /// ```
- ///
- /// [`AtomicBool`]: std::sync::atomic::AtomicBool
- #[inline]
- pub fn snooze(&self) {
- if self.step.get() <= SPIN_LIMIT {
- for _ in 0..1 << self.step.get() {
- hint::spin_loop();
- }
- } else {
- #[cfg(not(feature = "std"))]
- for _ in 0..1 << self.step.get() {
- hint::spin_loop();
- }
-
- #[cfg(feature = "std")]
- ::std::thread::yield_now();
- }
-
- if self.step.get() <= YIELD_LIMIT {
- self.step.set(self.step.get() + 1);
- }
- }
-
- /// Returns `true` if exponential backoff has completed and blocking the thread is advised.
- ///
- /// # Examples
- ///
- /// Waiting for an [`AtomicBool`] to become `true` and parking the thread after a long wait:
- ///
- /// ```
- /// use crossbeam_utils::Backoff;
- /// use std::sync::Arc;
- /// use std::sync::atomic::AtomicBool;
- /// use std::sync::atomic::Ordering::SeqCst;
- /// use std::thread;
- /// use std::time::Duration;
- ///
- /// fn blocking_wait(ready: &AtomicBool) {
- /// let backoff = Backoff::new();
- /// while !ready.load(SeqCst) {
- /// if backoff.is_completed() {
- /// thread::park();
- /// } else {
- /// backoff.snooze();
- /// }
- /// }
- /// }
- ///
- /// let ready = Arc::new(AtomicBool::new(false));
- /// let ready2 = ready.clone();
- /// let waiter = thread::current();
- ///
- /// thread::spawn(move || {
- /// thread::sleep(Duration::from_millis(100));
- /// ready2.store(true, SeqCst);
- /// waiter.unpark();
- /// });
- ///
- /// assert_eq!(ready.load(SeqCst), false);
- /// blocking_wait(&ready);
- /// assert_eq!(ready.load(SeqCst), true);
- /// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371
- /// ```
- ///
- /// [`AtomicBool`]: std::sync::atomic::AtomicBool
- #[inline]
- pub fn is_completed(&self) -> bool {
- self.step.get() > YIELD_LIMIT
- }
-}
-
-impl fmt::Debug for Backoff {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("Backoff")
- .field("step", &self.step)
- .field("is_completed", &self.is_completed())
- .finish()
- }
-}
-
-impl Default for Backoff {
- fn default() -> Backoff {
- Backoff::new()
- }
-}
### external/vendor/crossbeam-utils/src/cache_padded.rs
@@ -1,217 +0,0 @@
-use core::fmt;
-use core::ops::{Deref, DerefMut};
-
-/// Pads and aligns a value to the length of a cache line.
-///
-/// In concurrent programming, sometimes it is desirable to make sure commonly accessed pieces of
-/// data are not placed into the same cache line. Updating an atomic value invalidates the whole
-/// cache line it belongs to, which makes the next access to the same cache line slower for other
-/// CPU cores. Use `CachePadded` to ensure updating one piece of data doesn't invalidate other
-/// cached data.
-///
-/// # Size and alignment
-///
-/// Cache lines are assumed to be N bytes long, depending on the architecture:
-///
-/// * On x86-64, aarch64, and powerpc64, N = 128.
-/// * On arm, mips, mips64, sparc, and hexagon, N = 32.
-/// * On m68k, N = 16.
-/// * On s390x, N = 256.
-/// * On all others, N = 64.
-///
-/// Note that N is just a reasonable guess and is not guaranteed to match the actual cache line
-/// length of the machine the program is running on. On modern Intel architectures, spatial
-/// prefetcher is pulling pairs of 64-byte cache lines at a time, so we pessimistically assume that
-/// cache lines are 128 bytes long.
-///
-/// The size of `CachePadded<T>` is the smallest multiple of N bytes large enough to accommodate
-/// a value of type `T`.
-///
-/// The alignment of `CachePadded<T>` is the maximum of N bytes and the alignment of `T`.
-///
-/// # Examples
-///
-/// Alignment and padding:
-///
-/// ```
-/// use crossbeam_utils::CachePadded;
-///
-/// let array = [CachePadded::new(1i8), CachePadded::new(2i8)];
-/// let addr1 = &*array[0] as *const i8 as usize;
-/// let addr2 = &*array[1] as *const i8 as usize;
-///
-/// assert!(addr2 - addr1 >= 32);
-/// assert_eq!(addr1 % 32, 0);
-/// assert_eq!(addr2 % 32, 0);
-/// ```
-///
-/// When building a concurrent queue with a head and a tail index, it is wise to place them in
-/// different cache lines so that concurrent threads pushing and popping elements don't invalidate
-/// each other's cache lines:
-///
-/// ```
-/// use crossbeam_utils::CachePadded;
-/// use std::sync::atomic::AtomicUsize;
-///
-/// struct Queue<T> {
-/// head: CachePadded<AtomicUsize>,
-/// tail: CachePadded<AtomicUsize>,
-/// buffer: *mut T,
-/// }
-/// ```
-#[derive(Clone, Copy, Default, Hash, PartialEq, Eq)]
-// Starting from Intel's Sandy Bridge, spatial prefetcher is now pulling pairs of 64-byte cache
-// lines at a time, so we have to align to 128 bytes rather than 64.
-//
-// Sources:
-// - https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf
-// - https://github.com/facebook/folly/blob/1b5288e6eea6df074758f877c849b6e73bbb9fbb/folly/lang/Align.h#L107
-//
-// aarch64/arm64ec's big.LITTLE architecture has asymmetric cores and "big" cores have 128-byte cache line size.
-//
-// Sources:
-// - https://www.mono-project.com/news/2016/09/12/arm64-icache/
-//
-// powerpc64 has 128-byte cache line size.
-//
-// Sources:
-// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_ppc64x.go#L9
-// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/powerpc/include/asm/cache.h#L26
-#[cfg_attr(
- any(
- target_arch = "x86_64",
- target_arch = "aarch64",
- target_arch = "arm64ec",
- target_arch = "powerpc64",
- ),
- repr(align(128))
-)]
-// arm, mips, mips64, sparc, and hexagon have 32-byte cache line size.
-//
-// Sources:
-// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_arm.go#L7
-// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips.go#L7
-// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mipsle.go#L7
-// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips64x.go#L9
-// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/sparc/include/asm/cache.h#L17
-// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/hexagon/include/asm/cache.h#L12
-#[cfg_attr(
- any(
- target_arch = "arm",
- target_arch = "mips",
- target_arch = "mips32r6",
- target_arch = "mips64",
- target_arch = "mips64r6",
- target_arch = "sparc",
- target_arch = "hexagon",
- ),
- repr(align(32))
-)]
-// m68k has 16-byte cache line size.
-//
-// Sources:
-// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/m68k/include/asm/cache.h#L9
-#[cfg_attr(target_arch = "m68k", repr(align(16)))]
-// s390x has 256-byte cache line size.
-//
-// Sources:
-// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_s390x.go#L7
-// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/s390/include/asm/cache.h#L13
-#[cfg_attr(target_arch = "s390x", repr(align(256)))]
-// x86, wasm, riscv, and sparc64 have 64-byte cache line size.
-//
-// Sources:
-// - https://github.com/golang/go/blob/dda2991c2ea0c5914714469c4defc2562a907230/src/internal/cpu/cpu_x86.go#L9
-// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_wasm.go#L7
-// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/riscv/include/asm/cache.h#L10
-// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/sparc/include/asm/cache.h#L19
-//
-// All others are assumed to have 64-byte cache line size.
-#[cfg_attr(
- not(any(
- target_arch = "x86_64",
- target_arch = "aarch64",
- target_arch = "arm64ec",
- target_arch = "powerpc64",
- target_arch = "arm",
- target_arch = "mips",
- target_arch = "mips32r6",
- target_arch = "mips64",
- target_arch = "mips64r6",
- target_arch = "sparc",
- target_arch = "hexagon",
- target_arch = "m68k",
- target_arch = "s390x",
- )),
- repr(align(64))
-)]
-pub struct CachePadded<T> {
- value: T,
-}
-
-unsafe impl<T: Send> Send for CachePadded<T> {}
-unsafe impl<T: Sync> Sync for CachePadded<T> {}
-
-impl<T> CachePadded<T> {
- /// Pads and aligns a value to the length of a cache line.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::CachePadded;
- ///
- /// let padded_value = CachePadded::new(1);
- /// ```
- pub const fn new(t: T) -> CachePadded<T> {
- CachePadded::<T> { value: t }
- }
-
- /// Returns the inner value.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::CachePadded;
- ///
- /// let padded_value = CachePadded::new(7);
- /// let value = padded_value.into_inner();
- /// assert_eq!(value, 7);
- /// ```
- pub fn into_inner(self) -> T {
- self.value
- }
-}
-
-impl<T> Deref for CachePadded<T> {
- type Target = T;
-
- fn deref(&self) -> &T {
- &self.value
- }
-}
-
-impl<T> DerefMut for CachePadded<T> {
- fn deref_mut(&mut self) -> &mut T {
- &mut self.value
- }
-}
-
-impl<T: fmt::Debug> fmt::Debug for CachePadded<T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("CachePadded")
- .field("value", &self.value)
- .finish()
- }
-}
-
-impl<T> From<T> for CachePadded<T> {
- fn from(t: T) -> Self {
- CachePadded::new(t)
- }
-}
-
-impl<T: fmt::Display> fmt::Display for CachePadded<T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- fmt::Display::fmt(&self.value, f)
- }
-}
### external/vendor/crossbeam-utils/src/lib.rs
@@ -1,110 +0,0 @@
-//! Miscellaneous tools for concurrent programming.
-//!
-//! ## Atomics
-//!
-//! * [`AtomicCell`], a thread-safe mutable memory location.
-//! * [`AtomicConsume`], for reading from primitive atomic types with "consume" ordering.
-//!
-//! ## Thread synchronization
-//!
-//! * [`Parker`], a thread parking primitive.
-//! * [`ShardedLock`], a sharded reader-writer lock with fast concurrent reads.
-//! * [`WaitGroup`], for synchronizing the beginning or end of some computation.
-//!
-//! ## Utilities
-//!
-//! * [`Backoff`], for exponential backoff in spin loops.
-//! * [`CachePadded`], for padding and aligning a value to the length of a cache line.
-//! * [`scope`], for spawning threads that borrow local variables from the stack.
-//!
-//! [`AtomicCell`]: atomic::AtomicCell
-//! [`AtomicConsume`]: atomic::AtomicConsume
-//! [`Parker`]: sync::Parker
-//! [`ShardedLock`]: sync::ShardedLock
-//! [`WaitGroup`]: sync::WaitGroup
-//! [`scope`]: thread::scope
-
-#![no_std]
-#![doc(test(
- no_crate_inject,
- attr(
- deny(warnings, rust_2018_idioms),
- allow(dead_code, unused_assignments, unused_variables)
- )
-))]
-#![warn(
- missing_docs,
- missing_debug_implementations,
- rust_2018_idioms,
- unreachable_pub
-)]
-
-#[cfg(feature = "std")]
-extern crate std;
-
-#[cfg(crossbeam_loom)]
-#[allow(unused_imports)]
-mod primitive {
- pub(crate) mod hint {
- pub(crate) use loom::hint::spin_loop;
- }
- pub(crate) mod sync {
- pub(crate) mod atomic {
- pub(crate) use loom::sync::atomic::{
- AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16,
- AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering,
- };
-
- // FIXME: loom does not support compiler_fence at the moment.
- // https://github.com/tokio-rs/loom/issues/117
- // we use fence as a stand-in for compiler_fence for the time being.
- // this may miss some races since fence is stronger than compiler_fence,
- // but it's the best we can do for the time being.
- pub(crate) use loom::sync::atomic::fence as compiler_fence;
- }
- pub(crate) use loom::sync::{Arc, Condvar, Mutex};
- }
-}
-#[cfg(not(crossbeam_loom))]
-#[allow(unused_imports)]
-mod primitive {
- pub(crate) mod hint {
- pub(crate) use core::hint::spin_loop;
- }
- pub(crate) mod sync {
- pub(crate) mod atomic {
- pub(crate) use core::sync::atomic::{compiler_fence, Ordering};
- #[cfg(not(crossbeam_no_atomic))]
- pub(crate) use core::sync::atomic::{
- AtomicBool, AtomicI16, AtomicI8, AtomicIsize, AtomicU16, AtomicU8, AtomicUsize,
- };
- #[cfg(not(crossbeam_no_atomic))]
- #[cfg(any(target_has_atomic = "32", not(target_pointer_width = "16")))]
- pub(crate) use core::sync::atomic::{AtomicI32, AtomicU32};
- #[cfg(not(crossbeam_no_atomic))]
- #[cfg(any(
- target_has_atomic = "64",
- not(any(target_pointer_width = "16", target_pointer_width = "32")),
- ))]
- pub(crate) use core::sync::atomic::{AtomicI64, AtomicU64};
- }
-
- #[cfg(feature = "std")]
- pub(crate) use std::sync::{Arc, Condvar, Mutex};
- }
-}
-
-pub mod atomic;
-
-mod cache_padded;
-pub use crate::cache_padded::CachePadded;
-
-mod backoff;
-pub use crate::backoff::Backoff;
-
-#[cfg(feature = "std")]
-pub mod sync;
-
-#[cfg(feature = "std")]
-#[cfg(not(crossbeam_loom))]
-pub mod thread;
### external/vendor/crossbeam-utils/src/sync/mod.rs
@@ -1,17 +0,0 @@
-//! Thread synchronization primitives.
-//!
-//! * [`Parker`], a thread parking primitive.
-//! * [`ShardedLock`], a sharded reader-writer lock with fast concurrent reads.
-//! * [`WaitGroup`], for synchronizing the beginning or end of some computation.
-
-#[cfg(not(crossbeam_loom))]
-mod once_lock;
-mod parker;
-#[cfg(not(crossbeam_loom))]
-mod sharded_lock;
-mod wait_group;
-
-pub use self::parker::{Parker, Unparker};
-#[cfg(not(crossbeam_loom))]
-pub use self::sharded_lock::{ShardedLock, ShardedLockReadGuard, ShardedLockWriteGuard};
-pub use self::wait_group::WaitGroup;
### external/vendor/crossbeam-utils/src/sync/once_lock.rs
@@ -1,88 +0,0 @@
-// Based on unstable std::sync::OnceLock.
-//
-// Source: https://github.com/rust-lang/rust/blob/8e9c93df464b7ada3fc7a1c8ccddd9dcb24ee0a0/library/std/src/sync/once_lock.rs
-
-use core::cell::UnsafeCell;
-use core::mem::MaybeUninit;
-use std::sync::Once;
-
-pub(crate) struct OnceLock<T> {
- once: Once,
- value: UnsafeCell<MaybeUninit<T>>,
- // Unlike std::sync::OnceLock, we don't need PhantomData here because
- // we don't use #[may_dangle].
-}
-
-unsafe impl<T: Sync + Send> Sync for OnceLock<T> {}
-unsafe impl<T: Send> Send for OnceLock<T> {}
-
-impl<T> OnceLock<T> {
- /// Creates a new empty cell.
- #[must_use]
- pub(crate) const fn new() -> Self {
- Self {
- once: Once::new(),
- value: UnsafeCell::new(MaybeUninit::uninit()),
- }
- }
-
- /// Gets the contents of the cell, initializing it with `f` if the cell
- /// was empty.
- ///
- /// Many threads may call `get_or_init` concurrently with different
- /// initializing functions, but it is guaranteed that only one function
- /// will be executed.
- ///
- /// # Panics
- ///
- /// If `f` panics, the panic is propagated to the caller, and the cell
- /// remains uninitialized.
- ///
- /// It is an error to reentrantly initialize the cell from `f`. The
- /// exact outcome is unspecified. Current implementation deadlocks, but
- /// this may be changed to a panic in the future.
- pub(crate) fn get_or_init<F>(&self, f: F) -> &T
- where
- F: FnOnce() -> T,
- {
- // Fast path check
- if self.once.is_completed() {
- // SAFETY: The inner value has been initialized
- return unsafe { self.get_unchecked() };
- }
- self.initialize(f);
-
- // SAFETY: The inner value has been initialized
- unsafe { self.get_unchecked() }
- }
-
- #[cold]
- fn initialize<F>(&self, f: F)
- where
- F: FnOnce() -> T,
- {
- let slot = self.value.get();
-
- self.once.call_once(|| {
- let value = f();
- unsafe { slot.write(MaybeUninit::new(value)) }
- });
- }
-
- /// # Safety
- ///
- /// The value must be initialized
- unsafe fn get_unchecked(&self) -> &T {
- debug_assert!(self.once.is_completed());
- &*self.value.get().cast::<T>()
- }
-}
-
-impl<T> Drop for OnceLock<T> {
- fn drop(&mut self) {
- if self.once.is_completed() {
- // SAFETY: The inner value has been initialized
- unsafe { (*self.value.get()).assume_init_drop() };
- }
- }
-}
### external/vendor/crossbeam-utils/src/sync/parker.rs
@@ -1,415 +0,0 @@
-use crate::primitive::sync::atomic::{AtomicUsize, Ordering::SeqCst};
-use crate::primitive::sync::{Arc, Condvar, Mutex};
-use std::fmt;
-use std::marker::PhantomData;
-use std::time::{Duration, Instant};
-
-/// A thread parking primitive.
-///
-/// Conceptually, each `Parker` has an associated token which is initially not present:
-///
-/// * The [`park`] method blocks the current thread unless or until the token is available, at
-/// which point it automatically consumes the token.
-///
-/// * The [`park_timeout`] and [`park_deadline`] methods work the same as [`park`], but block for
-/// a specified maximum time.
-///
-/// * The [`unpark`] method atomically makes the token available if it wasn't already. Because the
-/// token is initially absent, [`unpark`] followed by [`park`] will result in the second call
-/// returning immediately.
-///
-/// In other words, each `Parker` acts a bit like a spinlock that can be locked and unlocked using
-/// [`park`] and [`unpark`].
-///
-/// # Examples
-///
-/// ```
-/// use std::thread;
-/// use std::time::Duration;
-/// use crossbeam_utils::sync::Parker;
-///
-/// let p = Parker::new();
-/// let u = p.unparker().clone();
-///
-/// // Make the token available.
-/// u.unpark();
-/// // Wakes up immediately and consumes the token.
-/// p.park();
-///
-/// thread::spawn(move || {
-/// thread::sleep(Duration::from_millis(500));
-/// u.unpark();
-/// });
-///
-/// // Wakes up when `u.unpark()` provides the token.
-/// p.park();
-/// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371
-/// ```
-///
-/// [`park`]: Parker::park
-/// [`park_timeout`]: Parker::park_timeout
-/// [`park_deadline`]: Parker::park_deadline
-/// [`unpark`]: Unparker::unpark
-pub struct Parker {
- unparker: Unparker,
- _marker: PhantomData<*const ()>,
-}
-
-unsafe impl Send for Parker {}
-
-impl Default for Parker {
- fn default() -> Self {
- Self {
- unparker: Unparker {
- inner: Arc::new(Inner {
- state: AtomicUsize::new(EMPTY),
- lock: Mutex::new(()),
- cvar: Condvar::new(),
- }),
- },
- _marker: PhantomData,
- }
- }
-}
-
-impl Parker {
- /// Creates a new `Parker`.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::Parker;
- ///
- /// let p = Parker::new();
- /// ```
- ///
- pub fn new() -> Parker {
- Self::default()
- }
-
- /// Blocks the current thread until the token is made available.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::Parker;
- ///
- /// let p = Parker::new();
- /// let u = p.unparker().clone();
- ///
- /// // Make the token available.
- /// u.unpark();
- ///
- /// // Wakes up immediately and consumes the token.
- /// p.park();
- /// ```
- pub fn park(&self) {
- self.unparker.inner.park(None);
- }
-
- /// Blocks the current thread until the token is made available, but only for a limited time.
- ///
- /// # Examples
- ///
- /// ```
- /// use std::time::Duration;
- /// use crossbeam_utils::sync::Parker;
- ///
- /// let p = Parker::new();
- ///
- /// // Waits for the token to become available, but will not wait longer than 500 ms.
- /// p.park_timeout(Duration::from_millis(500));
- /// ```
- pub fn park_timeout(&self, timeout: Duration) {
- match Instant::now().checked_add(timeout) {
- Some(deadline) => self.park_deadline(deadline),
- None => self.park(),
- }
- }
-
- /// Blocks the current thread until the token is made available, or until a certain deadline.
- ///
- /// # Examples
- ///
- /// ```
- /// use std::time::{Duration, Instant};
- /// use crossbeam_utils::sync::Parker;
- ///
- /// let p = Parker::new();
- /// let deadline = Instant::now() + Duration::from_millis(500);
- ///
- /// // Waits for the token to become available, but will not wait longer than 500 ms.
- /// p.park_deadline(deadline);
- /// ```
- pub fn park_deadline(&self, deadline: Instant) {
- self.unparker.inner.park(Some(deadline))
- }
-
- /// Returns a reference to an associated [`Unparker`].
- ///
- /// The returned [`Unparker`] doesn't have to be used by reference - it can also be cloned.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::Parker;
- ///
- /// let p = Parker::new();
- /// let u = p.unparker().clone();
- ///
- /// // Make the token available.
- /// u.unpark();
- /// // Wakes up immediately and consumes the token.
- /// p.park();
- /// ```
- ///
- /// [`park`]: Parker::park
- /// [`park_timeout`]: Parker::park_timeout
- pub fn unparker(&self) -> &Unparker {
- &self.unparker
- }
-
- /// Converts a `Parker` into a raw pointer.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::Parker;
- ///
- /// let p = Parker::new();
- /// let raw = Parker::into_raw(p);
- /// # let _ = unsafe { Parker::from_raw(raw) };
- /// ```
- pub fn into_raw(this: Parker) -> *const () {
- Unparker::into_raw(this.unparker)
- }
-
- /// Converts a raw pointer into a `Parker`.
- ///
- /// # Safety
- ///
- /// This method is safe to use only with pointers returned by [`Parker::into_raw`].
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::Parker;
- ///
- /// let p = Parker::new();
- /// let raw = Parker::into_raw(p);
- /// let p = unsafe { Parker::from_raw(raw) };
- /// ```
- pub unsafe fn from_raw(ptr: *const ()) -> Parker {
- Parker {
- unparker: Unparker::from_raw(ptr),
- _marker: PhantomData,
- }
- }
-}
-
-impl fmt::Debug for Parker {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.pad("Parker { .. }")
- }
-}
-
-/// Unparks a thread parked by the associated [`Parker`].
-pub struct Unparker {
- inner: Arc<Inner>,
-}
-
-unsafe impl Send for Unparker {}
-unsafe impl Sync for Unparker {}
-
-impl Unparker {
- /// Atomically makes the token available if it is not already.
- ///
- /// This method will wake up the thread blocked on [`park`] or [`park_timeout`], if there is
- /// any.
- ///
- /// # Examples
- ///
- /// ```
- /// use std::thread;
- /// use std::time::Duration;
- /// use crossbeam_utils::sync::Parker;
- ///
- /// let p = Parker::new();
- /// let u = p.unparker().clone();
- ///
- /// thread::spawn(move || {
- /// thread::sleep(Duration::from_millis(500));
- /// u.unpark();
- /// });
- ///
- /// // Wakes up when `u.unpark()` provides the token.
- /// p.park();
- /// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371
- /// ```
- ///
- /// [`park`]: Parker::park
- /// [`park_timeout`]: Parker::park_timeout
- pub fn unpark(&self) {
- self.inner.unpark()
- }
-
- /// Converts an `Unparker` into a raw pointer.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::{Parker, Unparker};
- ///
- /// let p = Parker::new();
- /// let u = p.unparker().clone();
- /// let raw = Unparker::into_raw(u);
- /// # let _ = unsafe { Unparker::from_raw(raw) };
- /// ```
- pub fn into_raw(this: Unparker) -> *const () {
- Arc::into_raw(this.inner).cast::<()>()
- }
-
- /// Converts a raw pointer into an `Unparker`.
- ///
- /// # Safety
- ///
- /// This method is safe to use only with pointers returned by [`Unparker::into_raw`].
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::{Parker, Unparker};
- ///
- /// let p = Parker::new();
- /// let u = p.unparker().clone();
- ///
- /// let raw = Unparker::into_raw(u);
- /// let u = unsafe { Unparker::from_raw(raw) };
- /// ```
- pub unsafe fn from_raw(ptr: *const ()) -> Unparker {
- Unparker {
- inner: Arc::from_raw(ptr.cast::<Inner>()),
- }
- }
-}
-
-impl fmt::Debug for Unparker {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.pad("Unparker { .. }")
- }
-}
-
-impl Clone for Unparker {
- fn clone(&self) -> Unparker {
- Unparker {
- inner: self.inner.clone(),
- }
- }
-}
-
-const EMPTY: usize = 0;
-const PARKED: usize = 1;
-const NOTIFIED: usize = 2;
-
-struct Inner {
- state: AtomicUsize,
- lock: Mutex<()>,
- cvar: Condvar,
-}
-
-impl Inner {
- fn park(&self, deadline: Option<Instant>) {
- // If we were previously notified then we consume this notification and return quickly.
- if self
- .state
- .compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst)
- .is_ok()
- {
- return;
- }
-
- // If the timeout is zero, then there is no need to actually block.
- if let Some(deadline) = deadline {
- if deadline <= Instant::now() {
- return;
- }
- }
-
- // Otherwise we need to coordinate going to sleep.
- let mut m = self.lock.lock().unwrap();
-
- match self.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
- Ok(_) => {}
- // Consume this notification to avoid spurious wakeups in the next park.
- Err(NOTIFIED) => {
- // We must read `state` here, even though we know it will be `NOTIFIED`. This is
- // because `unpark` may have been called again since we read `NOTIFIED` in the
- // `compare_exchange` above. We must perform an acquire operation that synchronizes
- // with that `unpark` to observe any writes it made before the call to `unpark`. To
- // do that we must read from the write it made to `state`.
- let old = self.state.swap(EMPTY, SeqCst);
- assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
- return;
- }
- Err(n) => panic!("inconsistent park_timeout state: {}", n),
- }
-
- loop {
- // Block the current thread on the conditional variable.
- m = match deadline {
- None => self.cvar.wait(m).unwrap(),
- Some(deadline) => {
- let now = Instant::now();
- if now < deadline {
- // We could check for a timeout here, in the return value of wait_timeout,
- // but in the case that a timeout and an unpark arrive simultaneously, we
- // prefer to report the former.
- self.cvar.wait_timeout(m, deadline - now).unwrap().0
- } else {
- // We've timed out; swap out the state back to empty on our way out
- match self.state.swap(EMPTY, SeqCst) {
- NOTIFIED | PARKED => return,
- n => panic!("inconsistent park_timeout state: {}", n),
- };
- }
- }
- };
-
- if self
- .state
- .compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst)
- .is_ok()
- {
- // got a notification
- return;
- }
-
- // Spurious wakeup, go back to sleep. Alternatively, if we timed out, it will be caught
- // in the branch above, when we discover the deadline is in the past
- }
- }
-
- pub(crate) fn unpark(&self) {
- // To ensure the unparked thread will observe any writes we made before this call, we must
- // perform a release operation that `park` can synchronize with. To do that we must write
- // `NOTIFIED` even if `state` is already `NOTIFIED`. That is why this must be a swap rather
- // than a compare-and-swap that returns if it reads `NOTIFIED` on failure.
- match self.state.swap(NOTIFIED, SeqCst) {
- EMPTY => return, // no one was waiting
- NOTIFIED => return, // already unparked
- PARKED => {} // gotta go wake someone up
- _ => panic!("inconsistent state in unpark"),
- }
-
- // There is a period between when the parked thread sets `state` to `PARKED` (or last
- // checked `state` in the case of a spurious wakeup) and when it actually waits on `cvar`.
- // If we were to notify during this period it would be ignored and then when the parked
- // thread went to sleep it would never wake up. Fortunately, it has `lock` locked at this
- // stage so we can acquire `lock` to wait until it is ready to receive the notification.
- //
- // Releasing `lock` before the call to `notify_one` means that when the parked thread wakes
- // it doesn't get woken only to have to wait for us to release `lock`.
- drop(self.lock.lock().unwrap());
- self.cvar.notify_one();
- }
-}
### external/vendor/crossbeam-utils/src/sync/sharded_lock.rs
@@ -1,638 +0,0 @@
-use std::boxed::Box;
-use std::cell::UnsafeCell;
-use std::collections::HashMap;
-use std::fmt;
-use std::marker::PhantomData;
-use std::mem;
-use std::ops::{Deref, DerefMut};
-use std::panic::{RefUnwindSafe, UnwindSafe};
-use std::sync::{LockResult, PoisonError, TryLockError, TryLockResult};
-use std::sync::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
-use std::thread::{self, ThreadId};
-use std::vec::Vec;
-
-use crate::sync::once_lock::OnceLock;
-use crate::CachePadded;
-
-/// The number of shards per sharded lock. Must be a power of two.
-const NUM_SHARDS: usize = 8;
-
-/// A shard containing a single reader-writer lock.
-struct Shard {
- /// The inner reader-writer lock.
- lock: RwLock<()>,
-
- /// The write-guard keeping this shard locked.
- ///
- /// Write operations will lock each shard and store the guard here. These guards get dropped at
- /// the same time the big guard is dropped.
- write_guard: UnsafeCell<Option<RwLockWriteGuard<'static, ()>>>,
-}
-
-/// A sharded reader-writer lock.
-///
-/// This lock is equivalent to [`RwLock`], except read operations are faster and write operations
-/// are slower.
-///
-/// A `ShardedLock` is internally made of a list of *shards*, each being a [`RwLock`] occupying a
-/// single cache line. Read operations will pick one of the shards depending on the current thread
-/// and lock it. Write operations need to lock all shards in succession.
-///
-/// By splitting the lock into shards, concurrent read operations will in most cases choose
-/// different shards and thus update different cache lines, which is good for scalability. However,
-/// write operations need to do more work and are therefore slower than usual.
-///
-/// The priority policy of the lock is dependent on the underlying operating system's
-/// implementation, and this type does not guarantee that any particular policy will be used.
-///
-/// # Poisoning
-///
-/// A `ShardedLock`, like [`RwLock`], will become poisoned on a panic. Note that it may only be
-/// poisoned if a panic occurs while a write operation is in progress. If a panic occurs in any
-/// read operation, the lock will not be poisoned.
-///
-/// # Examples
-///
-/// ```
-/// use crossbeam_utils::sync::ShardedLock;
-///
-/// let lock = ShardedLock::new(5);
-///
-/// // Any number of read locks can be held at once.
-/// {
-/// let r1 = lock.read().unwrap();
-/// let r2 = lock.read().unwrap();
-/// assert_eq!(*r1, 5);
-/// assert_eq!(*r2, 5);
-/// } // Read locks are dropped at this point.
-///
-/// // However, only one write lock may be held.
-/// {
-/// let mut w = lock.write().unwrap();
-/// *w += 1;
-/// assert_eq!(*w, 6);
-/// } // Write lock is dropped here.
-/// ```
-///
-/// [`RwLock`]: std::sync::RwLock
-pub struct ShardedLock<T: ?Sized> {
- /// A list of locks protecting the internal data.
- shards: Box<[CachePadded<Shard>]>,
-
- /// The internal data.
- value: UnsafeCell<T>,
-}
-
-unsafe impl<T: ?Sized + Send> Send for ShardedLock<T> {}
-unsafe impl<T: ?Sized + Send + Sync> Sync for ShardedLock<T> {}
-
-impl<T: ?Sized> UnwindSafe for ShardedLock<T> {}
-impl<T: ?Sized> RefUnwindSafe for ShardedLock<T> {}
-
-impl<T> ShardedLock<T> {
- /// Creates a new sharded reader-writer lock.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::ShardedLock;
- ///
- /// let lock = ShardedLock::new(5);
- /// ```
- pub fn new(value: T) -> ShardedLock<T> {
- ShardedLock {
- shards: (0..NUM_SHARDS)
- .map(|_| {
- CachePadded::new(Shard {
- lock: RwLock::new(()),
- write_guard: UnsafeCell::new(None),
- })
- })
- .collect::<Box<[_]>>(),
- value: UnsafeCell::new(value),
- }
- }
-
- /// Consumes this lock, returning the underlying data.
- ///
- /// # Errors
- ///
- /// This method will return an error if the lock is poisoned. A lock gets poisoned when a write
- /// operation panics.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::ShardedLock;
- ///
- /// let lock = ShardedLock::new(String::new());
- /// {
- /// let mut s = lock.write().unwrap();
- /// *s = "modified".to_owned();
- /// }
- /// assert_eq!(lock.into_inner().unwrap(), "modified");
- /// ```
- pub fn into_inner(self) -> LockResult<T> {
- let is_poisoned = self.is_poisoned();
- let inner = self.value.into_inner();
-
- if is_poisoned {
- Err(PoisonError::new(inner))
- } else {
- Ok(inner)
- }
- }
-}
-
-impl<T: ?Sized> ShardedLock<T> {
- /// Returns `true` if the lock is poisoned.
- ///
- /// If another thread can still access the lock, it may become poisoned at any time. A `false`
- /// result should not be trusted without additional synchronization.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::ShardedLock;
- /// use std::sync::Arc;
- /// use std::thread;
- ///
- /// let lock = Arc::new(ShardedLock::new(0));
- /// let c_lock = lock.clone();
- ///
- /// let _ = thread::spawn(move || {
- /// let _lock = c_lock.write().unwrap();
- /// panic!(); // the lock gets poisoned
- /// }).join();
- /// assert_eq!(lock.is_poisoned(), true);
- /// ```
- pub fn is_poisoned(&self) -> bool {
- self.shards[0].lock.is_poisoned()
- }
-
- /// Returns a mutable reference to the underlying data.
- ///
- /// Since this call borrows the lock mutably, no actual locking needs to take place.
- ///
- /// # Errors
- ///
- /// This method will return an error if the lock is poisoned. A lock gets poisoned when a write
- /// operation panics.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::ShardedLock;
- ///
- /// let mut lock = ShardedLock::new(0);
- /// *lock.get_mut().unwrap() = 10;
- /// assert_eq!(*lock.read().unwrap(), 10);
- /// ```
- pub fn get_mut(&mut self) -> LockResult<&mut T> {
- let is_poisoned = self.is_poisoned();
- let inner = unsafe { &mut *self.value.get() };
-
- if is_poisoned {
- Err(PoisonError::new(inner))
- } else {
- Ok(inner)
- }
- }
-
- /// Attempts to acquire this lock with shared read access.
- ///
- /// If the access could not be granted at this time, an error is returned. Otherwise, a guard
- /// is returned which will release the shared access when it is dropped. This method does not
- /// provide any guarantees with respect to the ordering of whether contentious readers or
- /// writers will acquire the lock first.
- ///
- /// # Errors
- ///
- /// This method will return an error if the lock is poisoned. A lock gets poisoned when a write
- /// operation panics.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::ShardedLock;
- ///
- /// let lock = ShardedLock::new(1);
- ///
- /// match lock.try_read() {
- /// Ok(n) => assert_eq!(*n, 1),
- /// Err(_) => unreachable!(),
- /// };
- /// ```
- pub fn try_read(&self) -> TryLockResult<ShardedLockReadGuard<'_, T>> {
- // Take the current thread index and map it to a shard index. Thread indices will tend to
- // distribute shards among threads equally, thus reducing contention due to read-locking.
- let current_index = current_index().unwrap_or(0);
- let shard_index = current_index & (self.shards.len() - 1);
-
- match self.shards[shard_index].lock.try_read() {
- Ok(guard) => Ok(ShardedLockReadGuard {
- lock: self,
- _guard: guard,
- _marker: PhantomData,
- }),
- Err(TryLockError::Poisoned(err)) => {
- let guard = ShardedLockReadGuard {
- lock: self,
- _guard: err.into_inner(),
- _marker: PhantomData,
- };
- Err(TryLockError::Poisoned(PoisonError::new(guard)))
- }
- Err(TryLockError::WouldBlock) => Err(TryLockError::WouldBlock),
- }
- }
-
- /// Locks with shared read access, blocking the current thread until it can be acquired.
- ///
- /// The calling thread will be blocked until there are no more writers which hold the lock.
- /// There may be other readers currently inside the lock when this method returns. This method
- /// does not provide any guarantees with respect to the ordering of whether contentious readers
- /// or writers will acquire the lock first.
- ///
- /// Returns a guard which will release the shared access when dropped.
- ///
- /// # Errors
- ///
- /// This method will return an error if the lock is poisoned. A lock gets poisoned when a write
- /// operation panics.
- ///
- /// # Panics
- ///
- /// This method might panic when called if the lock is already held by the current thread.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::ShardedLock;
- /// use std::sync::Arc;
- /// use std::thread;
- ///
- /// let lock = Arc::new(ShardedLock::new(1));
- /// let c_lock = lock.clone();
- ///
- /// let n = lock.read().unwrap();
- /// assert_eq!(*n, 1);
- ///
- /// thread::spawn(move || {
- /// let r = c_lock.read();
- /// assert!(r.is_ok());
- /// }).join().unwrap();
- /// ```
- pub fn read(&self) -> LockResult<ShardedLockReadGuard<'_, T>> {
- // Take the current thread index and map it to a shard index. Thread indices will tend to
- // distribute shards among threads equally, thus reducing contention due to read-locking.
- let current_index = current_index().unwrap_or(0);
- let shard_index = current_index & (self.shards.len() - 1);
-
- match self.shards[shard_index].lock.read() {
- Ok(guard) => Ok(ShardedLockReadGuard {
- lock: self,
- _guard: guard,
- _marker: PhantomData,
- }),
- Err(err) => Err(PoisonError::new(ShardedLockReadGuard {
- lock: self,
- _guard: err.into_inner(),
- _marker: PhantomData,
- })),
- }
- }
-
- /// Attempts to acquire this lock with exclusive write access.
- ///
- /// If the access could not be granted at this time, an error is returned. Otherwise, a guard
- /// is returned which will release the exclusive access when it is dropped. This method does
- /// not provide any guarantees with respect to the ordering of whether contentious readers or
- /// writers will acquire the lock first.
- ///
- /// # Errors
- ///
- /// This method will return an error if the lock is poisoned. A lock gets poisoned when a write
- /// operation panics.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::ShardedLock;
- ///
- /// let lock = ShardedLock::new(1);
- ///
- /// let n = lock.read().unwrap();
- /// assert_eq!(*n, 1);
- ///
- /// assert!(lock.try_write().is_err());
- /// ```
- pub fn try_write(&self) -> TryLockResult<ShardedLockWriteGuard<'_, T>> {
- let mut poisoned = false;
- let mut blocked = None;
-
- // Write-lock each shard in succession.
- for (i, shard) in self.shards.iter().enumerate() {
- let guard = match shard.lock.try_write() {
- Ok(guard) => guard,
- Err(TryLockError::Poisoned(err)) => {
- poisoned = true;
- err.into_inner()
- }
- Err(TryLockError::WouldBlock) => {
- blocked = Some(i);
- break;
- }
- };
-
- // Store the guard into the shard.
- unsafe {
- let guard: RwLockWriteGuard<'static, ()> = mem::transmute(guard);
- let dest: *mut _ = shard.write_guard.get();
- *dest = Some(guard);
- }
- }
-
- if let Some(i) = blocked {
- // Unlock the shards in reverse order of locking.
- for shard in self.shards[0..i].iter().rev() {
- unsafe {
- let dest: *mut _ = shard.write_guard.get();
- let guard = (*dest).take();
- drop(guard);
- }
- }
- Err(TryLockError::WouldBlock)
- } else if poisoned {
- let guard = ShardedLockWriteGuard {
- lock: self,
- _marker: PhantomData,
- };
- Err(TryLockError::Poisoned(PoisonError::new(guard)))
- } else {
- Ok(ShardedLockWriteGuard {
- lock: self,
- _marker: PhantomData,
- })
- }
- }
-
- /// Locks with exclusive write access, blocking the current thread until it can be acquired.
- ///
- /// The calling thread will be blocked until there are no more writers which hold the lock.
- /// There may be other readers currently inside the lock when this method returns. This method
- /// does not provide any guarantees with respect to the ordering of whether contentious readers
- /// or writers will acquire the lock first.
- ///
- /// Returns a guard which will release the exclusive access when dropped.
- ///
- /// # Errors
- ///
- /// This method will return an error if the lock is poisoned. A lock gets poisoned when a write
- /// operation panics.
- ///
- /// # Panics
- ///
- /// This method might panic when called if the lock is already held by the current thread.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::ShardedLock;
- ///
- /// let lock = ShardedLock::new(1);
- ///
- /// let mut n = lock.write().unwrap();
- /// *n = 2;
- ///
- /// assert!(lock.try_read().is_err());
- /// ```
- pub fn write(&self) -> LockResult<ShardedLockWriteGuard<'_, T>> {
- let mut poisoned = false;
-
- // Write-lock each shard in succession.
- for shard in self.shards.iter() {
- let guard = match shard.lock.write() {
- Ok(guard) => guard,
- Err(err) => {
- poisoned = true;
- err.into_inner()
- }
- };
-
- // Store the guard into the shard.
- unsafe {
- let guard: RwLockWriteGuard<'_, ()> = guard;
- let guard: RwLockWriteGuard<'static, ()> = mem::transmute(guard);
- let dest: *mut _ = shard.write_guard.get();
- *dest = Some(guard);
- }
- }
-
- if poisoned {
- Err(PoisonError::new(ShardedLockWriteGuard {
- lock: self,
- _marker: PhantomData,
- }))
- } else {
- Ok(ShardedLockWriteGuard {
- lock: self,
- _marker: PhantomData,
- })
- }
- }
-}
-
-impl<T: ?Sized + fmt::Debug> fmt::Debug for ShardedLock<T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self.try_read() {
- Ok(guard) => f
- .debug_struct("ShardedLock")
- .field("data", &&*guard)
- .finish(),
- Err(TryLockError::Poisoned(err)) => f
- .debug_struct("ShardedLock")
- .field("data", &&**err.get_ref())
- .finish(),
- Err(TryLockError::WouldBlock) => {
- struct LockedPlaceholder;
- impl fmt::Debug for LockedPlaceholder {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.write_str("<locked>")
- }
- }
- f.debug_struct("ShardedLock")
- .field("data", &LockedPlaceholder)
- .finish()
- }
- }
- }
-}
-
-impl<T: Default> Default for ShardedLock<T> {
- fn default() -> ShardedLock<T> {
- ShardedLock::new(Default::default())
- }
-}
-
-impl<T> From<T> for ShardedLock<T> {
- fn from(t: T) -> Self {
- ShardedLock::new(t)
- }
-}
-
-/// A guard used to release the shared read access of a [`ShardedLock`] when dropped.
-#[clippy::has_significant_drop]
-pub struct ShardedLockReadGuard<'a, T: ?Sized> {
- lock: &'a ShardedLock<T>,
- _guard: RwLockReadGuard<'a, ()>,
- _marker: PhantomData<RwLockReadGuard<'a, T>>,
-}
-
-unsafe impl<T: ?Sized + Sync> Sync for ShardedLockReadGuard<'_, T> {}
-
-impl<T: ?Sized> Deref for ShardedLockReadGuard<'_, T> {
- type Target = T;
-
- fn deref(&self) -> &T {
- unsafe { &*self.lock.value.get() }
- }
-}
-
-impl<T: fmt::Debug> fmt::Debug for ShardedLockReadGuard<'_, T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("ShardedLockReadGuard")
- .field("lock", &self.lock)
- .finish()
- }
-}
-
-impl<T: ?Sized + fmt::Display> fmt::Display for ShardedLockReadGuard<'_, T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- (**self).fmt(f)
- }
-}
-
-/// A guard used to release the exclusive write access of a [`ShardedLock`] when dropped.
-#[clippy::has_significant_drop]
-pub struct ShardedLockWriteGuard<'a, T: ?Sized> {
- lock: &'a ShardedLock<T>,
- _marker: PhantomData<RwLockWriteGuard<'a, T>>,
-}
-
-unsafe impl<T: ?Sized + Sync> Sync for ShardedLockWriteGuard<'_, T> {}
-
-impl<T: ?Sized> Drop for ShardedLockWriteGuard<'_, T> {
- fn drop(&mut self) {
- // Unlock the shards in reverse order of locking.
- for shard in self.lock.shards.iter().rev() {
- unsafe {
- let dest: *mut _ = shard.write_guard.get();
- let guard = (*dest).take();
- drop(guard);
- }
- }
- }
-}
-
-impl<T: fmt::Debug> fmt::Debug for ShardedLockWriteGuard<'_, T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("ShardedLockWriteGuard")
- .field("lock", &self.lock)
- .finish()
- }
-}
-
-impl<T: ?Sized + fmt::Display> fmt::Display for ShardedLockWriteGuard<'_, T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- (**self).fmt(f)
- }
-}
-
-impl<T: ?Sized> Deref for ShardedLockWriteGuard<'_, T> {
- type Target = T;
-
- fn deref(&self) -> &T {
- unsafe { &*self.lock.value.get() }
- }
-}
-
-impl<T: ?Sized> DerefMut for ShardedLockWriteGuard<'_, T> {
- fn deref_mut(&mut self) -> &mut T {
- unsafe { &mut *self.lock.value.get() }
- }
-}
-
-/// Returns a `usize` that identifies the current thread.
-///
-/// Each thread is associated with an 'index'. While there are no particular guarantees, indices
-/// usually tend to be consecutive numbers between 0 and the number of running threads.
-///
-/// Since this function accesses TLS, `None` might be returned if the current thread's TLS is
-/// tearing down.
-#[inline]
-fn current_index() -> Option<usize> {
- REGISTRATION.try_with(|reg| reg.index).ok()
-}
-
-/// The global registry keeping track of registered threads and indices.
-struct ThreadIndices {
- /// Mapping from `ThreadId` to thread index.
- mapping: HashMap<ThreadId, usize>,
-
- /// A list of free indices.
- free_list: Vec<usize>,
-
- /// The next index to allocate if the free list is empty.
- next_index: usize,
-}
-
-fn thread_indices() -> &'static Mutex<ThreadIndices> {
- static THREAD_INDICES: OnceLock<Mutex<ThreadIndices>> = OnceLock::new();
- fn init() -> Mutex<ThreadIndices> {
- Mutex::new(ThreadIndices {
- mapping: HashMap::new(),
- free_list: Vec::new(),
- next_index: 0,
- })
- }
- THREAD_INDICES.get_or_init(init)
-}
-
-/// A registration of a thread with an index.
-///
-/// When dropped, unregisters the thread and frees the reserved index.
-struct Registration {
- index: usize,
- thread_id: ThreadId,
-}
-
-impl Drop for Registration {
- fn drop(&mut self) {
- let mut indices = thread_indices().lock().unwrap();
- indices.mapping.remove(&self.thread_id);
- indices.free_list.push(self.index);
- }
-}
-
-std::thread_local! {
- static REGISTRATION: Registration = {
- let thread_id = thread::current().id();
- let mut indices = thread_indices().lock().unwrap();
-
- let index = match indices.free_list.pop() {
- Some(i) => i,
- None => {
- let i = indices.next_index;
- indices.next_index += 1;
- i
- }
- };
- indices.mapping.insert(thread_id, index);
-
- Registration {
- index,
- thread_id,
- }
- };
-}
### external/vendor/crossbeam-utils/src/sync/wait_group.rs
@@ -1,145 +0,0 @@
-use crate::primitive::sync::{Arc, Condvar, Mutex};
-use std::fmt;
-
-/// Enables threads to synchronize the beginning or end of some computation.
-///
-/// # Wait groups vs barriers
-///
-/// `WaitGroup` is very similar to [`Barrier`], but there are a few differences:
-///
-/// * [`Barrier`] needs to know the number of threads at construction, while `WaitGroup` is cloned to
-/// register more threads.
-///
-/// * A [`Barrier`] can be reused even after all threads have synchronized, while a `WaitGroup`
-/// synchronizes threads only once.
-///
-/// * All threads wait for others to reach the [`Barrier`]. With `WaitGroup`, each thread can choose
-/// to either wait for other threads or to continue without blocking.
-///
-/// # Examples
-///
-/// ```
-/// use crossbeam_utils::sync::WaitGroup;
-/// use std::thread;
-///
-/// // Create a new wait group.
-/// let wg = WaitGroup::new();
-///
-/// for _ in 0..4 {
-/// // Create another reference to the wait group.
-/// let wg = wg.clone();
-///
-/// thread::spawn(move || {
-/// // Do some work.
-///
-/// // Drop the reference to the wait group.
-/// drop(wg);
-/// });
-/// }
-///
-/// // Block until all threads have finished their work.
-/// wg.wait();
-/// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371
-/// ```
-///
-/// [`Barrier`]: std::sync::Barrier
-pub struct WaitGroup {
- inner: Arc<Inner>,
-}
-
-/// Inner state of a `WaitGroup`.
-struct Inner {
- cvar: Condvar,
- count: Mutex<usize>,
-}
-
-impl Default for WaitGroup {
- fn default() -> Self {
- Self {
- inner: Arc::new(Inner {
- cvar: Condvar::new(),
- count: Mutex::new(1),
- }),
- }
- }
-}
-
-impl WaitGroup {
- /// Creates a new wait group and returns the single reference to it.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::WaitGroup;
- ///
- /// let wg = WaitGroup::new();
- /// ```
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Drops this reference and waits until all other references are dropped.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::sync::WaitGroup;
- /// use std::thread;
- ///
- /// let wg = WaitGroup::new();
- ///
- /// thread::spawn({
- /// let wg = wg.clone();
- /// move || {
- /// // Block until both threads have reached `wait()`.
- /// wg.wait();
- /// }
- /// });
- ///
- /// // Block until both threads have reached `wait()`.
- /// wg.wait();
- /// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371
- /// ```
- pub fn wait(self) {
- if *self.inner.count.lock().unwrap() == 1 {
- return;
- }
-
- let inner = self.inner.clone();
- drop(self);
-
- let mut count = inner.count.lock().unwrap();
- while *count > 0 {
- count = inner.cvar.wait(count).unwrap();
- }
- }
-}
-
-impl Drop for WaitGroup {
- fn drop(&mut self) {
- let mut count = self.inner.count.lock().unwrap();
- *count -= 1;
-
- if *count == 0 {
- self.inner.cvar.notify_all();
- }
- }
-}
-
-impl Clone for WaitGroup {
- fn clone(&self) -> WaitGroup {
- let mut count = self.inner.count.lock().unwrap();
- *count += 1;
-
- WaitGroup {
- inner: self.inner.clone(),
- }
- }
-}
-
-impl fmt::Debug for WaitGroup {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- let count: &usize = &*self.inner.count.lock().unwrap();
- f.debug_struct("WaitGroup").field("count", count).finish()
- }
-}
### external/vendor/crossbeam-utils/src/thread.rs
@@ -1,611 +0,0 @@
-//! Threads that can borrow variables from the stack.
-//!
-//! Create a scope when spawned threads need to access variables on the stack:
-//!
-//! ```
-//! use crossbeam_utils::thread;
-//!
-//! let people = vec![
-//! "Alice".to_string(),
-//! "Bob".to_string(),
-//! "Carol".to_string(),
-//! ];
-//!
-//! thread::scope(|s| {
-//! for person in &people {
-//! s.spawn(move |_| {
-//! println!("Hello, {}!", person);
-//! });
-//! }
-//! }).unwrap();
-//! ```
-//!
-//! # Why scoped threads?
-//!
-//! Suppose we wanted to re-write the previous example using plain threads:
-//!
-//! ```compile_fail,E0597
-//! use std::thread;
-//!
-//! let people = vec![
-//! "Alice".to_string(),
-//! "Bob".to_string(),
-//! "Carol".to_string(),
-//! ];
-//!
-//! let mut threads = Vec::new();
-//!
-//! for person in &people {
-//! threads.push(thread::spawn(move || {
-//! println!("Hello, {}!", person);
-//! }));
-//! }
-//!
-//! for thread in threads {
-//! thread.join().unwrap();
-//! }
-//! ```
-//!
-//! This doesn't work because the borrow checker complains about `people` not living long enough:
-//!
-//! ```text
-//! error[E0597]: `people` does not live long enough
-//! --> src/main.rs:12:20
-//! |
-//! 12 | for person in &people {
-//! | ^^^^^^ borrowed value does not live long enough
-//! ...
-//! 21 | }
-//! | - borrowed value only lives until here
-//! |
-//! = note: borrowed value must be valid for the static lifetime...
-//! ```
-//!
-//! The problem here is that spawned threads are not allowed to borrow variables on stack because
-//! the compiler cannot prove they will be joined before `people` is destroyed.
-//!
-//! Scoped threads are a mechanism to guarantee to the compiler that spawned threads will be joined
-//! before the scope ends.
-//!
-//! # How scoped threads work
-//!
-//! If a variable is borrowed by a thread, the thread must complete before the variable is
-//! destroyed. Threads spawned using [`std::thread::spawn`] can only borrow variables with the
-//! `'static` lifetime because the borrow checker cannot be sure when the thread will complete.
-//!
-//! A scope creates a clear boundary between variables outside the scope and threads inside the
-//! scope. Whenever a scope spawns a thread, it promises to join the thread before the scope ends.
-//! This way we guarantee to the borrow checker that scoped threads only live within the scope and
-//! can safely access variables outside it.
-//!
-//! # Nesting scoped threads
-//!
-//! Sometimes scoped threads need to spawn more threads within the same scope. This is a little
-//! tricky because argument `s` lives *inside* the invocation of `thread::scope()` and as such
-//! cannot be borrowed by scoped threads:
-//!
-//! ```compile_fail,E0521
-//! use crossbeam_utils::thread;
-//!
-//! thread::scope(|s| {
-//! s.spawn(|_| {
-//! // Not going to compile because we're trying to borrow `s`,
-//! // which lives *inside* the scope! :(
-//! s.spawn(|_| println!("nested thread"));
-//! });
-//! });
-//! ```
-//!
-//! Fortunately, there is a solution. Every scoped thread is passed a reference to its scope as an
-//! argument, which can be used for spawning nested threads:
-//!
-//! ```
-//! use crossbeam_utils::thread;
-//!
-//! thread::scope(|s| {
-//! // Note the `|s|` here.
-//! s.spawn(|s| {
-//! // Yay, this works because we're using a fresh argument `s`! :)
-//! s.spawn(|_| println!("nested thread"));
-//! });
-//! }).unwrap();
-//! ```
-
-use std::boxed::Box;
-use std::fmt;
-use std::io;
-use std::marker::PhantomData;
-use std::mem;
-use std::panic;
-use std::string::String;
-use std::sync::{Arc, Mutex};
-use std::thread;
-use std::vec::Vec;
-
-use crate::sync::WaitGroup;
-
-type SharedVec<T> = Arc<Mutex<Vec<T>>>;
-type SharedOption<T> = Arc<Mutex<Option<T>>>;
-
-/// Creates a new scope for spawning threads.
-///
-/// All child threads that haven't been manually joined will be automatically joined just before
-/// this function invocation ends. If all joined threads have successfully completed, `Ok` is
-/// returned with the return value of `f`. If any of the joined threads has panicked, an `Err` is
-/// returned containing errors from panicked threads. Note that if panics are implemented by
-/// aborting the process, no error is returned; see the notes of [std::panic::catch_unwind].
-///
-/// **Note:** Since Rust 1.63, this function is soft-deprecated in favor of the more efficient [`std::thread::scope`].
-///
-/// # Examples
-///
-/// ```
-/// use crossbeam_utils::thread;
-///
-/// let var = vec![1, 2, 3];
-///
-/// thread::scope(|s| {
-/// s.spawn(|_| {
-/// println!("A child thread borrowing `var`: {:?}", var);
-/// });
-/// }).unwrap();
-/// ```
-pub fn scope<'env, F, R>(f: F) -> thread::Result<R>
-where
- F: FnOnce(&Scope<'env>) -> R,
-{
- struct AbortOnPanic;
- impl Drop for AbortOnPanic {
- fn drop(&mut self) {
- if thread::panicking() {
- std::process::abort();
- }
- }
- }
-
- let wg = WaitGroup::new();
- let scope = Scope::<'env> {
- handles: SharedVec::default(),
- wait_group: wg.clone(),
- _marker: PhantomData,
- };
-
- // Execute the scoped function, but catch any panics.
- let result = panic::catch_unwind(panic::AssertUnwindSafe(|| f(&scope)));
-
- // If an unwinding panic occurs before all threads are joined
- // promote it to an aborting panic to prevent any threads from escaping the scope.
- let guard = AbortOnPanic;
-
- // Wait until all nested scopes are dropped.
- drop(scope.wait_group);
- wg.wait();
-
- // Join all remaining spawned threads.
- let panics: Vec<_> = scope
- .handles
- .lock()
- .unwrap()
- // Filter handles that haven't been joined, join them, and collect errors.
- .drain(..)
- .filter_map(|handle| handle.lock().unwrap().take())
- .filter_map(|handle| handle.join().err())
- .collect();
-
- mem::forget(guard);
-
- // If `f` has panicked, resume unwinding.
- // If any of the child threads have panicked, return the panic errors.
- // Otherwise, everything is OK and return the result of `f`.
- match result {
- Err(err) => panic::resume_unwind(err),
- Ok(res) => {
- if panics.is_empty() {
- Ok(res)
- } else {
- Err(Box::new(panics))
- }
- }
- }
-}
-
-/// A scope for spawning threads.
-pub struct Scope<'env> {
- /// The list of the thread join handles.
- handles: SharedVec<SharedOption<thread::JoinHandle<()>>>,
-
- /// Used to wait until all subscopes all dropped.
- wait_group: WaitGroup,
-
- /// Borrows data with invariant lifetime `'env`.
- _marker: PhantomData<&'env mut &'env ()>,
-}
-
-unsafe impl Sync for Scope<'_> {}
-
-impl<'env> Scope<'env> {
- /// Spawns a scoped thread.
- ///
- /// This method is similar to the [`spawn`] function in Rust's standard library. The difference
- /// is that this thread is scoped, meaning it's guaranteed to terminate before the scope exits,
- /// allowing it to reference variables outside the scope.
- ///
- /// The scoped thread is passed a reference to this scope as an argument, which can be used for
- /// spawning nested threads.
- ///
- /// The returned [handle](ScopedJoinHandle) can be used to manually
- /// [join](ScopedJoinHandle::join) the thread before the scope exits.
- ///
- /// This will create a thread using default parameters of [`ScopedThreadBuilder`], if you want to specify the
- /// stack size or the name of the thread, use this API instead.
- ///
- /// [`spawn`]: std::thread::spawn
- ///
- /// # Panics
- ///
- /// Panics if the OS fails to create a thread; use [`ScopedThreadBuilder::spawn`]
- /// to recover from such errors.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::thread;
- ///
- /// thread::scope(|s| {
- /// let handle = s.spawn(|_| {
- /// println!("A child thread is running");
- /// 42
- /// });
- ///
- /// // Join the thread and retrieve its result.
- /// let res = handle.join().unwrap();
- /// assert_eq!(res, 42);
- /// }).unwrap();
- /// ```
- pub fn spawn<'scope, F, T>(&'scope self, f: F) -> ScopedJoinHandle<'scope, T>
- where
- F: FnOnce(&Scope<'env>) -> T,
- F: Send + 'env,
- T: Send + 'env,
- {
- self.builder()
- .spawn(f)
- .expect("failed to spawn scoped thread")
- }
-
- /// Creates a builder that can configure a thread before spawning.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::thread;
- ///
- /// thread::scope(|s| {
- /// s.builder()
- /// .spawn(|_| println!("A child thread is running"))
- /// .unwrap();
- /// }).unwrap();
- /// ```
- pub fn builder<'scope>(&'scope self) -> ScopedThreadBuilder<'scope, 'env> {
- ScopedThreadBuilder {
- scope: self,
- builder: thread::Builder::new(),
- }
- }
-}
-
-impl fmt::Debug for Scope<'_> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.pad("Scope { .. }")
- }
-}
-
-/// Configures the properties of a new thread.
-///
-/// The two configurable properties are:
-///
-/// - [`name`]: Specifies an [associated name for the thread][naming-threads].
-/// - [`stack_size`]: Specifies the [desired stack size for the thread][stack-size].
-///
-/// The [`spawn`] method will take ownership of the builder and return an [`io::Result`] of the
-/// thread handle with the given configuration.
-///
-/// The [`Scope::spawn`] method uses a builder with default configuration and unwraps its return
-/// value. You may want to use this builder when you want to recover from a failure to launch a
-/// thread.
-///
-/// # Examples
-///
-/// ```
-/// use crossbeam_utils::thread;
-///
-/// thread::scope(|s| {
-/// s.builder()
-/// .spawn(|_| println!("Running a child thread"))
-/// .unwrap();
-/// }).unwrap();
-/// ```
-///
-/// [`name`]: ScopedThreadBuilder::name
-/// [`stack_size`]: ScopedThreadBuilder::stack_size
-/// [`spawn`]: ScopedThreadBuilder::spawn
-/// [`io::Result`]: std::io::Result
-/// [naming-threads]: std::thread#naming-threads
-/// [stack-size]: std::thread#stack-size
-#[derive(Debug)]
-pub struct ScopedThreadBuilder<'scope, 'env> {
- scope: &'scope Scope<'env>,
- builder: thread::Builder,
-}
-
-impl<'scope, 'env> ScopedThreadBuilder<'scope, 'env> {
- /// Sets the name for the new thread.
- ///
- /// The name must not contain null bytes (`\0`).
- ///
- /// For more information about named threads, see [here][naming-threads].
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::thread;
- /// use std::thread::current;
- ///
- /// thread::scope(|s| {
- /// s.builder()
- /// .name("my thread".to_string())
- /// .spawn(|_| assert_eq!(current().name(), Some("my thread")))
- /// .unwrap();
- /// }).unwrap();
- /// ```
- ///
- /// [naming-threads]: std::thread#naming-threads
- pub fn name(mut self, name: String) -> ScopedThreadBuilder<'scope, 'env> {
- self.builder = self.builder.name(name);
- self
- }
-
- /// Sets the size of the stack for the new thread.
- ///
- /// The stack size is measured in bytes.
- ///
- /// For more information about the stack size for threads, see [here][stack-size].
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::thread;
- ///
- /// thread::scope(|s| {
- /// s.builder()
- /// .stack_size(32 * 1024)
- /// .spawn(|_| println!("Running a child thread"))
- /// .unwrap();
- /// }).unwrap();
- /// ```
- ///
- /// [stack-size]: std::thread#stack-size
- pub fn stack_size(mut self, size: usize) -> ScopedThreadBuilder<'scope, 'env> {
- self.builder = self.builder.stack_size(size);
- self
- }
-
- /// Spawns a scoped thread with this configuration.
- ///
- /// The scoped thread is passed a reference to this scope as an argument, which can be used for
- /// spawning nested threads.
- ///
- /// The returned handle can be used to manually join the thread before the scope exits.
- ///
- /// # Errors
- ///
- /// Unlike the [`Scope::spawn`] method, this method yields an
- /// [`io::Result`] to capture any failure to create the thread at
- /// the OS level.
- ///
- /// [`io::Result`]: std::io::Result
- ///
- /// # Panics
- ///
- /// Panics if a thread name was set and it contained null bytes.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::thread;
- ///
- /// thread::scope(|s| {
- /// let handle = s.builder()
- /// .spawn(|_| {
- /// println!("A child thread is running");
- /// 42
- /// })
- /// .unwrap();
- ///
- /// // Join the thread and retrieve its result.
- /// let res = handle.join().unwrap();
- /// assert_eq!(res, 42);
- /// }).unwrap();
- /// ```
- pub fn spawn<F, T>(self, f: F) -> io::Result<ScopedJoinHandle<'scope, T>>
- where
- F: FnOnce(&Scope<'env>) -> T,
- F: Send + 'env,
- T: Send + 'env,
- {
- // The result of `f` will be stored here.
- let result = SharedOption::default();
-
- // Spawn the thread and grab its join handle and thread handle.
- let (handle, thread) = {
- let result = Arc::clone(&result);
-
- // A clone of the scope that will be moved into the new thread.
- let scope = Scope::<'env> {
- handles: Arc::clone(&self.scope.handles),
- wait_group: self.scope.wait_group.clone(),
- _marker: PhantomData,
- };
-
- // Spawn the thread.
- let handle = {
- let closure = move || {
- // Make sure the scope is inside the closure with the proper `'env` lifetime.
- let scope: Scope<'env> = scope;
-
- // Run the closure.
- let res = f(&scope);
-
- // Store the result if the closure didn't panic.
- *result.lock().unwrap() = Some(res);
- };
-
- // Allocate `closure` on the heap and erase the `'env` bound.
- let closure: Box<dyn FnOnce() + Send + 'env> = Box::new(closure);
- let closure: Box<dyn FnOnce() + Send + 'static> =
- unsafe { mem::transmute(closure) };
-
- // Finally, spawn the closure.
- self.builder.spawn(closure)?
- };
-
- let thread = handle.thread().clone();
- let handle = Arc::new(Mutex::new(Some(handle)));
- (handle, thread)
- };
-
- // Add the handle to the shared list of join handles.
- self.scope.handles.lock().unwrap().push(Arc::clone(&handle));
-
- Ok(ScopedJoinHandle {
- handle,
- result,
- thread,
- _marker: PhantomData,
- })
- }
-}
-
-unsafe impl<T> Send for ScopedJoinHandle<'_, T> {}
-unsafe impl<T> Sync for ScopedJoinHandle<'_, T> {}
-
-/// A handle that can be used to join its scoped thread.
-///
-/// This struct is created by the [`Scope::spawn`] method and the
-/// [`ScopedThreadBuilder::spawn`] method.
-pub struct ScopedJoinHandle<'scope, T> {
- /// A join handle to the spawned thread.
- handle: SharedOption<thread::JoinHandle<()>>,
-
- /// Holds the result of the inner closure.
- result: SharedOption<T>,
-
- /// A handle to the spawned thread.
- thread: thread::Thread,
-
- /// Borrows the parent scope with lifetime `'scope`.
- _marker: PhantomData<&'scope ()>,
-}
-
-impl<T> ScopedJoinHandle<'_, T> {
- /// Waits for the thread to finish and returns its result.
- ///
- /// If the child thread panics, an error is returned. Note that if panics are implemented by
- /// aborting the process, no error is returned; see the notes of [std::panic::catch_unwind].
- ///
- /// # Panics
- ///
- /// This function may panic on some platforms if a thread attempts to join itself or otherwise
- /// may create a deadlock with joining threads.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::thread;
- ///
- /// thread::scope(|s| {
- /// let handle1 = s.spawn(|_| println!("I'm a happy thread :)"));
- /// let handle2 = s.spawn(|_| panic!("I'm a sad thread :("));
- ///
- /// // Join the first thread and verify that it succeeded.
- /// let res = handle1.join();
- /// assert!(res.is_ok());
- ///
- /// // Join the second thread and verify that it panicked.
- /// let res = handle2.join();
- /// assert!(res.is_err());
- /// }).unwrap();
- /// ```
- pub fn join(self) -> thread::Result<T> {
- // Take out the handle. The handle will surely be available because the root scope waits
- // for nested scopes before joining remaining threads.
- let handle = self.handle.lock().unwrap().take().unwrap();
-
- // Join the thread and then take the result out of its inner closure.
- handle
- .join()
- .map(|()| self.result.lock().unwrap().take().unwrap())
- }
-
- /// Returns a handle to the underlying thread.
- ///
- /// # Examples
- ///
- /// ```
- /// use crossbeam_utils::thread;
- ///
- /// thread::scope(|s| {
- /// let handle = s.spawn(|_| println!("A child thread is running"));
- /// println!("The child thread ID: {:?}", handle.thread().id());
- /// }).unwrap();
- /// ```
- pub fn thread(&self) -> &thread::Thread {
- &self.thread
- }
-}
-
-/// Unix-specific extensions.
-#[cfg(unix)]
-mod unix {
- use super::ScopedJoinHandle;
- use std::os::unix::thread::{JoinHandleExt, RawPthread};
-
- impl<T> JoinHandleExt for ScopedJoinHandle<'_, T> {
- fn as_pthread_t(&self) -> RawPthread {
- // Borrow the handle. The handle will surely be available because the root scope waits
- // for nested scopes before joining remaining threads.
- let handle = self.handle.lock().unwrap();
- handle.as_ref().unwrap().as_pthread_t()
- }
- fn into_pthread_t(self) -> RawPthread {
- self.as_pthread_t()
- }
- }
-}
-/// Windows-specific extensions.
-#[cfg(windows)]
-mod windows {
- use super::ScopedJoinHandle;
- use std::os::windows::io::{AsRawHandle, IntoRawHandle, RawHandle};
-
- impl<T> AsRawHandle for ScopedJoinHandle<'_, T> {
- fn as_raw_handle(&self) -> RawHandle {
- // Borrow the handle. The handle will surely be available because the root scope waits
- // for nested scopes before joining remaining threads.
- let handle = self.handle.lock().unwrap();
- handle.as_ref().unwrap().as_raw_handle()
- }
- }
-
- impl<T> IntoRawHandle for ScopedJoinHandle<'_, T> {
- fn into_raw_handle(self) -> RawHandle {
- self.as_raw_handle()
- }
- }
-}
-
-impl<T> fmt::Debug for ScopedJoinHandle<'_, T> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.pad("ScopedJoinHandle { .. }")
- }
-}
### external/vendor/crossbeam-utils/tests/atomic_cell.rs
@@ -1,374 +0,0 @@
-use std::mem;
-use std::sync::atomic::AtomicUsize;
-use std::sync::atomic::Ordering::SeqCst;
-
-use crossbeam_utils::atomic::AtomicCell;
-
-#[test]
-fn is_lock_free() {
- struct UsizeWrap(#[allow(dead_code)] usize);
- struct U8Wrap(#[allow(dead_code)] bool);
- struct I16Wrap(#[allow(dead_code)] i16);
- #[repr(align(8))]
- struct U64Align8(#[allow(dead_code)] u64);
-
- assert!(AtomicCell::<usize>::is_lock_free());
- assert!(AtomicCell::<isize>::is_lock_free());
- assert!(AtomicCell::<UsizeWrap>::is_lock_free());
-
- assert!(AtomicCell::<()>::is_lock_free());
-
- assert!(AtomicCell::<u8>::is_lock_free());
- assert!(AtomicCell::<i8>::is_lock_free());
- assert!(AtomicCell::<bool>::is_lock_free());
- assert!(AtomicCell::<U8Wrap>::is_lock_free());
-
- assert!(AtomicCell::<u16>::is_lock_free());
- assert!(AtomicCell::<i16>::is_lock_free());
- assert!(AtomicCell::<I16Wrap>::is_lock_free());
-
- assert!(AtomicCell::<u32>::is_lock_free());
- assert!(AtomicCell::<i32>::is_lock_free());
-
- // Sizes of both types must be equal, and the alignment of `u64` must be greater or equal than
- // that of `AtomicU64`. In i686-unknown-linux-gnu, the alignment of `u64` is `4` and alignment
- // of `AtomicU64` is `8`, so `AtomicCell<u64>` is not lock-free.
- assert_eq!(
- AtomicCell::<u64>::is_lock_free(),
- cfg!(target_has_atomic = "64") && std::mem::align_of::<u64>() == 8
- );
- assert_eq!(mem::size_of::<U64Align8>(), 8);
- assert_eq!(mem::align_of::<U64Align8>(), 8);
- assert_eq!(
- AtomicCell::<U64Align8>::is_lock_free(),
- cfg!(target_has_atomic = "64")
- );
-
- // AtomicU128 is unstable
- assert!(!AtomicCell::<u128>::is_lock_free());
-}
-
-#[test]
-fn const_is_lock_free() {
- const _U: bool = AtomicCell::<usize>::is_lock_free();
- const _I: bool = AtomicCell::<isize>::is_lock_free();
-}
-
-#[test]
-fn drops_unit() {
- static CNT: AtomicUsize = AtomicUsize::new(0);
- CNT.store(0, SeqCst);
-
- #[derive(Debug, PartialEq, Eq)]
- struct Foo();
-
- impl Foo {
- fn new() -> Foo {
- CNT.fetch_add(1, SeqCst);
- Foo()
- }
- }
-
- impl Drop for Foo {
- fn drop(&mut self) {
- CNT.fetch_sub(1, SeqCst);
- }
- }
-
- impl Default for Foo {
- fn default() -> Foo {
- Foo::new()
- }
- }
-
- let a = AtomicCell::new(Foo::new());
-
- assert_eq!(a.swap(Foo::new()), Foo::new());
- assert_eq!(CNT.load(SeqCst), 1);
-
- a.store(Foo::new());
- assert_eq!(CNT.load(SeqCst), 1);
-
- assert_eq!(a.swap(Foo::default()), Foo::new());
- assert_eq!(CNT.load(SeqCst), 1);
-
- drop(a);
- assert_eq!(CNT.load(SeqCst), 0);
-}
-
-#[test]
-fn drops_u8() {
- static CNT: AtomicUsize = AtomicUsize::new(0);
- CNT.store(0, SeqCst);
-
- #[derive(Debug, PartialEq, Eq)]
- struct Foo(u8);
-
- impl Foo {
- fn new(val: u8) -> Foo {
- CNT.fetch_add(1, SeqCst);
- Foo(val)
- }
- }
-
- impl Drop for Foo {
- fn drop(&mut self) {
- CNT.fetch_sub(1, SeqCst);
- }
- }
-
- impl Default for Foo {
- fn default() -> Foo {
- Foo::new(0)
- }
- }
-
- let a = AtomicCell::new(Foo::new(5));
-
- assert_eq!(a.swap(Foo::new(6)), Foo::new(5));
- assert_eq!(a.swap(Foo::new(1)), Foo::new(6));
- assert_eq!(CNT.load(SeqCst), 1);
-
- a.store(Foo::new(2));
- assert_eq!(CNT.load(SeqCst), 1);
-
- assert_eq!(a.swap(Foo::default()), Foo::new(2));
- assert_eq!(CNT.load(SeqCst), 1);
-
- assert_eq!(a.swap(Foo::default()), Foo::new(0));
- assert_eq!(CNT.load(SeqCst), 1);
-
- drop(a);
- assert_eq!(CNT.load(SeqCst), 0);
-}
-
-#[test]
-fn drops_usize() {
- static CNT: AtomicUsize = AtomicUsize::new(0);
- CNT.store(0, SeqCst);
-
- #[derive(Debug, PartialEq, Eq)]
- struct Foo(usize);
-
- impl Foo {
- fn new(val: usize) -> Foo {
- CNT.fetch_add(1, SeqCst);
- Foo(val)
- }
- }
-
- impl Drop for Foo {
- fn drop(&mut self) {
- CNT.fetch_sub(1, SeqCst);
- }
- }
-
- impl Default for Foo {
- fn default() -> Foo {
- Foo::new(0)
- }
- }
-
- let a = AtomicCell::new(Foo::new(5));
-
- assert_eq!(a.swap(Foo::new(6)), Foo::new(5));
- assert_eq!(a.swap(Foo::new(1)), Foo::new(6));
- assert_eq!(CNT.load(SeqCst), 1);
-
- a.store(Foo::new(2));
- assert_eq!(CNT.load(SeqCst), 1);
-
- assert_eq!(a.swap(Foo::default()), Foo::new(2));
- assert_eq!(CNT.load(SeqCst), 1);
-
- assert_eq!(a.swap(Foo::default()), Foo::new(0));
- assert_eq!(CNT.load(SeqCst), 1);
-
- drop(a);
- assert_eq!(CNT.load(SeqCst), 0);
-}
-
-#[test]
-fn modular_u8() {
- #[derive(Clone, Copy, Eq, Debug, Default)]
- struct Foo(u8);
-
- impl PartialEq for Foo {
- fn eq(&self, other: &Foo) -> bool {
- self.0 % 5 == other.0 % 5
- }
- }
-
- let a = AtomicCell::new(Foo(1));
-
- assert_eq!(a.load(), Foo(1));
- assert_eq!(a.swap(Foo(2)), Foo(11));
- assert_eq!(a.load(), Foo(52));
-
- a.store(Foo(0));
- assert_eq!(a.compare_exchange(Foo(0), Foo(5)), Ok(Foo(100)));
- assert_eq!(a.load().0, 5);
- assert_eq!(a.compare_exchange(Foo(10), Foo(15)), Ok(Foo(100)));
- assert_eq!(a.load().0, 15);
-}
-
-#[test]
-fn modular_usize() {
- #[derive(Clone, Copy, Eq, Debug, Default)]
- struct Foo(usize);
-
- impl PartialEq for Foo {
- fn eq(&self, other: &Foo) -> bool {
- self.0 % 5 == other.0 % 5
- }
- }
-
- let a = AtomicCell::new(Foo(1));
-
- assert_eq!(a.load(), Foo(1));
- assert_eq!(a.swap(Foo(2)), Foo(11));
- assert_eq!(a.load(), Foo(52));
-
- a.store(Foo(0));
- assert_eq!(a.compare_exchange(Foo(0), Foo(5)), Ok(Foo(100)));
- assert_eq!(a.load().0, 5);
- assert_eq!(a.compare_exchange(Foo(10), Foo(15)), Ok(Foo(100)));
- assert_eq!(a.load().0, 15);
-}
-
-#[test]
-fn garbage_padding() {
- #[derive(Copy, Clone, Eq, PartialEq)]
- struct Object {
- a: i64,
- b: i32,
- }
-
- let cell = AtomicCell::new(Object { a: 0, b: 0 });
- let _garbage = [0xfe, 0xfe, 0xfe, 0xfe, 0xfe]; // Needed
- let next = Object { a: 0, b: 0 };
-
- let prev = cell.load();
- assert!(cell.compare_exchange(prev, next).is_ok());
- println!();
-}
-
-#[test]
-fn const_atomic_cell_new() {
- static CELL: AtomicCell<usize> = AtomicCell::new(0);
-
- CELL.store(1);
- assert_eq!(CELL.load(), 1);
-}
-
-// https://github.com/crossbeam-rs/crossbeam/pull/767
-macro_rules! test_arithmetic {
- ($test_name:ident, $ty:ident) => {
- #[test]
- fn $test_name() {
- let a: AtomicCell<$ty> = AtomicCell::new(7);
-
- assert_eq!(a.fetch_add(3), 7);
- assert_eq!(a.load(), 10);
-
- assert_eq!(a.fetch_sub(3), 10);
- assert_eq!(a.load(), 7);
-
- assert_eq!(a.fetch_and(3), 7);
- assert_eq!(a.load(), 3);
-
- assert_eq!(a.fetch_or(16), 3);
- assert_eq!(a.load(), 19);
-
- assert_eq!(a.fetch_xor(2), 19);
- assert_eq!(a.load(), 17);
-
- assert_eq!(a.fetch_max(18), 17);
- assert_eq!(a.load(), 18);
-
- assert_eq!(a.fetch_min(17), 18);
- assert_eq!(a.load(), 17);
-
- assert_eq!(a.fetch_nand(7), 17);
- assert_eq!(a.load(), !(17 & 7));
- }
- };
-}
-test_arithmetic!(arithmetic_u8, u8);
-test_arithmetic!(arithmetic_i8, i8);
-test_arithmetic!(arithmetic_u16, u16);
-test_arithmetic!(arithmetic_i16, i16);
-test_arithmetic!(arithmetic_u32, u32);
-test_arithmetic!(arithmetic_i32, i32);
-test_arithmetic!(arithmetic_u64, u64);
-test_arithmetic!(arithmetic_i64, i64);
-test_arithmetic!(arithmetic_u128, u128);
-test_arithmetic!(arithmetic_i128, i128);
-
-// https://github.com/crossbeam-rs/crossbeam/issues/748
-#[cfg_attr(miri, ignore)] // TODO
-#[test]
-fn issue_748() {
- #[allow(dead_code)]
- #[repr(align(8))]
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- enum Test {
- Field(u32),
- FieldLess,
- }
-
- assert_eq!(mem::size_of::<Test>(), 8);
- assert_eq!(
- AtomicCell::<Test>::is_lock_free(),
- cfg!(target_has_atomic = "64")
- );
- let x = AtomicCell::new(Test::FieldLess);
- assert_eq!(x.load(), Test::FieldLess);
-}
-
-// https://github.com/crossbeam-rs/crossbeam/issues/833
-#[test]
-fn issue_833() {
- use std::num::NonZeroU128;
- use std::sync::atomic::{AtomicBool, Ordering};
- use std::thread;
-
- #[cfg(miri)]
- const N: usize = 10_000;
- #[cfg(not(miri))]
- const N: usize = 1_000_000;
-
- #[allow(dead_code)]
- enum Enum {
- NeverConstructed,
- Cell(AtomicCell<NonZeroU128>),
- }
-
- static STATIC: Enum = Enum::Cell(AtomicCell::new(match NonZeroU128::new(1) {
- Some(nonzero) => nonzero,
- None => unreachable!(),
- }));
- static FINISHED: AtomicBool = AtomicBool::new(false);
-
- let handle = thread::spawn(|| {
- let cell = match &STATIC {
- Enum::NeverConstructed => unreachable!(),
- Enum::Cell(cell) => cell,
- };
- let x = NonZeroU128::new(0xFFFF_FFFF_FFFF_FFFF_0000_0000_0000_0000).unwrap();
- let y = NonZeroU128::new(0x0000_0000_0000_0000_FFFF_FFFF_FFFF_FFFF).unwrap();
- while !FINISHED.load(Ordering::Relaxed) {
- cell.store(x);
- cell.store(y);
- }
- });
-
- for _ in 0..N {
- if let Enum::NeverConstructed = STATIC {
- unreachable!(":(");
- }
- }
-
- FINISHED.store(true, Ordering::Relaxed);
- handle.join().unwrap();
-}
### external/vendor/crossbeam-utils/tests/cache_padded.rs
@@ -1,113 +0,0 @@
-use std::cell::Cell;
-use std::mem;
-
-use crossbeam_utils::CachePadded;
-
-#[test]
-fn default() {
- let x: CachePadded<u64> = Default::default();
- assert_eq!(*x, 0);
-}
-
-#[test]
-fn store_u64() {
- let x: CachePadded<u64> = CachePadded::new(17);
- assert_eq!(*x, 17);
-}
-
-#[test]
-fn store_pair() {
- let x: CachePadded<(u64, u64)> = CachePadded::new((17, 37));
- assert_eq!(x.0, 17);
- assert_eq!(x.1, 37);
-}
-
-#[test]
-fn distance() {
- let arr = [CachePadded::new(17u8), CachePadded::new(37u8)];
- let a = &*arr[0] as *const u8;
- let b = &*arr[1] as *const u8;
- let align = mem::align_of::<CachePadded<()>>();
- assert!(align >= 32);
- assert_eq!(unsafe { a.add(align) }, b);
-}
-
-#[test]
-fn different_sizes() {
- CachePadded::new(17u8);
- CachePadded::new(17u16);
- CachePadded::new(17u32);
- CachePadded::new([17u64; 0]);
- CachePadded::new([17u64; 1]);
- CachePadded::new([17u64; 2]);
- CachePadded::new([17u64; 3]);
- CachePadded::new([17u64; 4]);
- CachePadded::new([17u64; 5]);
- CachePadded::new([17u64; 6]);
- CachePadded::new([17u64; 7]);
- CachePadded::new([17u64; 8]);
-}
-
-#[test]
-fn large() {
- let a = [17u64; 9];
- let b = CachePadded::new(a);
- assert!(mem::size_of_val(&a) <= mem::size_of_val(&b));
-}
-
-#[test]
-fn debug() {
- assert_eq!(
- format!("{:?}", CachePadded::new(17u64)),
- "CachePadded { value: 17 }"
- );
-}
-
-#[test]
-fn drops() {
- let count = Cell::new(0);
-
- struct Foo<'a>(&'a Cell<usize>);
-
- impl<'a> Drop for Foo<'a> {
- fn drop(&mut self) {
- self.0.set(self.0.get() + 1);
- }
- }
-
- let a = CachePadded::new(Foo(&count));
- let b = CachePadded::new(Foo(&count));
-
- assert_eq!(count.get(), 0);
- drop(a);
- assert_eq!(count.get(), 1);
- drop(b);
- assert_eq!(count.get(), 2);
-}
-
-#[allow(clippy::clone_on_copy)] // This is intentional.
-#[test]
-fn clone() {
- let a = CachePadded::new(17);
- let b = a.clone();
- assert_eq!(*a, *b);
-}
-
-#[test]
-fn runs_custom_clone() {
- let count = Cell::new(0);
-
- struct Foo<'a>(&'a Cell<usize>);
-
- impl<'a> Clone for Foo<'a> {
- fn clone(&self) -> Foo<'a> {
- self.0.set(self.0.get() + 1);
- Foo::<'a>(self.0)
- }
- }
-
- let a = CachePadded::new(Foo(&count));
- let _ = a.clone();
-
- assert_eq!(count.get(), 1);
-}
### external/vendor/crossbeam-utils/tests/parker.rs
@@ -1,41 +0,0 @@
-use std::thread::sleep;
-use std::time::Duration;
-use std::u32;
-
-use crossbeam_utils::sync::Parker;
-use crossbeam_utils::thread;
-
-#[test]
-fn park_timeout_unpark_before() {
- let p = Parker::new();
- for _ in 0..10 {
- p.unparker().unpark();
- p.park_timeout(Duration::from_millis(u32::MAX as u64));
- }
-}
-
-#[test]
-fn park_timeout_unpark_not_called() {
- let p = Parker::new();
- for _ in 0..10 {
- p.park_timeout(Duration::from_millis(10))
- }
-}
-
-#[test]
-fn park_timeout_unpark_called_other_thread() {
- for _ in 0..10 {
- let p = Parker::new();
- let u = p.unparker().clone();
-
- thread::scope(|scope| {
- scope.spawn(move |_| {
- sleep(Duration::from_millis(50));
- u.unpark();
- });
-
- p.park_timeout(Duration::from_millis(u32::MAX as u64))
- })
- .unwrap();
- }
-}
### external/vendor/crossbeam-utils/tests/sharded_lock.rs
@@ -1,252 +0,0 @@
-use std::sync::atomic::{AtomicUsize, Ordering};
-use std::sync::mpsc::channel;
-use std::sync::{Arc, TryLockError};
-use std::thread;
-
-use crossbeam_utils::sync::ShardedLock;
-use rand::Rng;
-
-#[derive(Eq, PartialEq, Debug)]
-struct NonCopy(i32);
-
-#[test]
-fn smoke() {
- let l = ShardedLock::new(());
- drop(l.read().unwrap());
- drop(l.write().unwrap());
- drop((l.read().unwrap(), l.read().unwrap()));
- drop(l.write().unwrap());
-}
-
-#[test]
-fn frob() {
- const N: u32 = 10;
- #[cfg(miri)]
- const M: usize = 50;
- #[cfg(not(miri))]
- const M: usize = 1000;
-
- let r = Arc::new(ShardedLock::new(()));
-
- let (tx, rx) = channel::<()>();
- for _ in 0..N {
- let tx = tx.clone();
- let r = r.clone();
- thread::spawn(move || {
- let mut rng = rand::thread_rng();
- for _ in 0..M {
- if rng.gen_bool(1.0 / (N as f64)) {
- drop(r.write().unwrap());
- } else {
- drop(r.read().unwrap());
- }
- }
- drop(tx);
- });
- }
- drop(tx);
- let _ = rx.recv();
-}
-
-#[test]
-fn arc_poison_wr() {
- let arc = Arc::new(ShardedLock::new(1));
- let arc2 = arc.clone();
- let _: Result<(), _> = thread::spawn(move || {
- let _lock = arc2.write().unwrap();
- panic!();
- })
- .join();
- assert!(arc.read().is_err());
-}
-
-#[test]
-fn arc_poison_ww() {
- let arc = Arc::new(ShardedLock::new(1));
- assert!(!arc.is_poisoned());
- let arc2 = arc.clone();
- let _: Result<(), _> = thread::spawn(move || {
- let _lock = arc2.write().unwrap();
- panic!();
- })
- .join();
- assert!(arc.write().is_err());
- assert!(arc.is_poisoned());
-}
-
-#[test]
-fn arc_no_poison_rr() {
- let arc = Arc::new(ShardedLock::new(1));
- let arc2 = arc.clone();
- let _: Result<(), _> = thread::spawn(move || {
- let _lock = arc2.read().unwrap();
- panic!();
- })
- .join();
- let lock = arc.read().unwrap();
- assert_eq!(*lock, 1);
-}
-#[test]
-fn arc_no_poison_sl() {
- let arc = Arc::new(ShardedLock::new(1));
- let arc2 = arc.clone();
- let _: Result<(), _> = thread::spawn(move || {
- let _lock = arc2.read().unwrap();
- panic!()
- })
- .join();
- let lock = arc.write().unwrap();
- assert_eq!(*lock, 1);
-}
-
-#[test]
-fn arc() {
- let arc = Arc::new(ShardedLock::new(0));
- let arc2 = arc.clone();
- let (tx, rx) = channel();
-
- thread::spawn(move || {
- let mut lock = arc2.write().unwrap();
- for _ in 0..10 {
- let tmp = *lock;
- *lock = -1;
- thread::yield_now();
- *lock = tmp + 1;
- }
- tx.send(()).unwrap();
- });
-
- // Readers try to catch the writer in the act
- let mut children = Vec::new();
- for _ in 0..5 {
- let arc3 = arc.clone();
- children.push(thread::spawn(move || {
- let lock = arc3.read().unwrap();
- assert!(*lock >= 0);
- }));
- }
-
- // Wait for children to pass their asserts
- for r in children {
- assert!(r.join().is_ok());
- }
-
- // Wait for writer to finish
- rx.recv().unwrap();
- let lock = arc.read().unwrap();
- assert_eq!(*lock, 10);
-}
-
-#[test]
-fn arc_access_in_unwind() {
- let arc = Arc::new(ShardedLock::new(1));
- let arc2 = arc.clone();
- let _ = thread::spawn(move || {
- struct Unwinder {
- i: Arc<ShardedLock<isize>>,
- }
- impl Drop for Unwinder {
- fn drop(&mut self) {
- let mut lock = self.i.write().unwrap();
- *lock += 1;
- }
- }
- let _u = Unwinder { i: arc2 };
- panic!();
- })
- .join();
- let lock = arc.read().unwrap();
- assert_eq!(*lock, 2);
-}
-
-#[test]
-fn unsized_type() {
- let sl: &ShardedLock<[i32]> = &ShardedLock::new([1, 2, 3]);
- {
- let b = &mut *sl.write().unwrap();
- b[0] = 4;
- b[2] = 5;
- }
- let comp: &[i32] = &[4, 2, 5];
- assert_eq!(&*sl.read().unwrap(), comp);
-}
-
-#[test]
-fn try_write() {
- let lock = ShardedLock::new(0isize);
- let read_guard = lock.read().unwrap();
-
- let write_result = lock.try_write();
- match write_result {
- Err(TryLockError::WouldBlock) => (),
- Ok(_) => panic!("try_write should not succeed while read_guard is in scope"),
- Err(_) => panic!("unexpected error"),
- }
-
- drop(read_guard);
-}
-
-#[test]
-fn test_into_inner() {
- let m = ShardedLock::new(NonCopy(10));
- assert_eq!(m.into_inner().unwrap(), NonCopy(10));
-}
-
-#[test]
-fn test_into_inner_drop() {
- struct Foo(Arc<AtomicUsize>);
- impl Drop for Foo {
- fn drop(&mut self) {
- self.0.fetch_add(1, Ordering::SeqCst);
- }
- }
- let num_drops = Arc::new(AtomicUsize::new(0));
- let m = ShardedLock::new(Foo(num_drops.clone()));
- assert_eq!(num_drops.load(Ordering::SeqCst), 0);
- {
- let _inner = m.into_inner().unwrap();
- assert_eq!(num_drops.load(Ordering::SeqCst), 0);
- }
- assert_eq!(num_drops.load(Ordering::SeqCst), 1);
-}
-
-#[test]
-fn test_into_inner_poison() {
- let m = Arc::new(ShardedLock::new(NonCopy(10)));
- let m2 = m.clone();
- let _ = thread::spawn(move || {
- let _lock = m2.write().unwrap();
- panic!("test panic in inner thread to poison ShardedLock");
- })
- .join();
-
- assert!(m.is_poisoned());
- match Arc::try_unwrap(m).unwrap().into_inner() {
- Err(e) => assert_eq!(e.into_inner(), NonCopy(10)),
- Ok(x) => panic!("into_inner of poisoned ShardedLock is Ok: {:?}", x),
- }
-}
-
-#[test]
-fn test_get_mut() {
- let mut m = ShardedLock::new(NonCopy(10));
- *m.get_mut().unwrap() = NonCopy(20);
- assert_eq!(m.into_inner().unwrap(), NonCopy(20));
-}
-
-#[test]
-fn test_get_mut_poison() {
- let m = Arc::new(ShardedLock::new(NonCopy(10)));
- let m2 = m.clone();
- let _ = thread::spawn(move || {
- let _lock = m2.write().unwrap();
- panic!("test panic in inner thread to poison ShardedLock");
- })
- .join();
-
- assert!(m.is_poisoned());
- match Arc::try_unwrap(m).unwrap().get_mut() {
- Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)),
- Ok(x) => panic!("get_mut of poisoned ShardedLock is Ok: {:?}", x),
- }
-}
### external/vendor/crossbeam-utils/tests/thread.rs
@@ -1,215 +0,0 @@
-use std::any::Any;
-use std::sync::atomic::{AtomicUsize, Ordering};
-use std::thread::sleep;
-use std::time::Duration;
-
-use crossbeam_utils::thread;
-
-const THREADS: usize = 10;
-const SMALL_STACK_SIZE: usize = 20;
-
-#[test]
-fn join() {
- let counter = AtomicUsize::new(0);
- thread::scope(|scope| {
- let handle = scope.spawn(|_| {
- counter.store(1, Ordering::Relaxed);
- });
- assert!(handle.join().is_ok());
-
- let panic_handle = scope.spawn(|_| {
- panic!("\"My honey is running out!\", said Pooh.");
- });
- assert!(panic_handle.join().is_err());
- })
- .unwrap();
-
- // There should be sufficient synchronization.
- assert_eq!(1, counter.load(Ordering::Relaxed));
-}
-
-#[test]
-fn counter() {
- let counter = AtomicUsize::new(0);
- thread::scope(|scope| {
- for _ in 0..THREADS {
- scope.spawn(|_| {
- counter.fetch_add(1, Ordering::Relaxed);
- });
- }
- })
- .unwrap();
-
- assert_eq!(THREADS, counter.load(Ordering::Relaxed));
-}
-
-#[test]
-fn counter_builder() {
- let counter = AtomicUsize::new(0);
- thread::scope(|scope| {
- for i in 0..THREADS {
- scope
- .builder()
- .name(format!("child-{}", i))
- .stack_size(SMALL_STACK_SIZE)
- .spawn(|_| {
- counter.fetch_add(1, Ordering::Relaxed);
- })
- .unwrap();
- }
- })
- .unwrap();
-
- assert_eq!(THREADS, counter.load(Ordering::Relaxed));
-}
-
-#[test]
-fn counter_panic() {
- let counter = AtomicUsize::new(0);
- let result = thread::scope(|scope| {
- scope.spawn(|_| {
- panic!("\"My honey is running out!\", said Pooh.");
- });
- sleep(Duration::from_millis(100));
-
- for _ in 0..THREADS {
- scope.spawn(|_| {
- counter.fetch_add(1, Ordering::Relaxed);
- });
- }
- });
-
- assert_eq!(THREADS, counter.load(Ordering::Relaxed));
- assert!(result.is_err());
-}
-
-#[test]
-fn panic_twice() {
- let result = thread::scope(|scope| {
- scope.spawn(|_| {
- sleep(Duration::from_millis(500));
- panic!("thread #1");
- });
- scope.spawn(|_| {
- panic!("thread #2");
- });
- });
-
- let err = result.unwrap_err();
- let vec = err
- .downcast_ref::<Vec<Box<dyn Any + Send + 'static>>>()
- .unwrap();
- assert_eq!(2, vec.len());
-
- let first = vec[0].downcast_ref::<&str>().unwrap();
- let second = vec[1].downcast_ref::<&str>().unwrap();
- assert_eq!("thread #1", *first);
- assert_eq!("thread #2", *second)
-}
-
-#[test]
-fn panic_many() {
- let result = thread::scope(|scope| {
- scope.spawn(|_| panic!("deliberate panic #1"));
- scope.spawn(|_| panic!("deliberate panic #2"));
- scope.spawn(|_| panic!("deliberate panic #3"));
- });
-
- let err = result.unwrap_err();
- let vec = err
- .downcast_ref::<Vec<Box<dyn Any + Send + 'static>>>()
- .unwrap();
- assert_eq!(3, vec.len());
-
- for panic in vec.iter() {
- let panic = panic.downcast_ref::<&str>().unwrap();
- assert!(
- *panic == "deliberate panic #1"
- || *panic == "deliberate panic #2"
- || *panic == "deliberate panic #3"
- );
- }
-}
-
-#[test]
-fn nesting() {
- let var = "foo".to_string();
-
- struct Wrapper<'a> {
- var: &'a String,
- }
-
- impl<'a> Wrapper<'a> {
- fn recurse(&'a self, scope: &thread::Scope<'a>, depth: usize) {
- assert_eq!(self.var, "foo");
-
- if depth > 0 {
- scope.spawn(move |scope| {
- self.recurse(scope, depth - 1);
- });
- }
- }
- }
-
- let wrapper = Wrapper { var: &var };
-
- thread::scope(|scope| {
- scope.spawn(|scope| {
- scope.spawn(|scope| {
- wrapper.recurse(scope, 5);
- });
- });
- })
- .unwrap();
-}
-
-#[test]
-fn join_nested() {
- thread::scope(|scope| {
- scope.spawn(|scope| {
- let handle = scope.spawn(|_| 7);
-
- sleep(Duration::from_millis(200));
- handle.join().unwrap();
- });
-
- sleep(Duration::from_millis(100));
- })
- .unwrap();
-}
-
-#[test]
-fn scope_returns_ok() {
- let result = thread::scope(|scope| scope.spawn(|_| 1234).join().unwrap()).unwrap();
- assert_eq!(result, 1234);
-}
-
-#[cfg(unix)]
-#[test]
-fn as_pthread_t() {
- use std::os::unix::thread::JoinHandleExt;
- thread::scope(|scope| {
- let handle = scope.spawn(|_scope| {
- sleep(Duration::from_millis(100));
- 42
- });
- let _pthread_t = handle.as_pthread_t();
- handle.join().unwrap();
- })
- .unwrap();
-}
-
-#[cfg(windows)]
-#[test]
-fn as_raw_handle() {
- use std::os::windows::io::AsRawHandle;
- thread::scope(|scope| {
- let handle = scope.spawn(|_scope| {
- sleep(Duration::from_millis(100));
- 42
- });
- let _raw_handle = handle.as_raw_handle();
- handle.join().unwrap();
- })
- .unwrap();
-}
### external/vendor/crossbeam-utils/tests/wait_group.rs
@@ -1,67 +0,0 @@
-use std::sync::mpsc;
-use std::thread;
-use std::time::Duration;
-
-use crossbeam_utils::sync::WaitGroup;
-
-const THREADS: usize = 10;
-
-#[test]
-fn wait() {
- let wg = WaitGroup::new();
- let (tx, rx) = mpsc::channel();
-
- for _ in 0..THREADS {
- let wg = wg.clone();
- let tx = tx.clone();
-
- thread::spawn(move || {
- wg.wait();
- tx.send(()).unwrap();
- });
- }
-
- thread::sleep(Duration::from_millis(100));
-
- // At this point, all spawned threads should be blocked, so we shouldn't get anything from the
- // channel.
- assert!(rx.try_recv().is_err());
-
- wg.wait();
-
- // Now, the wait group is cleared and we should receive messages.
- for _ in 0..THREADS {
- rx.recv().unwrap();
- }
-}
-
-#[test]
-fn wait_and_drop() {
- let wg = WaitGroup::new();
- let wg2 = WaitGroup::new();
- let (tx, rx) = mpsc::channel();
-
- for _ in 0..THREADS {
- let wg = wg.clone();
- let wg2 = wg2.clone();
- let tx = tx.clone();
-
- thread::spawn(move || {
- wg2.wait();
- tx.send(()).unwrap();
- drop(wg);
- });
- }
-
- // At this point, no thread has gotten past `wg2.wait()`, so we shouldn't get anything from the
- // channel.
- assert!(rx.try_recv().is_err());
- drop(wg2);
-
- wg.wait();
-
- // Now, the wait group is cleared and we should receive messages.
- for _ in 0..THREADS {
- rx.try_recv().unwrap();
- }
-}
### external/vendor/prost-derive/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"45147dd1905e2b74e1999b67b97d9ce91b0091424b049ff3b14148abf19f5bd2","Cargo.toml":"ead70d2c5042f3983e63d28a5056647d2606e29366a6e3f3ab6e659376c3ddd6","Cargo.toml.orig":"3025dc28159a9c39a44c8aec70328c5a88179f6e1af56142ba285b4176d3fd35","LICENSE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","README.md":"6c67fa1e48f14adfaf834f520f798ddfb79f90804f46cc215ee391a7d57913a4","src/field/group.rs":"0e2a468af54d9082d858f18d5276fd549349f0048d9aaf41a3493018a811d962","src/field/map.rs":"a03791fc758802cdf4e75e197acd7975141377e3d1ad1273e6cefab2b7fddfe9","src/field/message.rs":"736e160b4e470dc6d0f2fcbf12e704c590bc1880e5fe08933c440f1cf2e767b1","src/field/mod.rs":"541c1a346a0ff4fcb4610a5c9d379e99a7dbfe8981e5c1c902ddf6c395dfda0a","src/field/oneof.rs":"c0a55cb194d9651cbc63c2a19243a7e5fc197c170a9f44af87b30b07bad21b4e","src/field/scalar.rs":"61150549be0de070845018ae5aef8c42bebdae033e4e251bddbd0bd2a892c501","src/lib.rs":"a3e62b31b0e72438b41a8a2e69241640ace46b95936c4f93269bf650386e3c59"},"package":"18bec9b0adc4eba778b33684b7ba3e7137789434769ee3ce3930463ef904cfca"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"1fe87a8d0a47b1402770759a4a233d505ecfe2f4af1f0b8d7c05f25c46d25248","Cargo.lock":"2b68a79a14cbee0dfc844198376c819899d4e87c78fca8bcf877e9a22d9a79b5","Cargo.toml":"c4f227909783d7f93ef23f91b47b1699b01a6280320119e4ad3963251ca1f600","Cargo.toml.orig":"43771716b293f4614d464969619b91148bfdb0d7d95a59352cfe803fd8aef18f","LICENSE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","README.md":"6c67fa1e48f14adfaf834f520f798ddfb79f90804f46cc215ee391a7d57913a4","src/field/group.rs":"cad8346873c7c9318b1c04f7d915aab425f842b6f7f437fb48f2a083f12a2d09","src/field/map.rs":"97b8269566a8d11a1965c77d4d8bf1d042c9e28fa4b77803c75b7d7c248adc74","src/field/message.rs":"2d49b1724789bb2d09d71168fd6d5580500a46a5c854c02d08b798129329c0e5","src/field/mod.rs":"53111de27ff47ea1970f8965173f6dbb2f2a3c0260114b1ced428ab9d67d0adb","src/field/oneof.rs":"6a3f0c3b21635d05b483ce7dddafc959bcca33fcdfdc9ddee3745ea132da8514","src/field/scalar.rs":"7374f30703ffa9df9afaee6312c4159247b8f19526d67c25e42be5eb6d70ba8d","src/lib.rs":"43c577c33deedd35aa0cef967dfd449ee6b4ac91b47c26aaf818ce1209893062"},"package":"b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"}
\ No newline at end of file
### external/vendor/prost-derive/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "f19104a3d4345f4635bbc5fd54cb5089572e2660"
+ "sha1": "13646cde7eab75c81b3047767aa0a86e7dbecf12"
},
"path_in_vcs": "prost-derive"
}
\ No newline at end of file
### external/vendor/prost-derive/Cargo.lock
@@ -0,0 +1,70 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "anyhow"
+version = "1.0.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
+
+[[package]]
+name = "either"
+version = "1.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
+
+[[package]]
+name = "itertools"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "prost-derive"
+version = "0.14.4"
+dependencies = [
+ "anyhow",
+ "itertools",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
### external/vendor/prost-derive/Cargo.toml
@@ -11,28 +11,36 @@
[package]
edition = "2021"
-rust-version = "1.70"
+rust-version = "1.85"
name = "prost-derive"
-version = "0.13.1"
+version = "0.14.4"
authors = [
"Dan Burkert <dan@danburkert.com>",
"Lucio Franco <luciofranco14@gmail.com>",
"Casper Meijn <casper@meijn.net>",
"Tokio Contributors <team@tokio.rs>",
]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = "Generate encoding and decoding implementations for Prost annotated types."
readme = "README.md"
license = "Apache-2.0"
repository = "https://github.com/tokio-rs/prost"
[lib]
-proc_macro = true
+name = "prost_derive"
+path = "src/lib.rs"
+proc-macro = true
[dependencies.anyhow]
version = "1.0.1"
[dependencies.itertools]
-version = ">=0.10.1, <=0.13"
+version = ">=0.10.1, <=0.14"
[dependencies.proc-macro2]
version = "1.0.60"
@@ -43,3 +51,6 @@ version = "1"
[dependencies.syn]
version = "2"
features = ["extra-traits"]
+
+[lints.clippy]
+collapsible_if = "allow"
### external/vendor/prost-derive/Cargo.toml.orig
@@ -10,11 +10,15 @@ edition.workspace = true
rust-version.workspace = true
[lib]
-proc_macro = true
+proc-macro = true
[dependencies]
anyhow = "1.0.1"
-itertools = ">=0.10.1, <=0.13"
+itertools = ">=0.10.1, <=0.14"
proc-macro2 = "1.0.60"
quote = "1"
syn = { version = "2", features = ["extra-traits"] }
+
+[lints.clippy]
+# This lint has MSRV 1.88
+collapsible_if = "allow"
### external/vendor/prost-derive/src/field/group.rs
@@ -1,7 +1,7 @@
use anyhow::{bail, Error};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
-use syn::Meta;
+use syn::{Meta, Path};
use crate::field::{set_bool, set_option, tag_attr, word_attr, Label};
@@ -71,29 +71,29 @@ impl Field {
}
}
- pub fn encode(&self, ident: TokenStream) -> TokenStream {
+ pub fn encode(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
let tag = self.tag;
match self.label {
Label::Optional => quote! {
if let Some(ref msg) = #ident {
- ::prost::encoding::group::encode(#tag, msg, buf);
+ #prost_path::encoding::group::encode(#tag, msg, buf);
}
},
Label::Required => quote! {
- ::prost::encoding::group::encode(#tag, &#ident, buf);
+ #prost_path::encoding::group::encode(#tag, &#ident, buf);
},
Label::Repeated => quote! {
for msg in &#ident {
- ::prost::encoding::group::encode(#tag, msg, buf);
+ #prost_path::encoding::group::encode(#tag, msg, buf);
}
},
}
}
- pub fn merge(&self, ident: TokenStream) -> TokenStream {
+ pub fn merge(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
match self.label {
Label::Optional => quote! {
- ::prost::encoding::group::merge(
+ #prost_path::encoding::group::merge(
tag,
wire_type,
#ident.get_or_insert_with(::core::default::Default::default),
@@ -102,25 +102,25 @@ impl Field {
)
},
Label::Required => quote! {
- ::prost::encoding::group::merge(tag, wire_type, #ident, buf, ctx)
+ #prost_path::encoding::group::merge(tag, wire_type, #ident, buf, ctx)
},
Label::Repeated => quote! {
- ::prost::encoding::group::merge_repeated(tag, wire_type, #ident, buf, ctx)
+ #prost_path::encoding::group::merge_repeated(tag, wire_type, #ident, buf, ctx)
},
}
}
- pub fn encoded_len(&self, ident: TokenStream) -> TokenStream {
+ pub fn encoded_len(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
let tag = self.tag;
match self.label {
Label::Optional => quote! {
- #ident.as_ref().map_or(0, |msg| ::prost::encoding::group::encoded_len(#tag, msg))
+ #ident.as_ref().map_or(0, |msg| #prost_path::encoding::group::encoded_len(#tag, msg))
},
Label::Required => quote! {
- ::prost::encoding::group::encoded_len(#tag, &#ident)
+ #prost_path::encoding::group::encoded_len(#tag, &#ident)
},
Label::Repeated => quote! {
- ::prost::encoding::group::encoded_len_repeated(#tag, &#ident)
+ #prost_path::encoding::group::encoded_len_repeated(#tag, &#ident)
},
}
}
### external/vendor/prost-derive/src/field/map.rs
@@ -2,7 +2,7 @@ use anyhow::{bail, Error};
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::punctuated::Punctuated;
-use syn::{Expr, ExprLit, Ident, Lit, Meta, MetaNameValue, Token};
+use syn::{Expr, ExprLit, Ident, Lit, Meta, MetaNameValue, Path, Token};
use crate::field::{scalar, set_option, tag_attr};
@@ -82,7 +82,7 @@ impl Field {
None => bail!("invalid map attribute: must have key and value types"),
};
if items.next().is_some() {
- bail!("invalid map attribute: {:?}", attr);
+ bail!("invalid map attribute: {attr:?}");
}
(k, v)
}
@@ -124,21 +124,21 @@ impl Field {
}
/// Returns a statement which encodes the map field.
- pub fn encode(&self, ident: TokenStream) -> TokenStream {
+ pub fn encode(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
let tag = self.tag;
let key_mod = self.key_ty.module();
- let ke = quote!(::prost::encoding::#key_mod::encode);
- let kl = quote!(::prost::encoding::#key_mod::encoded_len);
+ let ke = quote!(#prost_path::encoding::#key_mod::encode);
+ let kl = quote!(#prost_path::encoding::#key_mod::encoded_len);
let module = self.map_ty.module();
match &self.value_ty {
ValueTy::Scalar(scalar::Ty::Enumeration(ty)) => {
let default = quote!(#ty::default() as i32);
quote! {
- ::prost::encoding::#module::encode_with_default(
+ #prost_path::encoding::#module::encode_with_default(
#ke,
#kl,
- ::prost::encoding::int32::encode,
- ::prost::encoding::int32::encoded_len,
+ #prost_path::encoding::int32::encode,
+ #prost_path::encoding::int32::encoded_len,
&(#default),
#tag,
&#ident,
@@ -148,10 +148,10 @@ impl Field {
}
ValueTy::Scalar(value_ty) => {
let val_mod = value_ty.module();
- let ve = quote!(::prost::encoding::#val_mod::encode);
- let vl = quote!(::prost::encoding::#val_mod::encoded_len);
+ let ve = quote!(#prost_path::encoding::#val_mod::encode);
+ let vl = quote!(#prost_path::encoding::#val_mod::encoded_len);
quote! {
- ::prost::encoding::#module::encode(
+ #prost_path::encoding::#module::encode(
#ke,
#kl,
#ve,
@@ -163,11 +163,11 @@ impl Field {
}
}
ValueTy::Message => quote! {
- ::prost::encoding::#module::encode(
+ #prost_path::encoding::#module::encode(
#ke,
#kl,
- ::prost::encoding::message::encode,
- ::prost::encoding::message::encoded_len,
+ #prost_path::encoding::message::encode,
+ #prost_path::encoding::message::encoded_len,
#tag,
&#ident,
buf,
@@ -178,17 +178,17 @@ impl Field {
/// Returns an expression which evaluates to the result of merging a decoded key value pair
/// into the map.
- pub fn merge(&self, ident: TokenStream) -> TokenStream {
+ pub fn merge(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
let key_mod = self.key_ty.module();
- let km = quote!(::prost::encoding::#key_mod::merge);
+ let km = quote!(#prost_path::encoding::#key_mod::merge);
let module = self.map_ty.module();
match &self.value_ty {
ValueTy::Scalar(scalar::Ty::Enumeration(ty)) => {
let default = quote!(#ty::default() as i32);
quote! {
- ::prost::encoding::#module::merge_with_default(
+ #prost_path::encoding::#module::merge_with_default(
#km,
- ::prost::encoding::int32::merge,
+ #prost_path::encoding::int32::merge,
#default,
&mut #ident,
buf,
@@ -198,13 +198,13 @@ impl Field {
}
ValueTy::Scalar(value_ty) => {
let val_mod = value_ty.module();
- let vm = quote!(::prost::encoding::#val_mod::merge);
- quote!(::prost::encoding::#module::merge(#km, #vm, &mut #ident, buf, ctx))
+ let vm = quote!(#prost_path::encoding::#val_mod::merge);
+ quote!(#prost_path::encoding::#module::merge(#km, #vm, &mut #ident, buf, ctx))
}
ValueTy::Message => quote! {
- ::prost::encoding::#module::merge(
+ #prost_path::encoding::#module::merge(
#km,
- ::prost::encoding::message::merge,
+ #prost_path::encoding::message::merge,
&mut #ident,
buf,
ctx,
@@ -214,18 +214,18 @@ impl Field {
}
/// Returns an expression which evaluates to the encoded length of the map.
- pub fn encoded_len(&self, ident: TokenStream) -> TokenStream {
+ pub fn encoded_len(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
let tag = self.tag;
let key_mod = self.key_ty.module();
- let kl = quote!(::prost::encoding::#key_mod::encoded_len);
+ let kl = quote!(#prost_path::encoding::#key_mod::encoded_len);
let module = self.map_ty.module();
match &self.value_ty {
ValueTy::Scalar(scalar::Ty::Enumeration(ty)) => {
let default = quote!(#ty::default() as i32);
quote! {
- ::prost::encoding::#module::encoded_len_with_default(
+ #prost_path::encoding::#module::encoded_len_with_default(
#kl,
- ::prost::encoding::int32::encoded_len,
+ #prost_path::encoding::int32::encoded_len,
&(#default),
#tag,
&#ident,
@@ -234,13 +234,13 @@ impl Field {
}
ValueTy::Scalar(value_ty) => {
let val_mod = value_ty.module();
- let vl = quote!(::prost::encoding::#val_mod::encoded_len);
- quote!(::prost::encoding::#module::encoded_len(#kl, #vl, #tag, &#ident))
+ let vl = quote!(#prost_path::encoding::#val_mod::encoded_len);
+ quote!(#prost_path::encoding::#module::encoded_len(#kl, #vl, #tag, &#ident))
}
ValueTy::Message => quote! {
- ::prost::encoding::#module::encoded_len(
+ #prost_path::encoding::#module::encoded_len(
#kl,
- ::prost::encoding::message::encoded_len,
+ #prost_path::encoding::message::encoded_len,
#tag,
&#ident,
)
@@ -253,25 +253,24 @@ impl Field {
}
/// Returns methods to embed in the message.
- pub fn methods(&self, ident: &TokenStream) -> Option<TokenStream> {
+ pub fn methods(&self, prost_path: &Path, ident: &TokenStream) -> Option<TokenStream> {
if let ValueTy::Scalar(scalar::Ty::Enumeration(ty)) = &self.value_ty {
- let key_ty = self.key_ty.rust_type();
+ let key_ty = self.key_ty.rust_type(prost_path);
let key_ref_ty = self.key_ty.rust_ref_type();
- let get = Ident::new(&format!("get_{}", ident), Span::call_site());
- let insert = Ident::new(&format!("insert_{}", ident), Span::call_site());
+ let get = Ident::new(&format!("get_{ident}"), Span::call_site());
+ let insert = Ident::new(&format!("insert_{ident}"), Span::call_site());
let take_ref = if self.key_ty.is_numeric() {
quote!(&)
} else {
quote!()
};
let get_doc = format!(
- "Returns the enum value for the corresponding key in `{}`, \
- or `None` if the entry does not exist or it is not a valid enum value.",
- ident,
+ "Returns the enum value for the corresponding key in `{ident}`, \
+ or `None` if the entry does not exist or it is not a valid enum value."
);
- let insert_doc = format!("Inserts a key value pair into `{}`.", ident);
+ let insert_doc = format!("Inserts a key value pair into `{ident}`.");
Some(quote! {
#[doc=#get_doc]
pub fn #get(&self, key: #key_ref_ty) -> ::core::option::Option<#ty> {
@@ -297,16 +296,16 @@ impl Field {
///
/// The Debug tries to convert any enumerations met into the variants if possible, instead of
/// outputting the raw numbers.
- pub fn debug(&self, wrapper_name: TokenStream) -> TokenStream {
+ pub fn debug(&self, prost_path: &Path, wrapper_name: TokenStream) -> TokenStream {
let type_name = match self.map_ty {
MapTy::HashMap => Ident::new("HashMap", Span::call_site()),
MapTy::BTreeMap => Ident::new("BTreeMap", Span::call_site()),
};
// A fake field for generating the debug wrapper
- let key_wrapper = fake_scalar(self.key_ty.clone()).debug(quote!(KeyWrapper));
- let key = self.key_ty.rust_type();
- let value_wrapper = self.value_ty.debug();
+ let key_wrapper = fake_scalar(self.key_ty.clone()).debug(prost_path, quote!(KeyWrapper));
+ let key = self.key_ty.rust_type(prost_path);
+ let value_wrapper = self.value_ty.debug(prost_path);
let libname = self.map_ty.lib();
let fmt = quote! {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
@@ -332,7 +331,7 @@ impl Field {
};
}
- let value = ty.rust_type();
+ let value = ty.rust_type(prost_path);
quote! {
struct #wrapper_name<'a>(&'a ::#libname::collections::#type_name<#key, #value>);
impl<'a> ::core::fmt::Debug for #wrapper_name<'a> {
@@ -368,7 +367,7 @@ fn key_ty_from_str(s: &str) -> Result<scalar::Ty, Error> {
| scalar::Ty::Sfixed64
| scalar::Ty::Bool
| scalar::Ty::String => Ok(ty),
- _ => bail!("invalid map key type: {}", s),
+ _ => bail!("invalid map key type: {s}"),
}
}
@@ -386,17 +385,17 @@ impl ValueTy {
} else if s.trim() == "message" {
Ok(ValueTy::Message)
} else {
- bail!("invalid map value type: {}", s);
+ bail!("invalid map value type: {s}");
}
}
/// Returns a newtype wrapper around the ValueTy for nicer debug.
///
/// If the contained value is enumeration, it tries to convert it to the variant. If not, it
/// just forwards the implementation.
- fn debug(&self) -> TokenStream {
+ fn debug(&self, prost_path: &Path) -> TokenStream {
match self {
- ValueTy::Scalar(ty) => fake_scalar(ty.clone()).debug(quote!(ValueWrapper)),
+ ValueTy::Scalar(ty) => fake_scalar(ty.clone()).debug(prost_path, quote!(ValueWrapper)),
ValueTy::Message => quote!(
fn ValueWrapper<T>(v: T) -> T {
v
### external/vendor/prost-derive/src/field/message.rs
@@ -1,7 +1,7 @@
use anyhow::{bail, Error};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
-use syn::Meta;
+use syn::{Meta, Path};
use crate::field::{set_bool, set_option, tag_attr, word_attr, Label};
@@ -71,53 +71,53 @@ impl Field {
}
}
- pub fn encode(&self, ident: TokenStream) -> TokenStream {
+ pub fn encode(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
let tag = self.tag;
match self.label {
Label::Optional => quote! {
if let Some(ref msg) = #ident {
- ::prost::encoding::message::encode(#tag, msg, buf);
+ #prost_path::encoding::message::encode(#tag, msg, buf);
}
},
Label::Required => quote! {
- ::prost::encoding::message::encode(#tag, &#ident, buf);
+ #prost_path::encoding::message::encode(#tag, &#ident, buf);
},
Label::Repeated => quote! {
for msg in &#ident {
- ::prost::encoding::message::encode(#tag, msg, buf);
+ #prost_path::encoding::message::encode(#tag, msg, buf);
}
},
}
}
- pub fn merge(&self, ident: TokenStream) -> TokenStream {
+ pub fn merge(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
match self.label {
Label::Optional => quote! {
- ::prost::encoding::message::merge(wire_type,
+ #prost_path::encoding::message::merge(wire_type,
#ident.get_or_insert_with(::core::default::Default::default),
buf,
ctx)
},
Label::Required => quote! {
- ::prost::encoding::message::merge(wire_type, #ident, buf, ctx)
+ #prost_path::encoding::message::merge(wire_type, #ident, buf, ctx)
},
Label::Repeated => quote! {
- ::prost::encoding::message::merge_repeated(wire_type, #ident, buf, ctx)
+ #prost_path::encoding::message::merge_repeated(wire_type, #ident, buf, ctx)
},
}
}
- pub fn encoded_len(&self, ident: TokenStream) -> TokenStream {
+ pub fn encoded_len(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
let tag = self.tag;
match self.label {
Label::Optional => quote! {
- #ident.as_ref().map_or(0, |msg| ::prost::encoding::message::encoded_len(#tag, msg))
+ #ident.as_ref().map_or(0, |msg| #prost_path::encoding::message::encoded_len(#tag, msg))
},
Label::Required => quote! {
- ::prost::encoding::message::encoded_len(#tag, &#ident)
+ #prost_path::encoding::message::encoded_len(#tag, &#ident)
},
Label::Repeated => quote! {
- ::prost::encoding::message::encoded_len_repeated(#tag, &#ident)
+ #prost_path::encoding::message::encoded_len_repeated(#tag, &#ident)
},
}
}
### external/vendor/prost-derive/src/field/mod.rs
@@ -11,6 +11,7 @@ use anyhow::{bail, Error};
use proc_macro2::TokenStream;
use quote::quote;
use syn::punctuated::Punctuated;
+use syn::Path;
use syn::{Attribute, Expr, ExprLit, Lit, LitBool, LitInt, Meta, MetaNameValue, Token};
#[derive(Clone)]
@@ -89,36 +90,36 @@ impl Field {
}
/// Returns a statement which encodes the field.
- pub fn encode(&self, ident: TokenStream) -> TokenStream {
+ pub fn encode(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
match *self {
- Field::Scalar(ref scalar) => scalar.encode(ident),
- Field::Message(ref message) => message.encode(ident),
- Field::Map(ref map) => map.encode(ident),
+ Field::Scalar(ref scalar) => scalar.encode(prost_path, ident),
+ Field::Message(ref message) => message.encode(prost_path, ident),
+ Field::Map(ref map) => map.encode(prost_path, ident),
Field::Oneof(ref oneof) => oneof.encode(ident),
- Field::Group(ref group) => group.encode(ident),
+ Field::Group(ref group) => group.encode(prost_path, ident),
}
}
/// Returns an expression which evaluates to the result of merging a decoded
/// value into the field.
- pub fn merge(&self, ident: TokenStream) -> TokenStream {
+ pub fn merge(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
match *self {
- Field::Scalar(ref scalar) => scalar.merge(ident),
- Field::Message(ref message) => message.merge(ident),
- Field::Map(ref map) => map.merge(ident),
+ Field::Scalar(ref scalar) => scalar.merge(prost_path, ident),
+ Field::Message(ref message) => message.merge(prost_path, ident),
+ Field::Map(ref map) => map.merge(prost_path, ident),
Field::Oneof(ref oneof) => oneof.merge(ident),
- Field::Group(ref group) => group.merge(ident),
+ Field::Group(ref group) => group.merge(prost_path, ident),
}
}
/// Returns an expression which evaluates to the encoded length of the field.
- pub fn encoded_len(&self, ident: TokenStream) -> TokenStream {
+ pub fn encoded_len(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
match *self {
- Field::Scalar(ref scalar) => scalar.encoded_len(ident),
- Field::Map(ref map) => map.encoded_len(ident),
- Field::Message(ref msg) => msg.encoded_len(ident),
+ Field::Scalar(ref scalar) => scalar.encoded_len(prost_path, ident),
+ Field::Map(ref map) => map.encoded_len(prost_path, ident),
+ Field::Message(ref msg) => msg.encoded_len(prost_path, ident),
Field::Oneof(ref oneof) => oneof.encoded_len(ident),
- Field::Group(ref group) => group.encoded_len(ident),
+ Field::Group(ref group) => group.encoded_len(prost_path, ident),
}
}
@@ -133,18 +134,18 @@ impl Field {
}
}
- pub fn default(&self) -> TokenStream {
+ pub fn default(&self, prost_path: &Path) -> TokenStream {
match *self {
- Field::Scalar(ref scalar) => scalar.default(),
+ Field::Scalar(ref scalar) => scalar.default(prost_path),
_ => quote!(::core::default::Default::default()),
}
}
/// Produces the fragment implementing debug for the given field.
- pub fn debug(&self, ident: TokenStream) -> TokenStream {
+ pub fn debug(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
match *self {
Field::Scalar(ref scalar) => {
- let wrapper = scalar.debug(quote!(ScalarWrapper));
+ let wrapper = scalar.debug(prost_path, quote!(ScalarWrapper));
quote! {
{
#wrapper
@@ -153,7 +154,7 @@ impl Field {
}
}
Field::Map(ref map) => {
- let wrapper = map.debug(quote!(MapWrapper));
+ let wrapper = map.debug(prost_path, quote!(MapWrapper));
quote! {
{
#wrapper
@@ -165,10 +166,10 @@ impl Field {
}
}
- pub fn methods(&self, ident: &TokenStream) -> Option<TokenStream> {
+ pub fn methods(&self, prost_path: &Path, ident: &TokenStream) -> Option<TokenStream> {
match *self {
Field::Scalar(ref scalar) => scalar.methods(ident),
- Field::Map(ref map) => map.methods(ident),
+ Field::Map(ref map) => map.methods(prost_path, ident),
_ => None,
}
}
@@ -231,9 +232,7 @@ fn prost_attrs(attrs: Vec<Attribute>) -> Result<Vec<Meta>, Error> {
if let Meta::List(meta_list) = &attr.meta {
if meta_list.path.is_ident("prost") {
result.extend(
- meta_list
- .parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?
- .into_iter(),
+ meta_list.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?,
)
}
}
@@ -246,15 +245,15 @@ where
T: fmt::Debug,
{
if let Some(ref existing) = *option {
- bail!("{}: {:?} and {:?}", message, existing, value);
+ bail!("{message}: {existing:?} and {value:?}");
}
*option = Some(value);
Ok(())
}
pub fn set_bool(b: &mut bool, message: &str) -> Result<(), Error> {
if *b {
- bail!("{}", message);
+ bail!("{message}");
} else {
*b = true;
Ok(())
@@ -290,7 +289,7 @@ fn bool_attr(key: &str, attr: &Meta) -> Result<Option<bool>, Error> {
}),
..
}) => Ok(Some(value)),
- _ => bail!("invalid {} attribute", key),
+ _ => bail!("invalid {key} attribute"),
}
}
@@ -319,9 +318,9 @@ pub(super) fn tag_attr(attr: &Meta) -> Result<Option<u32>, Error> {
.map_err(Error::from)
.map(Option::Some),
Lit::Int(ref lit) => Ok(Some(lit.base10_parse()?)),
- _ => bail!("invalid tag attribute: {:?}", attr),
+ _ => bail!("invalid tag attribute: {attr:?}"),
},
- _ => bail!("invalid tag attribute: {:?}", attr),
+ _ => bail!("invalid tag attribute: {attr:?}"),
}
}
@@ -350,6 +349,6 @@ fn tags_attr(attr: &Meta) -> Result<Option<Vec<u32>>, Error> {
.map(|s| s.trim().parse::<u32>().map_err(Error::from))
.collect::<Result<Vec<u32>, _>>()
.map(Some),
- _ => bail!("invalid tag attribute: {:?}", attr),
+ _ => bail!("invalid tag attribute: {attr:?}"),
}
}
### external/vendor/prost-derive/src/field/oneof.rs
@@ -29,7 +29,7 @@ impl Field {
..
}) => parse_str::<Path>(&lit.value())?,
Meta::List(ref list) => list.parse_args::<Ident>()?.into(),
- _ => bail!("invalid oneof attribute: {:?}", attr),
+ _ => bail!("invalid oneof attribute: {attr:?}"),
};
set_option(&mut ty, t, "duplicate oneof attribute")?;
} else if let Some(t) = tags_attr(attr)? {
### external/vendor/prost-derive/src/field/scalar.rs
@@ -105,14 +105,14 @@ impl Field {
}
}
- pub fn encode(&self, ident: TokenStream) -> TokenStream {
+ pub fn encode(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
let module = self.ty.module();
let encode_fn = match self.kind {
Kind::Plain(..) | Kind::Optional(..) | Kind::Required(..) => quote!(encode),
Kind::Repeated => quote!(encode_repeated),
Kind::Packed => quote!(encode_packed),
};
- let encode_fn = quote!(::prost::encoding::#module::#encode_fn);
+ let encode_fn = quote!(#prost_path::encoding::#module::#encode_fn);
let tag = self.tag;
match self.kind {
@@ -137,13 +137,13 @@ impl Field {
/// Returns an expression which evaluates to the result of merging a decoded
/// scalar value into the field.
- pub fn merge(&self, ident: TokenStream) -> TokenStream {
+ pub fn merge(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
let module = self.ty.module();
let merge_fn = match self.kind {
Kind::Plain(..) | Kind::Optional(..) | Kind::Required(..) => quote!(merge),
Kind::Repeated | Kind::Packed => quote!(merge_repeated),
};
- let merge_fn = quote!(::prost::encoding::#module::#merge_fn);
+ let merge_fn = quote!(#prost_path::encoding::#module::#merge_fn);
match self.kind {
Kind::Plain(..) | Kind::Required(..) | Kind::Repeated | Kind::Packed => quote! {
@@ -159,14 +159,14 @@ impl Field {
}
/// Returns an expression which evaluates to the encoded length of the field.
- pub fn encoded_len(&self, ident: TokenStream) -> TokenStream {
+ pub fn encoded_len(&self, prost_path: &Path, ident: TokenStream) -> TokenStream {
let module = self.ty.module();
let encoded_len_fn = match self.kind {
Kind::Plain(..) | Kind::Optional(..) | Kind::Required(..) => quote!(encoded_len),
Kind::Repeated => quote!(encoded_len_repeated),
Kind::Packed => quote!(encoded_len_packed),
};
- let encoded_len_fn = quote!(::prost::encoding::#module::#encoded_len_fn);
+ let encoded_len_fn = quote!(#prost_path::encoding::#module::#encoded_len_fn);
let tag = self.tag;
match self.kind {
@@ -204,11 +204,11 @@ impl Field {
}
/// Returns an expression which evaluates to the default value of the field.
- pub fn default(&self) -> TokenStream {
+ pub fn default(&self, prost_path: &Path) -> TokenStream {
match self.kind {
- Kind::Plain(ref value) | Kind::Required(ref value) => value.owned(),
+ Kind::Plain(ref value) | Kind::Required(ref value) => value.owned(prost_path),
Kind::Optional(_) => quote!(::core::option::Option::None),
- Kind::Repeated | Kind::Packed => quote!(::prost::alloc::vec::Vec::new()),
+ Kind::Repeated | Kind::Packed => quote!(#prost_path::alloc::vec::Vec::new()),
}
}
@@ -236,9 +236,9 @@ impl Field {
}
/// Returns a fragment for formatting the field `ident` in `Debug`.
- pub fn debug(&self, wrapper_name: TokenStream) -> TokenStream {
+ pub fn debug(&self, prost_path: &Path, wrapper_name: TokenStream) -> TokenStream {
let wrapper = self.debug_inner(quote!(Inner));
- let inner_ty = self.ty.rust_type();
+ let inner_ty = self.ty.rust_type(prost_path);
match self.kind {
Kind::Plain(_) | Kind::Required(_) => self.debug_inner(wrapper_name),
Kind::Optional(_) => quote! {
@@ -252,7 +252,7 @@ impl Field {
},
Kind::Repeated | Kind::Packed => {
quote! {
- struct #wrapper_name<'a>(&'a ::prost::alloc::vec::Vec<#inner_ty>);
+ struct #wrapper_name<'a>(&'a #prost_path::alloc::vec::Vec<#inner_ty>);
impl<'a> ::core::fmt::Debug for #wrapper_name<'a> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let mut vec_builder = f.debug_list();
@@ -285,14 +285,13 @@ impl Field {
};
if let Ty::Enumeration(ref ty) = self.ty {
- let set = Ident::new(&format!("set_{}", ident_str), Span::call_site());
- let set_doc = format!("Sets `{}` to the provided enum value.", ident_str);
+ let set = Ident::new(&format!("set_{ident_str}"), Span::call_site());
+ let set_doc = format!("Sets `{ident_str}` to the provided enum value.");
Some(match self.kind {
Kind::Plain(ref default) | Kind::Required(ref default) => {
let get_doc = format!(
- "Returns the enum value of `{}`, \
- or the default if the field is set to an invalid enum value.",
- ident_str,
+ "Returns the enum value of `{ident_str}`, \
+ or the default if the field is set to an invalid enum value."
);
quote! {
#[doc=#get_doc]
@@ -308,9 +307,8 @@ impl Field {
}
Kind::Optional(ref default) => {
let get_doc = format!(
- "Returns the enum value of `{}`, \
- or the default if the field is unset or set to an invalid enum value.",
- ident_str,
+ "Returns the enum value of `{ident_str}`, \
+ or the default if the field is unset or set to an invalid enum value."
);
quote! {
#[doc=#get_doc]
@@ -329,11 +327,10 @@ impl Field {
}
Kind::Repeated | Kind::Packed => {
let iter_doc = format!(
- "Returns an iterator which yields the valid enum values contained in `{}`.",
- ident_str,
+ "Returns an iterator which yields the valid enum values contained in `{ident_str}`."
);
- let push = Ident::new(&format!("push_{}", ident_str), Span::call_site());
- let push_doc = format!("Appends the provided enum value to `{}`.", ident_str);
+ let push = Ident::new(&format!("push_{ident_str}"), Span::call_site());
+ let push_doc = format!("Appends the provided enum value to `{ident_str}`.");
quote! {
#[doc=#iter_doc]
pub fn #get(&self) -> ::core::iter::FilterMap<
@@ -362,8 +359,7 @@ impl Field {
};
let get_doc = format!(
- "Returns the value of `{0}`, or the default value if `{0}` is unset.",
- ident_str,
+ "Returns the value of `{ident_str}`, or the default value if `{ident_str}` is unset."
);
Some(quote! {
@@ -413,14 +409,14 @@ impl BytesTy {
match s {
"vec" => Ok(BytesTy::Vec),
"bytes" => Ok(BytesTy::Bytes),
- _ => bail!("Invalid bytes type: {}", s),
+ _ => bail!("Invalid bytes type: {s}"),
}
}
- fn rust_type(&self) -> TokenStream {
+ fn rust_type(&self, prost_path: &Path) -> TokenStream {
match self {
- BytesTy::Vec => quote! { ::prost::alloc::vec::Vec<u8> },
- BytesTy::Bytes => quote! { ::prost::bytes::Bytes },
+ BytesTy::Vec => quote! { #prost_path::alloc::vec::Vec<u8> },
+ BytesTy::Bytes => quote! { #prost_path::bytes::Bytes },
}
}
}
@@ -471,7 +467,7 @@ impl Ty {
pub fn from_str(s: &str) -> Result<Ty, Error> {
let enumeration_len = "enumeration".len();
- let error = Err(anyhow!("invalid type: {}", s));
+ let error = Err(anyhow!("invalid type: {s}"));
let ty = match s.trim() {
"float" => Ty::Float,
"double" => Ty::Double,
@@ -529,10 +525,10 @@ impl Ty {
}
// TODO: rename to 'owned_type'.
- pub fn rust_type(&self) -> TokenStream {
+ pub fn rust_type(&self, prost_path: &Path) -> TokenStream {
match self {
- Ty::String => quote!(::prost::alloc::string::String),
- Ty::Bytes(ty) => ty.rust_type(),
+ Ty::String => quote!(#prost_path::alloc::string::String),
+ Ty::Bytes(ty) => ty.rust_type(prost_path),
_ => self.rust_ref_type(),
}
}
@@ -626,7 +622,7 @@ impl DefaultValue {
{
Ok(Some(lit.clone()))
} else {
- bail!("invalid default value attribute: {:?}", attr)
+ bail!("invalid default value attribute: {attr:?}")
}
}
@@ -676,7 +672,7 @@ impl DefaultValue {
let value = value.trim();
if let Ty::Enumeration(ref path) = *ty {
- let variant = Ident::new(value, Span::call_site());
+ let variant = parse_str::<Ident>(value)?;
return Ok(DefaultValue::Enumeration(quote!(#path::#variant)));
}
@@ -779,10 +775,10 @@ impl DefaultValue {
}
}
- pub fn owned(&self) -> TokenStream {
+ pub fn owned(&self, prost_path: &Path) -> TokenStream {
match *self {
DefaultValue::String(ref value) if value.is_empty() => {
- quote!(::prost::alloc::string::String::new())
+ quote!(#prost_path::alloc::string::String::new())
}
DefaultValue::String(ref value) => quote!(#value.into()),
DefaultValue::Bytes(ref value) if value.is_empty() => {
@@ -826,3 +822,16 @@ impl ToTokens for DefaultValue {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::{DefaultValue, Ty};
+ use syn::{parse_str, Lit, Path};
+
+ #[test]
+ fn from_lit_rejects_invalid_enumeration_default_without_panic() {
+ let ty = Ty::Enumeration(parse_str::<Path>("ExampleEnum").unwrap());
+ let lit = parse_str::<Lit>("\"not-valid!\"").unwrap();
+ assert!(DefaultValue::from_lit(&ty, lit).is_err());
+ }
+}
### external/vendor/prost-derive/src/lib.rs
@@ -1,32 +1,33 @@
-#![doc(html_root_url = "https://docs.rs/prost-derive/0.13.1")]
+#![doc(html_root_url = "https://docs.rs/prost-derive/0.14.4")]
// The `quote!` macro requires deep recursion.
#![recursion_limit = "4096"]
extern crate alloc;
extern crate proc_macro;
-use anyhow::{bail, Error};
+use anyhow::{bail, Context, Error};
use itertools::Itertools;
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{
- punctuated::Punctuated, Data, DataEnum, DataStruct, DeriveInput, Expr, Fields, FieldsNamed,
- FieldsUnnamed, Ident, Index, Variant,
+ punctuated::Punctuated, Data, DataEnum, DataStruct, DeriveInput, Expr, ExprLit, Fields,
+ FieldsNamed, FieldsUnnamed, Ident, Index, Variant,
};
+use syn::{Attribute, Lit, Meta, MetaNameValue, Path, Token};
mod field;
use crate::field::Field;
+use self::field::set_option;
+
fn try_message(input: TokenStream) -> Result<TokenStream, Error> {
let input: DeriveInput = syn::parse2(input)?;
-
let ident = input.ident;
- syn::custom_keyword!(skip_debug);
- let skip_debug = input
- .attrs
- .into_iter()
- .any(|a| a.path().is_ident("prost") && a.parse_args::<skip_debug>().is_ok());
+ let Attributes {
+ skip_debug,
+ prost_path,
+ } = Attributes::new(input.attrs)?;
let variant_data = match input.data {
Data::Struct(variant_data) => variant_data,
@@ -74,7 +75,7 @@ fn try_message(input: TokenStream) -> Result<TokenStream, Error> {
}
Ok(None) => None,
Err(err) => Some(Err(
- err.context(format!("invalid message field {}.{}", ident, field_ident))
+ err.context(format!("invalid message field {ident}.{field_ident}"))
)),
}
})
@@ -86,7 +87,7 @@ fn try_message(input: TokenStream) -> Result<TokenStream, Error> {
// Sort the fields by tag number so that fields will be encoded in tag order.
// TODO: This encodes oneof fields in the position of their lowest tag,
// regardless of the currently occupied variant, is that consequential?
- // See: https://developers.google.com/protocol-buffers/docs/encoding#order
+ // See: https://protobuf.dev/programming-guides/encoding/#order
fields.sort_by_key(|(_, field)| field.tags().into_iter().min().unwrap());
let fields = fields;
@@ -96,23 +97,19 @@ fn try_message(input: TokenStream) -> Result<TokenStream, Error> {
.duplicates()
.next()
{
- bail!(
- "message {} has multiple fields with tag {}",
- ident,
- duplicate_tag
- )
+ bail!("message {ident} has multiple fields with tag {duplicate_tag}",)
};
let encoded_len = fields
.iter()
- .map(|(field_ident, field)| field.encoded_len(quote!(self.#field_ident)));
+ .map(|(field_ident, field)| field.encoded_len(&prost_path, quote!(self.#field_ident)));
let encode = fields
.iter()
- .map(|(field_ident, field)| field.encode(quote!(self.#field_ident)));
+ .map(|(field_ident, field)| field.encode(&prost_path, quote!(self.#field_ident)));
let merge = fields.iter().map(|(field_ident, field)| {
- let merge = field.merge(quote!(value));
+ let merge = field.merge(&prost_path, quote!(value));
let tags = field.tags().into_iter().map(|tag| quote!(#tag));
let tags = Itertools::intersperse(tags, quote!(|));
@@ -141,15 +138,15 @@ fn try_message(input: TokenStream) -> Result<TokenStream, Error> {
let default = if is_struct {
let default = fields.iter().map(|(field_ident, field)| {
- let value = field.default();
+ let value = field.default(&prost_path);
quote!(#field_ident: #value,)
});
quote! {#ident {
#(#default)*
}}
} else {
let default = fields.iter().map(|(_, field)| {
- let value = field.default();
+ let value = field.default(&prost_path);
quote!(#value,)
});
quote! {#ident (
@@ -159,7 +156,7 @@ fn try_message(input: TokenStream) -> Result<TokenStream, Error> {
let methods = fields
.iter()
- .flat_map(|(field_ident, field)| field.methods(field_ident))
+ .flat_map(|(field_ident, field)| field.methods(&prost_path, field_ident))
.collect::<Vec<_>>();
let methods = if methods.is_empty() {
quote!()
@@ -173,25 +170,25 @@ fn try_message(input: TokenStream) -> Result<TokenStream, Error> {
};
let expanded = quote! {
- impl #impl_generics ::prost::Message for #ident #ty_generics #where_clause {
+ impl #impl_generics #prost_path::Message for #ident #ty_generics #where_clause {
#[allow(unused_variables)]
- fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) {
+ fn encode_raw(&self, buf: &mut impl #prost_path::bytes::BufMut) {
#(#encode)*
}
#[allow(unused_variables)]
fn merge_field(
&mut self,
tag: u32,
- wire_type: ::prost::encoding::WireType,
- buf: &mut impl ::prost::bytes::Buf,
- ctx: ::prost::encoding::DecodeContext,
- ) -> ::core::result::Result<(), ::prost::DecodeError>
+ wire_type: #prost_path::encoding::wire_type::WireType,
+ buf: &mut impl #prost_path::bytes::Buf,
+ ctx: #prost_path::encoding::DecodeContext,
+ ) -> ::core::result::Result<(), #prost_path::DecodeError>
{
#struct_name
match tag {
#(#merge)*
- _ => ::prost::encoding::skip_field(wire_type, tag, buf, ctx),
+ _ => #prost_path::encoding::skip_field(wire_type, tag, buf, ctx),
}
}
@@ -215,7 +212,7 @@ fn try_message(input: TokenStream) -> Result<TokenStream, Error> {
expanded
} else {
let debugs = unsorted_fields.iter().map(|(field_ident, field)| {
- let wrapper = field.debug(quote!(self.#field_ident));
+ let wrapper = field.debug(&prost_path, quote!(self.#field_ident));
let call = if is_struct {
quote!(builder.field(stringify!(#field_ident), &wrapper))
} else {
@@ -264,6 +261,8 @@ fn try_enumeration(input: TokenStream) -> Result<TokenStream, Error> {
let input: DeriveInput = syn::parse2(input)?;
let ident = input.ident;
+ let Attributes { prost_path, .. } = Attributes::new(input.attrs)?;
+
let generics = &input.generics;
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
@@ -274,8 +273,9 @@ fn try_enumeration(input: TokenStream) -> Result<TokenStream, Error> {
};
// Map the variants into 'fields'.
- let mut variants: Vec<(Ident, Expr)> = Vec::new();
+ let mut variants: Vec<(Ident, Expr, Option<TokenStream>)> = Vec::new();
for Variant {
+ attrs,
ident,
fields,
discriminant,
@@ -288,9 +288,15 @@ fn try_enumeration(input: TokenStream) -> Result<TokenStream, Error> {
bail!("Enumeration variants may not have fields")
}
}
-
match discriminant {
- Some((_, expr)) => variants.push((ident, expr)),
+ Some((_, expr)) => {
+ let deprecated_attr = if attrs.iter().any(|v| v.path().is_ident("deprecated")) {
+ Some(quote!(#[allow(deprecated)]))
+ } else {
+ None
+ };
+ variants.push((ident, expr, deprecated_attr))
+ }
None => bail!("Enumeration variants must have a discriminant"),
}
}
@@ -299,27 +305,25 @@ fn try_enumeration(input: TokenStream) -> Result<TokenStream, Error> {
panic!("Enumeration must have at least one variant");
}
- let default = variants[0].0.clone();
+ let (default, _, default_deprecated) = variants[0].clone();
- let is_valid = variants.iter().map(|(_, value)| quote!(#value => true));
+ let is_valid = variants.iter().map(|(_, value, _)| quote!(#value => true));
let from = variants
.iter()
- .map(|(variant, value)| quote!(#value => ::core::option::Option::Some(#ident::#variant)));
+ .map(|(variant, value, deprecated)| quote!(#value => ::core::option::Option::Some(#deprecated #ident::#variant)));
let try_from = variants
.iter()
- .map(|(variant, value)| quote!(#value => ::core::result::Result::Ok(#ident::#variant)));
+ .map(|(variant, value, deprecated)| quote!(#value => ::core::result::Result::Ok(#deprecated #ident::#variant)));
- let is_valid_doc = format!("Returns `true` if `value` is a variant of `{}`.", ident);
- let from_i32_doc = format!(
- "Converts an `i32` to a `{}`, or `None` if `value` is not a valid variant.",
- ident
- );
+ let is_valid_doc = format!("Returns `true` if `value` is a variant of `{ident}`.");
+ let from_i32_doc =
+ format!("Converts an `i32` to a `{ident}`, or `None` if `value` is not a valid variant.");
let expanded = quote! {
impl #impl_generics #ident #ty_generics #where_clause {
#[doc=#is_valid_doc]
- pub fn is_valid(value: i32) -> bool {
+ pub const fn is_valid(value: i32) -> bool {
match value {
#(#is_valid,)*
_ => false,
@@ -338,7 +342,7 @@ fn try_enumeration(input: TokenStream) -> Result<TokenStream, Error> {
impl #impl_generics ::core::default::Default for #ident #ty_generics #where_clause {
fn default() -> #ident {
- #ident::#default
+ #default_deprecated #ident::#default
}
}
@@ -349,12 +353,12 @@ fn try_enumeration(input: TokenStream) -> Result<TokenStream, Error> {
}
impl #impl_generics ::core::convert::TryFrom::<i32> for #ident #ty_generics #where_clause {
- type Error = ::prost::UnknownEnumValue;
+ type Error = #prost_path::UnknownEnumValue;
- fn try_from(value: i32) -> ::core::result::Result<#ident, ::prost::UnknownEnumValue> {
+ fn try_from(value: i32) -> ::core::result::Result<#ident, #prost_path::UnknownEnumValue> {
match value {
#(#try_from,)*
- _ => ::core::result::Result::Err(::prost::UnknownEnumValue(value)),
+ _ => ::core::result::Result::Err(#prost_path::UnknownEnumValue(value)),
}
}
}
@@ -373,11 +377,10 @@ fn try_oneof(input: TokenStream) -> Result<TokenStream, Error> {
let ident = input.ident;
- syn::custom_keyword!(skip_debug);
- let skip_debug = input
- .attrs
- .into_iter()
- .any(|a| a.path().is_ident("prost") && a.parse_args::<skip_debug>().is_ok());
+ let Attributes {
+ skip_debug,
+ prost_path,
+ } = Attributes::new(input.attrs)?;
let variants = match input.data {
Data::Enum(DataEnum { variants, .. }) => variants,
@@ -389,7 +392,7 @@ fn try_oneof(input: TokenStream) -> Result<TokenStream, Error> {
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
// Map the variants into 'fields'.
- let mut fields: Vec<(Ident, Field)> = Vec::new();
+ let mut fields: Vec<(Ident, Field, Option<TokenStream>)> = Vec::new();
for Variant {
attrs,
ident: variant_ident,
@@ -407,62 +410,59 @@ fn try_oneof(input: TokenStream) -> Result<TokenStream, Error> {
if variant_fields.len() != 1 {
bail!("Oneof enum variants must have a single field");
}
+ let deprecated_attr = if attrs.iter().any(|v| v.path().is_ident("deprecated")) {
+ Some(quote!(#[allow(deprecated)]))
+ } else {
+ None
+ };
match Field::new_oneof(attrs)? {
- Some(field) => fields.push((variant_ident, field)),
+ Some(field) => fields.push((variant_ident, field, deprecated_attr)),
None => bail!("invalid oneof variant: oneof variants may not be ignored"),
}
}
// Oneof variants cannot be oneofs themselves, so it's impossible to have a field with multiple
// tags.
- assert!(fields.iter().all(|(_, field)| field.tags().len() == 1));
+ assert!(fields.iter().all(|(_, field, _)| field.tags().len() == 1));
if let Some(duplicate_tag) = fields
.iter()
- .flat_map(|(_, field)| field.tags())
+ .flat_map(|(_, field, _)| field.tags())
.duplicates()
.next()
{
- bail!(
- "invalid oneof {}: multiple variants have tag {}",
- ident,
- duplicate_tag
- );
+ bail!("invalid oneof {ident}: multiple variants have tag {duplicate_tag}");
}
- let encode = fields.iter().map(|(variant_ident, field)| {
- let encode = field.encode(quote!(*value));
- quote!(#ident::#variant_ident(ref value) => { #encode })
+ let encode = fields.iter().map(|(variant_ident, field, deprecated)| {
+ let encode = field.encode(&prost_path, quote!(*value));
+ quote!(#deprecated #ident::#variant_ident(ref value) => { #encode })
});
- let merge = fields.iter().map(|(variant_ident, field)| {
+ let merge = fields.iter().map(|(variant_ident, field, deprecated)| {
let tag = field.tags()[0];
- let merge = field.merge(quote!(value));
+ let merge = field.merge(&prost_path, quote!(value));
quote! {
- #tag => {
- match field {
- ::core::option::Option::Some(#ident::#variant_ident(ref mut value)) => {
- #merge
- },
- _ => {
- let mut owned_value = ::core::default::Default::default();
- let value = &mut owned_value;
- #merge.map(|_| *field = ::core::option::Option::Some(#ident::#variant_ident(owned_value)))
- },
- }
+ #deprecated
+ #tag => if let ::core::option::Option::Some(#ident::#variant_ident(value)) = field {
+ #merge
+ } else {
+ let mut owned_value = ::core::default::Default::default();
+ let value = &mut owned_value;
+ #merge.map(|_| *field = ::core::option::Option::Some(#deprecated #ident::#variant_ident(owned_value)))
}
}
});
- let encoded_len = fields.iter().map(|(variant_ident, field)| {
- let encoded_len = field.encoded_len(quote!(*value));
- quote!(#ident::#variant_ident(ref value) => #encoded_len)
+ let encoded_len = fields.iter().map(|(variant_ident, field, deprecated)| {
+ let encoded_len = field.encoded_len(&prost_path, quote!(*value));
+ quote!(#deprecated #ident::#variant_ident(ref value) => #encoded_len)
});
let expanded = quote! {
impl #impl_generics #ident #ty_generics #where_clause {
/// Encodes the message to a buffer.
- pub fn encode(&self, buf: &mut impl ::prost::bytes::BufMut) {
+ pub fn encode(&self, buf: &mut impl #prost_path::bytes::BufMut) {
match *self {
#(#encode,)*
}
@@ -472,10 +472,10 @@ fn try_oneof(input: TokenStream) -> Result<TokenStream, Error> {
pub fn merge(
field: &mut ::core::option::Option<#ident #ty_generics>,
tag: u32,
- wire_type: ::prost::encoding::WireType,
- buf: &mut impl ::prost::bytes::Buf,
- ctx: ::prost::encoding::DecodeContext,
- ) -> ::core::result::Result<(), ::prost::DecodeError>
+ wire_type: #prost_path::encoding::wire_type::WireType,
+ buf: &mut impl #prost_path::bytes::Buf,
+ ctx: #prost_path::encoding::DecodeContext,
+ ) -> ::core::result::Result<(), #prost_path::DecodeError>
{
match tag {
#(#merge,)*
@@ -496,9 +496,9 @@ fn try_oneof(input: TokenStream) -> Result<TokenStream, Error> {
let expanded = if skip_debug {
expanded
} else {
- let debug = fields.iter().map(|(variant_ident, field)| {
- let wrapper = field.debug(quote!(*value));
- quote!(#ident::#variant_ident(ref value) => {
+ let debug = fields.iter().map(|(variant_ident, field, deprecated)| {
+ let wrapper = field.debug(&prost_path, quote!(*value));
+ quote!(#deprecated #ident::#variant_ident(ref value) => {
let wrapper = #wrapper;
f.debug_tuple(stringify!(#variant_ident))
.field(&wrapper)
@@ -526,6 +526,71 @@ pub fn oneof(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
try_oneof(input.into()).unwrap().into()
}
+/// Get the items belonging to the 'prost' list attribute, e.g. `#[prost(foo, bar="baz")]`.
+fn prost_attrs(attrs: Vec<Attribute>) -> Result<Vec<Meta>, Error> {
+ let mut result = Vec::new();
+ for attr in attrs.iter() {
+ if let Meta::List(meta_list) = &attr.meta {
+ if meta_list.path.is_ident("prost") {
+ result.extend(
+ meta_list.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?,
+ )
+ }
+ }
+ }
+ Ok(result)
+}
+
+/// Extracts the path to prost specified using the `#[prost(prost_path = "...")]` attribute. When
+/// missing, falls back to default, which is `::prost`.
+fn get_prost_path(attrs: &[Meta]) -> Result<Path, Error> {
+ let mut prost_path = None;
+
+ for attr in attrs {
+ match attr {
+ Meta::NameValue(MetaNameValue {
+ path,
+ value:
+ Expr::Lit(ExprLit {
+ lit: Lit::Str(lit), ..
+ }),
+ ..
+ }) if path.is_ident("prost_path") => {
+ let path: Path =
+ syn::parse_str(&lit.value()).context("invalid prost_path argument")?;
+
+ set_option(&mut prost_path, path, "duplicate prost_path attributes")?;
+ }
+ _ => continue,
+ }
+ }
+
+ let prost_path =
+ prost_path.unwrap_or_else(|| syn::parse_str("::prost").expect("default prost_path"));
+
+ Ok(prost_path)
+}
+
+struct Attributes {
+ skip_debug: bool,
+ prost_path: Path,
+}
+
+impl Attributes {
+ fn new(attrs: Vec<Attribute>) -> Result<Self, Error> {
+ syn::custom_keyword!(skip_debug);
+ let skip_debug = attrs.iter().any(|a| a.parse_args::<skip_debug>().is_ok());
+
+ let attrs = prost_attrs(attrs)?;
+ let prost_path = get_prost_path(&attrs)?;
+
+ Ok(Self {
+ skip_debug,
+ prost_path,
+ })
+ }
+}
+
#[cfg(test)]
mod test {
use crate::{try_message, try_oneof};
### external/vendor/prost/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"17f8aef293eb8b1b6037d090faf4a3d0200b45c71c7e04198bd8110469991746","Cargo.toml":"1fbba13d18616dbf70e2b6dc138eeb150c1fdedc69bb9d0241d78db0a51b196a","Cargo.toml.orig":"3553552a894dac2d6c92242d5408c0a8e90cfd18ca8d38f49dce66e42f71729d","LICENSE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","README.md":"606dccfcabd1797578a542e45f40df0ae37a42e53edd9df4c8c050653e586787","benches/varint.rs":"25e28eadeb5092882281eaa16307ae72cbdabe04a308c9cfe15d3a62c8ead40b","src/encoding.rs":"df60b41c214362063540a2bb65560c9c17eea071279b87e582cf35c200cb0da3","src/error.rs":"f0549601c38d34ee8c32dd5567bc2722d09b8cafe533da0d2124d5fd32cc0d6e","src/lib.rs":"9aa005356c2c5a384be5b3d3a3e721cee598f7f3760ed88765b4127eb79ce2ff","src/message.rs":"71de498c10c7d60c7732cb17f7e614158953a1ff249f52273b094b9afbf857f4","src/name.rs":"4524233d6c1a85ca55ce54d9740e72ecbb05714b558e8a77346c0a125a2e5320","src/types.rs":"908f5000fa83058e82e25f2041e8dc522d46961668cf703ba5446cd1964e3545"},"package":"e13db3d3fde688c61e2446b4d843bc27a7e8af269a69440c0308021dc92333cc"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"4fa96b154b282372a1e11b8aea18807f683919d29a05947a21f3a4b5eb605d95","Cargo.lock":"caa0281413aa2d14e29ffdd6dcf5811c34c0bc8390bf3a8eaccfd7bec35f1794","Cargo.toml":"0d6f06dd96d0b54342ea7e1d9a3fdc8d166782bde60771b06c5cb0bb38a06592","Cargo.toml.orig":"75b4fead75f27eb8a8ad972293fb8410a59cb612b33679dfce7532994775494c","LICENSE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","README.md":"0f12f109bff21e8eb36ca61759552d4c9545494ab1bde86301b745d9e8ebe200","benches/varint.rs":"fb4043e0a6393e2799aafef64ce0717dc2720b7251173eb3d1c394d43fd76dde","src/encoding.rs":"2262da48addaf0544bb7c1f38ae617160fc4fba1781bd9c99fdc96b0dd6288d4","src/encoding/length_delimiter.rs":"cd21e4891444b157a844d7aef423a51f69735cdd21cb33ae8968fa330b3b303c","src/encoding/varint.rs":"29f75ff30f6a30e07ec017f3260cff9ffbf52cddbd9e4f26f72d705725cebc10","src/encoding/wire_type.rs":"2fc76491b4d4a1226a2a8aee0c4bfdfa846723fa864b982bb91cfee9e9f861bb","src/error.rs":"3c24128fca68c3cca7f48e7d185f9696c949dc9de7d22bbac1871f393f36b992","src/lib.rs":"0f15a2b2ef06e424beac918e33c68aaac90a91dfe778b1be05fa015a706aaacb","src/message.rs":"466407987e2dfb94640845ac9ec722b249ee9d86e54c1918de225e5da527e27b","src/name.rs":"c60a283ffb67ae358f0c34fdb5dac28a71f56ca16fa3d0bbfcffc0f9d23ae63c","src/types.rs":"4c73041aa3ad7daad9f82ac484ae728dc6f712cc6c3da2aa6514b6428002e0d1"},"package":"528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"}
\ No newline at end of file
### external/vendor/prost/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "f19104a3d4345f4635bbc5fd54cb5089572e2660"
+ "sha1": "13646cde7eab75c81b3047767aa0a86e7dbecf12"
},
"path_in_vcs": "prost"
}
\ No newline at end of file
### external/vendor/prost/Cargo.lock
@@ -0,0 +1,963 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "alloca"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "anes"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
+
+[[package]]
+name = "anstyle"
+version = "1.0.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
+
+[[package]]
+name = "anyhow"
+version = "1.0.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "bit-set"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
+dependencies = [
+ "bit-vec",
+]
+
+[[package]]
+name = "bit-vec"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
+
+[[package]]
+name = "bitflags"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
+
+[[package]]
+name = "bytes"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
+
+[[package]]
+name = "cast"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
+
+[[package]]
+name = "cc"
+version = "1.2.62"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "chacha20"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "rand_core 0.10.1",
+]
+
+[[package]]
+name = "ciborium"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
+dependencies = [
+ "ciborium-io",
+ "ciborium-ll",
+ "serde",
+]
+
+[[package]]
+name = "ciborium-io"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
+
+[[package]]
+name = "ciborium-ll"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
+dependencies = [
+ "ciborium-io",
+ "half",
+]
+
+[[package]]
+name = "clap"
+version = "4.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
+dependencies = [
+ "clap_builder",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
+dependencies = [
+ "anstyle",
+ "clap_lex",
+]
+
+[[package]]
+name = "clap_lex"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "criterion"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3"
+dependencies = [
+ "alloca",
+ "anes",
+ "cast",
+ "ciborium",
+ "clap",
+ "criterion-plot",
+ "itertools",
+ "num-traits",
+ "oorandom",
+ "page_size",
+ "regex",
+ "serde",
+ "serde_json",
+ "tinytemplate",
+ "walkdir",
+]
+
+[[package]]
+name = "criterion-plot"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea"
+dependencies = [
+ "cast",
+ "itertools",
+]
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+[[package]]
+name = "either"
+version = "1.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 6.0.0",
+ "rand_core 0.10.1",
+ "wasip2",
+ "wasip3",
+]
+
+[[package]]
+name = "half"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
+dependencies = [
+ "cfg-if",
+ "crunchy",
+ "zerocopy",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "id-arena"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
+
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "itertools"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "leb128fmt"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+
+[[package]]
+name = "libc"
+version = "0.2.186"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "log"
+version = "0.4.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "616ec5685824bcc94416c6d4a7a446eea774a31efd7062c8480ba6fd06d7a6e5"
+
+[[package]]
+name = "memchr"
+version = "2.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "oorandom"
+version = "11.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
+
+[[package]]
+name = "page_size"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da"
+dependencies = [
+ "libc",
+ "winapi",
+]
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "proptest"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
+dependencies = [
+ "bit-set",
+ "bit-vec",
+ "bitflags",
+ "num-traits",
+ "rand 0.9.4",
+ "rand_chacha",
+ "rand_xorshift",
+ "regex-syntax",
+ "rusty-fork",
+ "tempfile",
+ "unarray",
+]
+
+[[package]]
+name = "prost"
+version = "0.14.4"
+dependencies = [
+ "bytes",
+ "criterion",
+ "proptest",
+ "prost-derive",
+ "rand 0.10.1",
+]
+
+[[package]]
+name = "prost-derive"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
+dependencies = [
+ "anyhow",
+ "itertools",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "quick-error"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
+
+[[package]]
+name = "quote"
+version = "1.0.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
+dependencies = [
+ "rand_chacha",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.2",
+ "rand_core 0.10.1",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "rand_xorshift"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
+dependencies = [
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "regex"
+version = "1.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
+
+[[package]]
+name = "rustix"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys",
+]
+
+[[package]]
+name = "rusty-fork"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
+dependencies = [
+ "fnv",
+ "quick-error",
+ "tempfile",
+ "wait-timeout",
+]
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.150"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "shlex"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom 0.4.2",
+ "once_cell",
+ "rustix",
+ "windows-sys",
+]
+
+[[package]]
+name = "tinytemplate"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
+dependencies = [
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "unarray"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
+[[package]]
+name = "wait-timeout"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "wasip2"
+version = "1.0.3+wasi-0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"
+dependencies = [
+ "wit-bindgen 0.57.1",
+]
+
+[[package]]
+name = "wasip3"
+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
+dependencies = [
+ "wit-bindgen 0.51.0",
+]
+
+[[package]]
+name = "wasm-encoder"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
+dependencies = [
+ "leb128fmt",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.15.5",
+ "indexmap",
+ "semver",
+]
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+dependencies = [
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "prettyplease",
+ "syn",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
+dependencies = [
+ "anyhow",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+ "wasmparser",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.49"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bce33a6288fa3f072a8c2c7d0f2fdbb90e28298f0135c1f99b96c3db2efcc60b"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.49"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd425244944f4ab65ccff928e7323354c5a018c75838362fdce749dfad2ee1e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
### external/vendor/prost/Cargo.toml
@@ -11,15 +11,21 @@
[package]
edition = "2021"
-rust-version = "1.70"
+rust-version = "1.85"
name = "prost"
-version = "0.13.1"
+version = "0.14.4"
authors = [
"Dan Burkert <dan@danburkert.com>",
"Lucio Franco <luciofranco14@gmail.com>",
"Casper Meijn <casper@meijn.net>",
"Tokio Contributors <team@tokio.rs>",
]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = "A Protocol Buffers implementation for the Rust Language."
readme = "README.md"
keywords = [
@@ -30,37 +36,39 @@ categories = ["encoding"]
license = "Apache-2.0"
repository = "https://github.com/tokio-rs/prost"
+[features]
+default = [
+ "derive",
+ "std",
+]
+derive = ["dep:prost-derive"]
+no-recursion-limit = []
+std = []
+
[lib]
+name = "prost"
+path = "src/lib.rs"
bench = false
[[bench]]
name = "varint"
+path = "benches/varint.rs"
harness = false
[dependencies.bytes]
version = "1"
default-features = false
[dependencies.prost-derive]
-version = "0.13.1"
+version = "0.14.4"
optional = true
[dev-dependencies.criterion]
-version = "0.5"
+version = "0.8"
default-features = false
[dev-dependencies.proptest]
version = "1"
[dev-dependencies.rand]
-version = "0.8"
-
-[features]
-default = [
- "derive",
- "std",
-]
-derive = ["dep:prost-derive"]
-no-recursion-limit = []
-prost-derive = ["derive"]
-std = []
+version = "0.10"
### external/vendor/prost/Cargo.toml.orig
@@ -18,18 +18,17 @@ bench = false
[features]
default = ["derive", "std"]
derive = ["dep:prost-derive"]
-prost-derive = ["derive"] # deprecated, please use derive feature instead
no-recursion-limit = []
std = []
[dependencies]
bytes = { version = "1", default-features = false }
-prost-derive = { version = "0.13.1", path = "../prost-derive", optional = true }
+prost-derive = { version = "0.14.4", path = "../prost-derive", optional = true }
[dev-dependencies]
-criterion = { version = "0.5", default-features = false }
+criterion = { version = "0.8", default-features = false }
proptest = "1"
-rand = "0.8"
+rand = "0.10"
[[bench]]
name = "varint"
### external/vendor/prost/README.md
@@ -1,3 +1,4 @@
+[](https://gist.github.com/rusty-snake/574a91f1df9f97ec77ca308d6d731e29)
[](https://github.com/tokio-rs/prost/actions/workflows/ci.yml?query=branch%3Amaster)
[](https://docs.rs/prost/)
[](https://crates.io/crates/prost)
@@ -6,7 +7,7 @@
# *PROST!*
-`prost` is a [Protocol Buffers](https://developers.google.com/protocol-buffers/)
+`prost` is a [Protocol Buffers](https://protobuf.dev/)
implementation for the [Rust Language](https://www.rust-lang.org/). `prost`
generates simple, idiomatic Rust code from `proto2` and `proto3` files.
@@ -17,7 +18,7 @@ Compared to other Protocol Buffers implementations, `prost`
* Retains comments from `.proto` files in generated Rust code.
* Allows existing Rust types (not generated from a `.proto`) to be serialized
and deserialized by adding attributes.
-* Uses the [`bytes::{Buf, BufMut}`](https://github.com/carllerche/bytes)
+* Uses the [`bytes::{Buf, BufMut}`](https://github.com/tokio-rs/bytes)
abstractions for serialization instead of `std::io::{Read, Write}`.
* Respects the Protobuf `package` specifier when organizing generated code
into Rust modules.
@@ -30,9 +31,9 @@ First, add `prost` and its public dependencies to your `Cargo.toml`:
```ignore
[dependencies]
-prost = "0.13"
+prost = "0.14"
# Only necessary if using Protobuf well-known types:
-prost-types = "0.13"
+prost-types = "0.14"
```
The recommended way to add `.proto` compilation to a Cargo project is to use the
@@ -46,10 +47,9 @@ See the [snazzy repository][snazzy] for a simple start-to-finish example.
### MSRV
-`prost` follows the `tokio-rs` project's MSRV model and supports 1.70. For more
-information on the tokio msrv policy you can check it out [here][tokio msrv]
-
-[tokio msrv]: https://github.com/tokio-rs/tokio/#supported-rust-versions
+`prost` will keep a rolling MSRV (minimum supported rust version) policy of at least 6 months.
+When increasing the MSRV, the new Rust version must have been released at least six months ago.
+The current MSRV is 1.85.
## Generated Code
@@ -73,7 +73,7 @@ Prost can now generate code for `.proto` files that don't have a package spec.
`prost` will translate the Protobuf package into
a Rust module. For example, given the `package` specifier:
-[package]: https://developers.google.com/protocol-buffers/docs/proto#packages
+[package]: https://protobuf.dev/programming-guides/proto3/#packages
```protobuf,ignore
package foo.bar;
@@ -164,7 +164,7 @@ The `#[derive(::prost::Enumeration)]` annotation added to the generated
```rust,ignore
impl PhoneType {
- pub fn is_valid(value: i32) -> bool { ... }
+ pub const fn is_valid(value: i32) -> bool { ... }
#[deprecated]
pub fn from_i32(value: i32) -> Option<PhoneType> { ... }
}
@@ -380,9 +380,9 @@ the `std` features in `prost` and `prost-types`:
```ignore
[dependencies]
-prost = { version = "0.13.1", default-features = false, features = ["prost-derive"] }
+prost = { version = "0.14.4", default-features = false, features = ["derive"] }
# Only necessary if using Protobuf well-known types:
-prost-types = { version = "0.13.1", default-features = false }
+prost-types = { version = "0.14.4", default-features = false }
```
Additionally, configure `prost-build` to output `BTreeMap`s instead of `HashMap`s
@@ -459,44 +459,70 @@ pub enum Gender {
## Nix
-The prost project maintains flakes support for local development. Once you have
-nix and nix flakes setup you can just run `nix develop` to get a shell
-configured with the required dependencies to compile the whole project.
+The prost project supports development using Nix flakes. Once you have Nix and flakes enabled, you can simply run:
+
+```bash
+nix develop
+```
+
+This will drop you into a shell with all dependencies configured to build the entire project.
+
+If you want to use the minimum supported Rust version ([see MSRV](#msrv)) as required by policy, run:
+
+```bash
+nix develop .#rust_minimum_version
+```
+
+This ensures compatibility testing and development with the oldest supported toolchain version.
## Feature Flags
- `std`: Enable integration with standard library. Disable this feature for `no_std` support. This feature is enabled by default.
- `derive`: Enable integration with `prost-derive`. Disable this feature to reduce compile times. This feature is enabled by default.
- `prost-derive`: Deprecated. Alias for `derive` feature.
- `no-recursion-limit`: Disable the recursion limit. The recursion limit is 100 and cannot be customized.
+## Contributing
+
+The current maintainer is not contributing new features and doesn't have the time to review new features. Bug fixes and small improvements are welcome. Feel free to contribute small and easily reviewable PRs.
+
+Bug fixes are still important, and security fixes will be released as soon as possible. Contact the `#prost` channel in [Tokio discord](https://discord.gg/tokio) if you feel a bug or security fix is not getting enough attention.
+
+The maintainer expects the official `protobuf` project to release their rust library soon and expects it to be as fully featured as the C++ library. See their [source code](https://github.com/protocolbuffers/protobuf/tree/main/rust) and [crate](https://crates.io/crates/protobuf/4.33.1-release) for more information.
+
## FAQ
1. **Could `prost` be implemented as a serializer for [Serde](https://serde.rs/)?**
- Probably not, however I would like to hear from a Serde expert on the matter.
- There are two complications with trying to serialize Protobuf messages with
- Serde:
+ Probably not, however I would like to hear from a Serde expert on the matter.
+ There are two complications with trying to serialize Protobuf messages with
+ Serde:
- - Protobuf fields require a numbered tag, and currently there appears to be no
- mechanism suitable for this in `serde`.
- - The mapping of Protobuf type to Rust type is not 1-to-1. As a result,
- trait-based approaches to dispatching don't work very well. Example: six
- different Protobuf field types correspond to a Rust `Vec<i32>`: `repeated
- int32`, `repeated sint32`, `repeated sfixed32`, and their packed
- counterparts.
+ - Protobuf fields require a numbered tag, and currently there appears to be no
+ mechanism suitable for this in `serde`.
+ - The mapping of Protobuf type to Rust type is not 1-to-1. As a result,
+ trait-based approaches to dispatching don't work very well. Example: six
+ different Protobuf field types correspond to a Rust `Vec<i32>`: `repeated
+ int32`, `repeated sint32`, `repeated sfixed32`, and their packed
+ counterparts.
- But it is possible to place `serde` derive tags onto the generated types, so
- the same structure can support both `prost` and `Serde`.
+ But it is possible to place `serde` derive tags onto the generated types, so
+ the same structure can support both `prost` and `Serde`.
2. **I get errors when trying to run `cargo test` on MacOS**
- If the errors are about missing `autoreconf` or similar, you can probably fix
- them by running
+ If the errors are about missing `autoreconf` or similar, you can probably fix
+ them by running
+
+ ```ignore
+ brew install automake
+ brew install libtool
+ ```
+
+3. **Why are most fields are wrapped in an `Option`?**
- ```ignore
- brew install automake
- brew install libtool
- ```
+ In the `protobuf` wire protocol all fields are optional. The design of `prost` choose to expose
+ this to the user of the types. `prost` leans toward correctness and safety, aligned with Rust’s
+ philosophy — even at the cost of verbosity.
## License
### external/vendor/prost/benches/varint.rs
@@ -2,13 +2,13 @@ use std::mem;
use bytes::Buf;
use criterion::{Criterion, Throughput};
-use prost::encoding::{decode_varint, encode_varint, encoded_len_varint};
+use prost::encoding::varint::{decode_varint, encode_varint, encoded_len_varint};
use rand::{rngs::StdRng, seq::SliceRandom, SeedableRng};
fn benchmark_varint(criterion: &mut Criterion, name: &str, mut values: Vec<u64>) {
// Shuffle the values in a stable order.
values.shuffle(&mut StdRng::seed_from_u64(0));
- let name = format!("varint/{}", name);
+ let name = format!("varint/{name}");
let encoded_len = values
.iter()
@@ -28,7 +28,7 @@ fn benchmark_varint(criterion: &mut Criterion, name: &str, mut values: Vec<u64>)
for &value in &encode_values {
encode_varint(value, &mut buf);
}
- criterion::black_box(&buf);
+ std::hint::black_box(&buf);
})
}
})
@@ -50,7 +50,7 @@ fn benchmark_varint(criterion: &mut Criterion, name: &str, mut values: Vec<u64>)
while buf.has_remaining() {
let result = decode_varint(&mut buf);
debug_assert!(result.is_ok());
- criterion::black_box(&result);
+ std::hint::black_box(&result);
}
})
}
@@ -65,7 +65,7 @@ fn benchmark_varint(criterion: &mut Criterion, name: &str, mut values: Vec<u64>)
for &value in &values {
sum += encoded_len_varint(value);
}
- criterion::black_box(sum);
+ std::hint::black_box(sum);
})
})
.throughput(Throughput::Bytes(decoded_len));
### external/vendor/prost/src/encoding.rs
@@ -1,180 +1,32 @@
//! Utility functions and types for encoding and decoding Protobuf types.
//!
-//! Meant to be used only from `Message` implementations.
-
-#![allow(clippy::implicit_hasher, clippy::ptr_arg)]
+//! This module contains the encoding and decoding primitives for Protobuf as described in
+//! <https://protobuf.dev/programming-guides/encoding/>.
+//!
+//! This module is `pub`, but is only for prost internal use. The `prost-derive` crate needs access for its `Message` implementations.
use alloc::collections::BTreeMap;
-use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
-use core::cmp::min;
use core::mem;
use core::str;
-use core::u32;
-use core::usize;
use ::bytes::{Buf, BufMut, Bytes};
+use crate::error::DecodeErrorKind;
use crate::DecodeError;
use crate::Message;
-/// Encodes an integer value into LEB128 variable length format, and writes it to the buffer.
-/// The buffer must have enough remaining space (maximum 10 bytes).
-#[inline]
-pub fn encode_varint(mut value: u64, buf: &mut impl BufMut) {
- // Varints are never more than 10 bytes
- for _ in 0..10 {
- if value < 0x80 {
- buf.put_u8(value as u8);
- break;
- } else {
- buf.put_u8(((value & 0x7F) | 0x80) as u8);
- value >>= 7;
- }
- }
-}
-
-/// Decodes a LEB128-encoded variable length integer from the buffer.
-#[inline]
-pub fn decode_varint(buf: &mut impl Buf) -> Result<u64, DecodeError> {
- let bytes = buf.chunk();
- let len = bytes.len();
- if len == 0 {
- return Err(DecodeError::new("invalid varint"));
- }
-
- let byte = bytes[0];
- if byte < 0x80 {
- buf.advance(1);
- Ok(u64::from(byte))
- } else if len > 10 || bytes[len - 1] < 0x80 {
- let (value, advance) = decode_varint_slice(bytes)?;
- buf.advance(advance);
- Ok(value)
- } else {
- decode_varint_slow(buf)
- }
-}
-
-/// Decodes a LEB128-encoded variable length integer from the slice, returning the value and the
-/// number of bytes read.
-///
-/// Based loosely on [`ReadVarint64FromArray`][1] with a varint overflow check from
-/// [`ConsumeVarint`][2].
-///
-/// ## Safety
-///
-/// The caller must ensure that `bytes` is non-empty and either `bytes.len() >= 10` or the last
-/// element in bytes is < `0x80`.
-///
-/// [1]: https://github.com/google/protobuf/blob/3.3.x/src/google/protobuf/io/coded_stream.cc#L365-L406
-/// [2]: https://github.com/protocolbuffers/protobuf-go/blob/v1.27.1/encoding/protowire/wire.go#L358
-#[inline]
-fn decode_varint_slice(bytes: &[u8]) -> Result<(u64, usize), DecodeError> {
- // Fully unrolled varint decoding loop. Splitting into 32-bit pieces gives better performance.
-
- // Use assertions to ensure memory safety, but it should always be optimized after inline.
- assert!(!bytes.is_empty());
- assert!(bytes.len() > 10 || bytes[bytes.len() - 1] < 0x80);
-
- let mut b: u8 = unsafe { *bytes.get_unchecked(0) };
- let mut part0: u32 = u32::from(b);
- if b < 0x80 {
- return Ok((u64::from(part0), 1));
- };
- part0 -= 0x80;
- b = unsafe { *bytes.get_unchecked(1) };
- part0 += u32::from(b) << 7;
- if b < 0x80 {
- return Ok((u64::from(part0), 2));
- };
- part0 -= 0x80 << 7;
- b = unsafe { *bytes.get_unchecked(2) };
- part0 += u32::from(b) << 14;
- if b < 0x80 {
- return Ok((u64::from(part0), 3));
- };
- part0 -= 0x80 << 14;
- b = unsafe { *bytes.get_unchecked(3) };
- part0 += u32::from(b) << 21;
- if b < 0x80 {
- return Ok((u64::from(part0), 4));
- };
- part0 -= 0x80 << 21;
- let value = u64::from(part0);
-
- b = unsafe { *bytes.get_unchecked(4) };
- let mut part1: u32 = u32::from(b);
- if b < 0x80 {
- return Ok((value + (u64::from(part1) << 28), 5));
- };
- part1 -= 0x80;
- b = unsafe { *bytes.get_unchecked(5) };
- part1 += u32::from(b) << 7;
- if b < 0x80 {
- return Ok((value + (u64::from(part1) << 28), 6));
- };
- part1 -= 0x80 << 7;
- b = unsafe { *bytes.get_unchecked(6) };
- part1 += u32::from(b) << 14;
- if b < 0x80 {
- return Ok((value + (u64::from(part1) << 28), 7));
- };
- part1 -= 0x80 << 14;
- b = unsafe { *bytes.get_unchecked(7) };
- part1 += u32::from(b) << 21;
- if b < 0x80 {
- return Ok((value + (u64::from(part1) << 28), 8));
- };
- part1 -= 0x80 << 21;
- let value = value + ((u64::from(part1)) << 28);
-
- b = unsafe { *bytes.get_unchecked(8) };
- let mut part2: u32 = u32::from(b);
- if b < 0x80 {
- return Ok((value + (u64::from(part2) << 56), 9));
- };
- part2 -= 0x80;
- b = unsafe { *bytes.get_unchecked(9) };
- part2 += u32::from(b) << 7;
- // Check for u64::MAX overflow. See [`ConsumeVarint`][1] for details.
- // [1]: https://github.com/protocolbuffers/protobuf-go/blob/v1.27.1/encoding/protowire/wire.go#L358
- if b < 0x02 {
- return Ok((value + (u64::from(part2) << 56), 10));
- };
-
- // We have overrun the maximum size of a varint (10 bytes) or the final byte caused an overflow.
- // Assume the data is corrupt.
- Err(DecodeError::new("invalid varint"))
-}
+pub mod varint;
+pub use varint::{decode_varint, encode_varint, encoded_len_varint};
-/// Decodes a LEB128-encoded variable length integer from the buffer, advancing the buffer as
-/// necessary.
-///
-/// Contains a varint overflow check from [`ConsumeVarint`][1].
-///
-/// [1]: https://github.com/protocolbuffers/protobuf-go/blob/v1.27.1/encoding/protowire/wire.go#L358
-#[inline(never)]
-#[cold]
-fn decode_varint_slow(buf: &mut impl Buf) -> Result<u64, DecodeError> {
- let mut value = 0;
- for count in 0..min(10, buf.remaining()) {
- let byte = buf.get_u8();
- value |= u64::from(byte & 0x7F) << (count * 7);
- if byte <= 0x7F {
- // Check for u64::MAX overflow. See [`ConsumeVarint`][1] for details.
- // [1]: https://github.com/protocolbuffers/protobuf-go/blob/v1.27.1/encoding/protowire/wire.go#L358
- if count == 9 && byte >= 0x02 {
- return Err(DecodeError::new("invalid varint"));
- } else {
- return Ok(value);
- }
- }
- }
+pub mod length_delimiter;
+pub use length_delimiter::{
+ decode_length_delimiter, encode_length_delimiter, length_delimiter_len,
+};
- Err(DecodeError::new("invalid varint"))
-}
+pub mod wire_type;
+pub use wire_type::{check_wire_type, WireType};
/// Additional information passed to every decode/merge function.
///
@@ -232,63 +84,22 @@ impl DecodeContext {
#[inline]
pub(crate) fn limit_reached(&self) -> Result<(), DecodeError> {
if self.recurse_count == 0 {
- Err(DecodeError::new("recursion limit reached"))
+ Err(DecodeErrorKind::RecursionLimitReached.into())
} else {
Ok(())
}
}
#[cfg(feature = "no-recursion-limit")]
#[inline]
- #[allow(clippy::unnecessary_wraps)] // needed in other features
pub(crate) fn limit_reached(&self) -> Result<(), DecodeError> {
Ok(())
}
}
-/// Returns the encoded length of the value in LEB128 variable length format.
-/// The returned value will be between 1 and 10, inclusive.
-#[inline]
-pub fn encoded_len_varint(value: u64) -> usize {
- // Based on [VarintSize64][1].
- // [1]: https://github.com/google/protobuf/blob/3.3.x/src/google/protobuf/io/coded_stream.h#L1301-L1309
- ((((value | 1).leading_zeros() ^ 63) * 9 + 73) / 64) as usize
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum WireType {
- Varint = 0,
- SixtyFourBit = 1,
- LengthDelimited = 2,
- StartGroup = 3,
- EndGroup = 4,
- ThirtyTwoBit = 5,
-}
-
pub const MIN_TAG: u32 = 1;
pub const MAX_TAG: u32 = (1 << 29) - 1;
-impl TryFrom<u64> for WireType {
- type Error = DecodeError;
-
- #[inline]
- fn try_from(value: u64) -> Result<Self, Self::Error> {
- match value {
- 0 => Ok(WireType::Varint),
- 1 => Ok(WireType::SixtyFourBit),
- 2 => Ok(WireType::LengthDelimited),
- 3 => Ok(WireType::StartGroup),
- 4 => Ok(WireType::EndGroup),
- 5 => Ok(WireType::ThirtyTwoBit),
- _ => Err(DecodeError::new(format!(
- "invalid wire type value: {}",
- value
- ))),
- }
- }
-}
-
/// Encodes a Protobuf field key, which consists of a wire type designator and
/// the field tag.
#[inline]
@@ -304,13 +115,13 @@ pub fn encode_key(tag: u32, wire_type: WireType, buf: &mut impl BufMut) {
pub fn decode_key(buf: &mut impl Buf) -> Result<(u32, WireType), DecodeError> {
let key = decode_varint(buf)?;
if key > u64::from(u32::MAX) {
- return Err(DecodeError::new(format!("invalid key value: {}", key)));
+ return Err(DecodeErrorKind::InvalidKey { key }.into());
}
let wire_type = WireType::try_from(key & 0x07)?;
let tag = key as u32 >> 3;
if tag < MIN_TAG {
- return Err(DecodeError::new("invalid tag value: 0"));
+ return Err(DecodeErrorKind::InvalidTag.into());
}
Ok((tag, wire_type))
@@ -319,21 +130,8 @@ pub fn decode_key(buf: &mut impl Buf) -> Result<(u32, WireType), DecodeError> {
/// Returns the width of an encoded Protobuf field key with the given tag.
/// The returned width will be between 1 and 5 bytes (inclusive).
#[inline]
-pub fn key_len(tag: u32) -> usize {
- encoded_len_varint(u64::from(tag << 3))
-}
-
-/// Checks that the expected wire type matches the actual wire type,
-/// or returns an error result.
-#[inline]
-pub fn check_wire_type(expected: WireType, actual: WireType) -> Result<(), DecodeError> {
- if expected != actual {
- return Err(DecodeError::new(format!(
- "invalid wire type: {:?} (expected {:?})",
- actual, expected
- )));
- }
- Ok(())
+pub const fn key_len(tag: u32) -> usize {
+ encoded_len_varint((tag << 3) as u64)
}
/// Helper function which abstracts reading a length delimiter prefix followed
@@ -351,7 +149,7 @@ where
let len = decode_varint(buf)?;
let remaining = buf.remaining();
if len > remaining as u64 {
- return Err(DecodeError::new("buffer underflow"));
+ return Err(DecodeErrorKind::BufferUnderflow.into());
}
let limit = remaining - len as usize;
@@ -360,7 +158,7 @@ where
}
if buf.remaining() != limit {
- return Err(DecodeError::new("delimited length exceeded"));
+ return Err(DecodeErrorKind::DelimitedLengthExceeded.into());
}
Ok(())
}
@@ -382,18 +180,18 @@ pub fn skip_field(
match inner_wire_type {
WireType::EndGroup => {
if inner_tag != tag {
- return Err(DecodeError::new("unexpected end group tag"));
+ return Err(DecodeErrorKind::UnexpectedEndGroupTag.into());
}
break 0;
}
_ => skip_field(inner_wire_type, inner_tag, buf, ctx.enter_recursion())?,
}
},
- WireType::EndGroup => return Err(DecodeError::new("unexpected end group tag")),
+ WireType::EndGroup => return Err(DecodeErrorKind::UnexpectedEndGroupTag.into()),
};
if len > buf.remaining() as u64 {
- return Err(DecodeError::new("buffer underflow"));
+ return Err(DecodeErrorKind::BufferUnderflow.into());
}
buf.advance(len as usize);
@@ -598,7 +396,7 @@ macro_rules! fixed_width {
) -> Result<(), DecodeError> {
check_wire_type($wire_type, wire_type)?;
if buf.remaining() < $width {
- return Err(DecodeError::new("buffer underflow"));
+ return Err(DecodeErrorKind::BufferUnderflow.into());
}
*value = buf.$get();
Ok(())
@@ -740,6 +538,7 @@ macro_rules! length_delimited {
}
#[inline]
+ #[allow(clippy::ptr_arg)]
pub fn encoded_len(tag: u32, value: &$ty) -> usize {
key_len(tag) + encoded_len_varint(value.len() as u64) + value.len()
}
@@ -785,7 +584,7 @@ pub mod string {
// in the buf implementation, a drop guard is used.
unsafe {
struct DropGuard<'a>(&'a mut Vec<u8>);
- impl<'a> Drop for DropGuard<'a> {
+ impl Drop for DropGuard<'_> {
#[inline]
fn drop(&mut self) {
self.0.clear();
@@ -800,9 +599,7 @@ pub mod string {
mem::forget(drop_guard);
Ok(())
}
- Err(_) => Err(DecodeError::new(
- "invalid string value: data is not UTF-8 encoded",
- )),
+ Err(_) => Err(DecodeErrorKind::InvalidString.into()),
}
}
}
@@ -887,6 +684,8 @@ impl sealed::BytesAdapter for Vec<u8> {
}
pub mod bytes {
+ use crate::error::DecodeErrorKind;
+
use super::*;
pub fn encode(tag: u32, value: &impl BytesAdapter, buf: &mut impl BufMut) {
@@ -904,7 +703,7 @@ pub mod bytes {
check_wire_type(WireType::LengthDelimited, wire_type)?;
let len = decode_varint(buf)?;
if len > buf.remaining() as u64 {
- return Err(DecodeError::new("buffer underflow"));
+ return Err(DecodeErrorKind::BufferUnderflow.into());
}
let len = len as usize;
@@ -915,7 +714,7 @@ pub mod bytes {
// > types and strings, if the same field appears multiple times, the parser accepts the
// > last value it sees.
//
- // [1]: https://developers.google.com/protocol-buffers/docs/encoding#optional
+ // [1]: https://protobuf.dev/programming-guides/encoding/#last-one-wins
//
// This is intended for A and B both being Bytes so it is zero-copy.
// Some combinations of A and B types may cause a double-copy,
@@ -933,7 +732,7 @@ pub mod bytes {
check_wire_type(WireType::LengthDelimited, wire_type)?;
let len = decode_varint(buf)?;
if len > buf.remaining() as u64 {
- return Err(DecodeError::new("buffer underflow"));
+ return Err(DecodeErrorKind::BufferUnderflow.into());
}
let len = len as usize;
@@ -1067,6 +866,8 @@ pub mod message {
}
pub mod group {
+ use crate::error::DecodeErrorKind;
+
use super::*;
pub fn encode<M>(tag: u32, msg: &M, buf: &mut impl BufMut)
@@ -1095,7 +896,7 @@ pub mod group {
let (field_tag, field_wire_type) = decode_key(buf)?;
if field_wire_type == WireType::EndGroup {
if field_tag != tag {
- return Err(DecodeError::new("unexpected end group tag"));
+ return Err(DecodeErrorKind::UnexpectedEndGroupTag.into());
}
return Ok(());
}
@@ -1350,7 +1151,6 @@ mod test {
use alloc::string::ToString;
use core::borrow::Borrow;
use core::fmt::Debug;
- use core::u64;
use ::bytes::BytesMut;
use proptest::{prelude::*, test_runner::TestCaseResult};
@@ -1525,101 +1325,6 @@ mod test {
assert!(s.is_empty());
}
- #[test]
- fn varint() {
- fn check(value: u64, encoded: &[u8]) {
- // Small buffer.
- let mut buf = Vec::with_capacity(1);
- encode_varint(value, &mut buf);
- assert_eq!(buf, encoded);
-
- // Large buffer.
- let mut buf = Vec::with_capacity(100);
- encode_varint(value, &mut buf);
- assert_eq!(buf, encoded);
-
- assert_eq!(encoded_len_varint(value), encoded.len());
-
- // See: https://github.com/tokio-rs/prost/pull/1008 for copying reasoning.
- let mut encoded_copy = encoded;
- let roundtrip_value = decode_varint(&mut encoded_copy).expect("decoding failed");
- assert_eq!(value, roundtrip_value);
-
- let mut encoded_copy = encoded;
- let roundtrip_value =
- decode_varint_slow(&mut encoded_copy).expect("slow decoding failed");
- assert_eq!(value, roundtrip_value);
- }
-
- check(2u64.pow(0) - 1, &[0x00]);
- check(2u64.pow(0), &[0x01]);
-
- check(2u64.pow(7) - 1, &[0x7F]);
- check(2u64.pow(7), &[0x80, 0x01]);
- check(300, &[0xAC, 0x02]);
-
- check(2u64.pow(14) - 1, &[0xFF, 0x7F]);
- check(2u64.pow(14), &[0x80, 0x80, 0x01]);
-
- check(2u64.pow(21) - 1, &[0xFF, 0xFF, 0x7F]);
- check(2u64.pow(21), &[0x80, 0x80, 0x80, 0x01]);
-
- check(2u64.pow(28) - 1, &[0xFF, 0xFF, 0xFF, 0x7F]);
- check(2u64.pow(28), &[0x80, 0x80, 0x80, 0x80, 0x01]);
-
- check(2u64.pow(35) - 1, &[0xFF, 0xFF, 0xFF, 0xFF, 0x7F]);
- check(2u64.pow(35), &[0x80, 0x80, 0x80, 0x80, 0x80, 0x01]);
-
- check(2u64.pow(42) - 1, &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F]);
- check(2u64.pow(42), &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01]);
-
- check(
- 2u64.pow(49) - 1,
- &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F],
- );
- check(
- 2u64.pow(49),
- &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01],
- );
-
- check(
- 2u64.pow(56) - 1,
- &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F],
- );
- check(
- 2u64.pow(56),
- &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01],
- );
-
- check(
- 2u64.pow(63) - 1,
- &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F],
- );
- check(
- 2u64.pow(63),
- &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01],
- );
-
- check(
- u64::MAX,
- &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01],
- );
- }
-
- const U64_MAX_PLUS_ONE: &[u8] = &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02];
-
- #[test]
- fn varint_overflow() {
- let mut copy = U64_MAX_PLUS_ONE;
- decode_varint(&mut copy).expect_err("decoding u64::MAX + 1 succeeded");
- }
-
- #[test]
- fn variant_slow_overflow() {
- let mut copy = U64_MAX_PLUS_ONE;
- decode_varint_slow(&mut copy).expect_err("slow decoding u64::MAX + 1 succeeded");
- }
-
/// This big bowl o' macro soup generates an encoding property test for each combination of map
/// type, scalar map key, and value type.
/// TODO: these tests take a long time to compile, can this be improved?
@@ -1723,4 +1428,35 @@ mod test {
(String, string),
(Vec<u8>, bytes)
]);
+
+ #[test]
+ /// `decode_varint` accepts a `Buf`, which can be multiple concatenated buffers.
+ /// This test ensures that future optimizations don't break the
+ /// `decode_varint` for non-continuous memory.
+ fn split_varint_decoding() {
+ let mut test_values = Vec::<u64>::with_capacity(10 * 2);
+ test_values.push(128);
+ for i in 2..9 {
+ test_values.push((1 << (7 * i)) - 1);
+ test_values.push(1 << (7 * i));
+ }
+
+ for v in test_values {
+ let mut buf = BytesMut::with_capacity(10);
+ encode_varint(v, &mut buf);
+ let half_len = buf.len() / 2;
+ let len = buf.len();
+ // this weird sequence here splits the buffer into two instances of Bytes
+ // which we then stitch together with `bytes::buf::Buf::chain`
+ // which ensures the varint bytes are not in a single chunk
+ let b2 = buf.split_off(half_len);
+ let mut c = buf.chain(b2);
+
+ // make sure all the bytes are inside
+ assert_eq!(c.remaining(), len);
+ // make sure the first chunk is split as we expected
+ assert_eq!(c.chunk().len(), half_len);
+ assert_eq!(v, decode_varint(&mut c).unwrap());
+ }
+ }
}
### external/vendor/prost/src/encoding/length_delimiter.rs
@@ -0,0 +1,64 @@
+use crate::error::DecodeErrorKind;
+pub use crate::error::{DecodeError, EncodeError, UnknownEnumValue};
+pub use crate::message::Message;
+pub use crate::name::Name;
+
+use bytes::{Buf, BufMut};
+
+use crate::encoding::varint::{decode_varint, encode_varint, encoded_len_varint};
+
+/// Encodes a length delimiter to the buffer.
+///
+/// See [Message::encode_length_delimited] for more info.
+///
+/// An error will be returned if the buffer does not have sufficient capacity to encode the
+/// delimiter.
+pub fn encode_length_delimiter(length: usize, buf: &mut impl BufMut) -> Result<(), EncodeError> {
+ let length = length as u64;
+ let required = encoded_len_varint(length);
+ let remaining = buf.remaining_mut();
+ if required > remaining {
+ return Err(EncodeError::new(required, remaining));
+ }
+ encode_varint(length, buf);
+ Ok(())
+}
+
+/// Returns the encoded length of a length delimiter.
+///
+/// Applications may use this method to ensure sufficient buffer capacity before calling
+/// `encode_length_delimiter`. The returned size will be between 1 and 10, inclusive.
+pub fn length_delimiter_len(length: usize) -> usize {
+ encoded_len_varint(length as u64)
+}
+
+/// Decodes a length delimiter from the buffer.
+///
+/// This method allows the length delimiter to be decoded independently of the message, when the
+/// message is encoded with [Message::encode_length_delimited].
+///
+/// An error may be returned in two cases:
+///
+/// * If the supplied buffer contains fewer than 10 bytes, then an error indicates that more
+/// input is required to decode the full delimiter.
+/// * If the supplied buffer contains 10 bytes or more, then the buffer contains an invalid
+/// delimiter, and typically the buffer should be considered corrupt.
+///
+/// # Examples
+///
+/// ```
+/// use prost::bytes::Bytes;
+///
+/// let mut buf = Bytes::from(vec![0x04, 0x0a, 0x02, 0x01, 0x02]);
+/// let len = prost::decode_length_delimiter(&mut buf).unwrap();
+///
+/// assert_eq!(len, 4);
+/// assert_eq!(&buf[..], [0x0a, 0x02, 0x01, 0x02]);
+/// ```
+pub fn decode_length_delimiter(mut buf: impl Buf) -> Result<usize, DecodeError> {
+ let length = decode_varint(&mut buf)?;
+ if length > usize::MAX as u64 {
+ return Err(DecodeErrorKind::LengthDelimiterTooLarge.into());
+ }
+ Ok(length as usize)
+}
### external/vendor/prost/src/encoding/varint.rs
@@ -0,0 +1,278 @@
+use core::cmp::min;
+use core::num::NonZeroU64;
+
+use ::bytes::{Buf, BufMut};
+
+use crate::{error::DecodeErrorKind, DecodeError};
+
+/// Encodes an integer value into LEB128 variable length format, and writes it to the buffer.
+/// The buffer must have enough remaining space (maximum 10 bytes).
+#[inline]
+pub fn encode_varint(mut value: u64, buf: &mut impl BufMut) {
+ // Varints are never more than 10 bytes
+ for _ in 0..10 {
+ if value < 0x80 {
+ buf.put_u8(value as u8);
+ break;
+ } else {
+ buf.put_u8(((value & 0x7F) | 0x80) as u8);
+ value >>= 7;
+ }
+ }
+}
+
+/// Returns the encoded length of the value in LEB128 variable length format.
+/// The returned value will be between 1 and 10, inclusive.
+#[inline]
+pub const fn encoded_len_varint(value: u64) -> usize {
+ // Based on [VarintSize64][1].
+ // [1]: https://github.com/protocolbuffers/protobuf/blob/v28.3/src/google/protobuf/io/coded_stream.h#L1744-L1756
+ // Safety: value | 1 is non-zero.
+ let log2value = unsafe { NonZeroU64::new_unchecked(value | 1) }.ilog2();
+ ((log2value * 9 + (64 + 9)) / 64) as usize
+}
+
+/// Decodes a LEB128-encoded variable length integer from the buffer.
+#[inline]
+pub fn decode_varint(buf: &mut impl Buf) -> Result<u64, DecodeError> {
+ let bytes = buf.chunk();
+ let len = bytes.len();
+ if len == 0 {
+ return Err(DecodeErrorKind::InvalidVarint.into());
+ }
+
+ let byte = bytes[0];
+ if byte < 0x80 {
+ buf.advance(1);
+ Ok(u64::from(byte))
+ } else if len > 10 || bytes[len - 1] < 0x80 {
+ let (value, advance) = decode_varint_slice(bytes)?;
+ buf.advance(advance);
+ Ok(value)
+ } else {
+ decode_varint_slow(buf)
+ }
+}
+
+/// Decodes a LEB128-encoded variable length integer from the slice, returning the value and the
+/// number of bytes read.
+///
+/// Based loosely on [`ReadVarint64FromArray`][1] with a varint overflow check from
+/// [`ConsumeVarint`][2].
+///
+/// ## Safety
+///
+/// The caller must ensure that `bytes` is non-empty and either `bytes.len() >= 10` or the last
+/// element in bytes is < `0x80`.
+///
+/// [1]: https://github.com/google/protobuf/blob/3.3.x/src/google/protobuf/io/coded_stream.cc#L365-L406
+/// [2]: https://github.com/protocolbuffers/protobuf-go/blob/v1.27.1/encoding/protowire/wire.go#L358
+#[inline]
+fn decode_varint_slice(bytes: &[u8]) -> Result<(u64, usize), DecodeError> {
+ // Fully unrolled varint decoding loop. Splitting into 32-bit pieces gives better performance.
+
+ // Use assertions to ensure memory safety, but it should always be optimized after inline.
+ assert!(!bytes.is_empty());
+ assert!(bytes.len() > 10 || bytes[bytes.len() - 1] < 0x80);
+
+ let mut b: u8 = unsafe { *bytes.get_unchecked(0) };
+ let mut part0: u32 = u32::from(b);
+ if b < 0x80 {
+ return Ok((u64::from(part0), 1));
+ };
+ part0 -= 0x80;
+ b = unsafe { *bytes.get_unchecked(1) };
+ part0 += u32::from(b) << 7;
+ if b < 0x80 {
+ return Ok((u64::from(part0), 2));
+ };
+ part0 -= 0x80 << 7;
+ b = unsafe { *bytes.get_unchecked(2) };
+ part0 += u32::from(b) << 14;
+ if b < 0x80 {
+ return Ok((u64::from(part0), 3));
+ };
+ part0 -= 0x80 << 14;
+ b = unsafe { *bytes.get_unchecked(3) };
+ part0 += u32::from(b) << 21;
+ if b < 0x80 {
+ return Ok((u64::from(part0), 4));
+ };
+ part0 -= 0x80 << 21;
+ let value = u64::from(part0);
+
+ b = unsafe { *bytes.get_unchecked(4) };
+ let mut part1: u32 = u32::from(b);
+ if b < 0x80 {
+ return Ok((value + (u64::from(part1) << 28), 5));
+ };
+ part1 -= 0x80;
+ b = unsafe { *bytes.get_unchecked(5) };
+ part1 += u32::from(b) << 7;
+ if b < 0x80 {
+ return Ok((value + (u64::from(part1) << 28), 6));
+ };
+ part1 -= 0x80 << 7;
+ b = unsafe { *bytes.get_unchecked(6) };
+ part1 += u32::from(b) << 14;
+ if b < 0x80 {
+ return Ok((value + (u64::from(part1) << 28), 7));
+ };
+ part1 -= 0x80 << 14;
+ b = unsafe { *bytes.get_unchecked(7) };
+ part1 += u32::from(b) << 21;
+ if b < 0x80 {
+ return Ok((value + (u64::from(part1) << 28), 8));
+ };
+ part1 -= 0x80 << 21;
+ let value = value + ((u64::from(part1)) << 28);
+
+ b = unsafe { *bytes.get_unchecked(8) };
+ let mut part2: u32 = u32::from(b);
+ if b < 0x80 {
+ return Ok((value + (u64::from(part2) << 56), 9));
+ };
+ part2 -= 0x80;
+ b = unsafe { *bytes.get_unchecked(9) };
+ part2 += u32::from(b) << 7;
+ // Check for u64::MAX overflow. See [`ConsumeVarint`][1] for details.
+ // [1]: https://github.com/protocolbuffers/protobuf-go/blob/v1.27.1/encoding/protowire/wire.go#L358
+ if b < 0x02 {
+ return Ok((value + (u64::from(part2) << 56), 10));
+ };
+
+ // We have overrun the maximum size of a varint (10 bytes) or the final byte caused an overflow.
+ // Assume the data is corrupt.
+ Err(DecodeErrorKind::InvalidVarint.into())
+}
+
+/// Decodes a LEB128-encoded variable length integer from the buffer, advancing the buffer as
+/// necessary.
+///
+/// Contains a varint overflow check from [`ConsumeVarint`][1].
+///
+/// [1]: https://github.com/protocolbuffers/protobuf-go/blob/v1.27.1/encoding/protowire/wire.go#L358
+#[inline(never)]
+#[cold]
+fn decode_varint_slow(buf: &mut impl Buf) -> Result<u64, DecodeError> {
+ let mut value = 0;
+ for count in 0..min(10, buf.remaining()) {
+ let byte = buf.get_u8();
+ value |= u64::from(byte & 0x7F) << (count * 7);
+ if byte <= 0x7F {
+ // Check for u64::MAX overflow. See [`ConsumeVarint`][1] for details.
+ // [1]: https://github.com/protocolbuffers/protobuf-go/blob/v1.27.1/encoding/protowire/wire.go#L358
+ if count == 9 && byte >= 0x02 {
+ return Err(DecodeErrorKind::InvalidVarint.into());
+ } else {
+ return Ok(value);
+ }
+ }
+ }
+
+ Err(DecodeErrorKind::InvalidVarint.into())
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn varint() {
+ fn check(value: u64, encoded: &[u8]) {
+ // Small buffer.
+ let mut buf = Vec::with_capacity(1);
+ encode_varint(value, &mut buf);
+ assert_eq!(buf, encoded);
+
+ // Large buffer.
+ let mut buf = Vec::with_capacity(100);
+ encode_varint(value, &mut buf);
+ assert_eq!(buf, encoded);
+
+ assert_eq!(encoded_len_varint(value), encoded.len());
+
+ // See: https://github.com/tokio-rs/prost/pull/1008 for copying reasoning.
+ let mut encoded_copy = encoded;
+ let roundtrip_value = decode_varint(&mut encoded_copy).expect("decoding failed");
+ assert_eq!(value, roundtrip_value);
+
+ let (roundtrip_value, advance) = decode_varint_slice(encoded).expect("decoding failed");
+ assert_eq!(value, roundtrip_value);
+ assert_eq!(encoded.len(), advance);
+
+ let mut encoded_copy = encoded;
+ let roundtrip_value =
+ decode_varint_slow(&mut encoded_copy).expect("slow decoding failed");
+ assert_eq!(value, roundtrip_value);
+ }
+
+ check(2u64.pow(0) - 1, &[0x00]);
+ check(2u64.pow(0), &[0x01]);
+
+ check(2u64.pow(7) - 1, &[0x7F]);
+ check(2u64.pow(7), &[0x80, 0x01]);
+ check(300, &[0xAC, 0x02]);
+
+ check(2u64.pow(14) - 1, &[0xFF, 0x7F]);
+ check(2u64.pow(14), &[0x80, 0x80, 0x01]);
+
+ check(2u64.pow(21) - 1, &[0xFF, 0xFF, 0x7F]);
+ check(2u64.pow(21), &[0x80, 0x80, 0x80, 0x01]);
+
+ check(2u64.pow(28) - 1, &[0xFF, 0xFF, 0xFF, 0x7F]);
+ check(2u64.pow(28), &[0x80, 0x80, 0x80, 0x80, 0x01]);
+
+ check(2u64.pow(35) - 1, &[0xFF, 0xFF, 0xFF, 0xFF, 0x7F]);
+ check(2u64.pow(35), &[0x80, 0x80, 0x80, 0x80, 0x80, 0x01]);
+
+ check(2u64.pow(42) - 1, &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F]);
+ check(2u64.pow(42), &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01]);
+
+ check(
+ 2u64.pow(49) - 1,
+ &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F],
+ );
+ check(
+ 2u64.pow(49),
+ &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01],
+ );
+
+ check(
+ 2u64.pow(56) - 1,
+ &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F],
+ );
+ check(
+ 2u64.pow(56),
+ &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01],
+ );
+
+ check(
+ 2u64.pow(63) - 1,
+ &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F],
+ );
+ check(
+ 2u64.pow(63),
+ &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01],
+ );
+
+ check(
+ u64::MAX,
+ &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01],
+ );
+ }
+
+ const U64_MAX_PLUS_ONE: &[u8] = &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02];
+
+ #[test]
+ fn varint_overflow() {
+ let mut copy = U64_MAX_PLUS_ONE;
+ decode_varint(&mut copy).expect_err("decoding u64::MAX + 1 succeeded");
+ }
+
+ #[test]
+ fn variant_slow_overflow() {
+ let mut copy = U64_MAX_PLUS_ONE;
+ decode_varint_slow(&mut copy).expect_err("slow decoding u64::MAX + 1 succeeded");
+ }
+}
### external/vendor/prost/src/encoding/wire_type.rs
@@ -0,0 +1,42 @@
+use crate::{error::DecodeErrorKind, DecodeError};
+
+/// Represent the wire type for protobuf encoding.
+///
+/// The integer value is equvilant with the encoded value.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum WireType {
+ Varint = 0,
+ SixtyFourBit = 1,
+ LengthDelimited = 2,
+ StartGroup = 3,
+ EndGroup = 4,
+ ThirtyTwoBit = 5,
+}
+
+impl TryFrom<u64> for WireType {
+ type Error = DecodeError;
+
+ #[inline]
+ fn try_from(value: u64) -> Result<Self, Self::Error> {
+ match value {
+ 0 => Ok(WireType::Varint),
+ 1 => Ok(WireType::SixtyFourBit),
+ 2 => Ok(WireType::LengthDelimited),
+ 3 => Ok(WireType::StartGroup),
+ 4 => Ok(WireType::EndGroup),
+ 5 => Ok(WireType::ThirtyTwoBit),
+ _ => Err(DecodeErrorKind::InvalidWireType { value }.into()),
+ }
+ }
+}
+
+/// Checks that the expected wire type matches the actual wire type,
+/// or returns an error result.
+#[inline]
+pub fn check_wire_type(expected: WireType, actual: WireType) -> Result<(), DecodeError> {
+ if expected != actual {
+ return Err(DecodeErrorKind::UnexpectedWireType { actual, expected }.into());
+ }
+ Ok(())
+}
### external/vendor/prost/src/error.rs
@@ -1,11 +1,13 @@
//! Protobuf encoding and decoding errors.
+use crate::encoding::WireType;
use alloc::borrow::Cow;
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
#[cfg(not(feature = "std"))]
+use alloc::string::String;
+#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
-
use core::fmt;
/// A Protobuf message decoding error.
@@ -21,7 +23,7 @@ pub struct DecodeError {
#[derive(Clone, PartialEq, Eq)]
struct Inner {
/// A 'best effort' root cause description.
- description: Cow<'static, str>,
+ description: DecodeErrorKind,
/// A stack of (message, field) name pairs, which identify the specific
/// message type and field where decoding failed. The stack contains an
/// entry per level of nesting.
@@ -32,15 +34,33 @@ impl DecodeError {
/// Creates a new `DecodeError` with a 'best effort' root cause description.
///
/// Meant to be used only by `Message` implementations.
- #[doc(hidden)]
+ #[deprecated(
+ since = "0.14.2",
+ note = "This function was meant for internal use only. Because of `doc(hidden)` it was publicly available and it is actually used by users. The prost project intents to remove this function in the next breaking release."
+ )]
#[cold]
+ #[doc(hidden)]
pub fn new(description: impl Into<Cow<'static, str>>) -> DecodeError {
- DecodeError {
- inner: Box::new(Inner {
- description: description.into(),
- stack: Vec::new(),
- }),
+ DecodeErrorKind::Other {
+ description: description.into(),
+ }
+ .into()
+ }
+
+ /// Creates a new `DecodeError` with a DecodeErrorKind::UnexpectedTypeUrl.
+ ///
+ /// Must only be used by `prost_types::Any` implementation.
+ #[doc(hidden)]
+ #[cold]
+ pub fn new_unexpected_type_url(
+ actual: impl Into<String>,
+ expected: impl Into<String>,
+ ) -> DecodeError {
+ DecodeErrorKind::UnexpectedTypeUrl {
+ actual: actual.into(),
+ expected: expected.into(),
}
+ .into()
}
/// Pushes a (message, field) name location pair on to the location stack.
@@ -65,14 +85,89 @@ impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("failed to decode Protobuf message: ")?;
for &(message, field) in &self.inner.stack {
- write!(f, "{}.{}: ", message, field)?;
+ write!(f, "{message}.{field}: ")?;
}
- f.write_str(&self.inner.description)
+ write!(f, "{}", self.inner.description)
}
}
-#[cfg(feature = "std")]
-impl std::error::Error for DecodeError {}
+impl From<DecodeErrorKind> for DecodeError {
+ fn from(description: DecodeErrorKind) -> Self {
+ DecodeError {
+ inner: Box::new(Inner {
+ description,
+ stack: Vec::new(),
+ }),
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum DecodeErrorKind {
+ /// Length delimiter exceeds maximum usize value
+ LengthDelimiterTooLarge,
+ /// Invalid varint
+ InvalidVarint,
+ #[cfg(not(feature = "no-recursion-limit"))]
+ /// Recursion limit reached
+ RecursionLimitReached,
+ /// Invalid wire type value
+ InvalidWireType { value: u64 },
+ /// Invalid key value
+ InvalidKey { key: u64 },
+ /// Invalid tag value: 0
+ InvalidTag,
+ /// Invalid wire type
+ UnexpectedWireType {
+ actual: WireType,
+ expected: WireType,
+ },
+ /// Buffer underflow
+ BufferUnderflow,
+ /// Delimited length exceeded
+ DelimitedLengthExceeded,
+ /// Unexpected end group tag
+ UnexpectedEndGroupTag,
+ /// Invalid string value: data is not UTF-8 encoded
+ InvalidString,
+ /// Unexpected type URL
+ UnexpectedTypeUrl { actual: String, expected: String },
+ /// A textual description of a problem
+ Other { description: Cow<'static, str> },
+}
+
+impl fmt::Display for DecodeErrorKind {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::LengthDelimiterTooLarge => {
+ write!(f, "length delimiter exceeds maximum usize value")
+ }
+ Self::InvalidVarint => write!(f, "invalid varint"),
+ #[cfg(not(feature = "no-recursion-limit"))]
+ Self::RecursionLimitReached => write!(f, "recursion limit reached"),
+ Self::InvalidWireType { value } => write!(f, "invalid wire type value: {value}"),
+ Self::InvalidKey { key } => write!(f, "invalid key value: {key}"),
+ Self::InvalidTag => write!(f, "invalid tag value: 0"),
+ Self::UnexpectedWireType { actual, expected } => {
+ write!(f, "invalid wire type: {actual:?} (expected {expected:?})")
+ }
+ Self::BufferUnderflow => write!(f, "buffer underflow"),
+ Self::DelimitedLengthExceeded => write!(f, "delimited length exceeded"),
+ Self::UnexpectedEndGroupTag => write!(f, "unexpected end group tag"),
+ Self::InvalidString => {
+ write!(f, "invalid string value: data is not UTF-8 encoded")
+ }
+ Self::UnexpectedTypeUrl { actual, expected } => {
+ write!(f, "unexpected type URL.type_url: expected type URL: \"{expected}\" (got: \"{actual}\")")
+ }
+ Self::Other { description } => {
+ write!(f, "{description}")
+ }
+ }
+ }
+}
+
+impl core::error::Error for DecodeError {}
#[cfg(feature = "std")]
impl From<DecodeError> for std::io::Error {
@@ -122,8 +217,7 @@ impl fmt::Display for EncodeError {
}
}
-#[cfg(feature = "std")]
-impl std::error::Error for EncodeError {}
+impl core::error::Error for EncodeError {}
#[cfg(feature = "std")]
impl From<EncodeError> for std::io::Error {
@@ -146,5 +240,34 @@ impl fmt::Display for UnknownEnumValue {
}
}
-#[cfg(feature = "std")]
-impl std::error::Error for UnknownEnumValue {}
+impl core::error::Error for UnknownEnumValue {}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn test_push() {
+ let mut decode_error = DecodeError::from(DecodeErrorKind::InvalidVarint);
+ decode_error.push("Foo bad", "bar.foo");
+ decode_error.push("Baz bad", "bar.baz");
+
+ assert_eq!(
+ decode_error.to_string(),
+ "failed to decode Protobuf message: Foo bad.bar.foo: Baz bad.bar.baz: invalid varint"
+ );
+ }
+
+ #[cfg(feature = "std")]
+ #[test]
+ fn test_into_std_io_error() {
+ let decode_error = DecodeError::from(DecodeErrorKind::InvalidVarint);
+ let std_io_error = std::io::Error::from(decode_error);
+
+ assert_eq!(std_io_error.kind(), std::io::ErrorKind::InvalidData);
+ assert_eq!(
+ std_io_error.to_string(),
+ "failed to decode Protobuf message: invalid varint"
+ );
+ }
+}
### external/vendor/prost/src/lib.rs
@@ -1,4 +1,4 @@
-#![doc(html_root_url = "https://docs.rs/prost/0.13.1")]
+#![doc(html_root_url = "https://docs.rs/prost/0.14.4")]
#![cfg_attr(not(feature = "std"), no_std)]
#![doc = include_str!("../README.md")]
@@ -17,65 +17,18 @@ mod types;
#[doc(hidden)]
pub mod encoding;
+pub use crate::encoding::length_delimiter::{
+ decode_length_delimiter, encode_length_delimiter, length_delimiter_len,
+};
pub use crate::error::{DecodeError, EncodeError, UnknownEnumValue};
pub use crate::message::Message;
pub use crate::name::Name;
-use bytes::{Buf, BufMut};
-
-use crate::encoding::{decode_varint, encode_varint, encoded_len_varint};
-
// See `encoding::DecodeContext` for more info.
// 100 is the default recursion limit in the C++ implementation.
#[cfg(not(feature = "no-recursion-limit"))]
const RECURSION_LIMIT: u32 = 100;
-/// Encodes a length delimiter to the buffer.
-///
-/// See [Message.encode_length_delimited] for more info.
-///
-/// An error will be returned if the buffer does not have sufficient capacity to encode the
-/// delimiter.
-pub fn encode_length_delimiter(length: usize, buf: &mut impl BufMut) -> Result<(), EncodeError> {
- let length = length as u64;
- let required = encoded_len_varint(length);
- let remaining = buf.remaining_mut();
- if required > remaining {
- return Err(EncodeError::new(required, remaining));
- }
- encode_varint(length, buf);
- Ok(())
-}
-
-/// Returns the encoded length of a length delimiter.
-///
-/// Applications may use this method to ensure sufficient buffer capacity before calling
-/// `encode_length_delimiter`. The returned size will be between 1 and 10, inclusive.
-pub fn length_delimiter_len(length: usize) -> usize {
- encoded_len_varint(length as u64)
-}
-
-/// Decodes a length delimiter from the buffer.
-///
-/// This method allows the length delimiter to be decoded independently of the message, when the
-/// message is encoded with [Message.encode_length_delimited].
-///
-/// An error may be returned in two cases:
-///
-/// * If the supplied buffer contains fewer than 10 bytes, then an error indicates that more
-/// input is required to decode the full delimiter.
-/// * If the supplied buffer contains more than 10 bytes, then the buffer contains an invalid
-/// delimiter, and typically the buffer should be considered corrupt.
-pub fn decode_length_delimiter(mut buf: impl Buf) -> Result<usize, DecodeError> {
- let length = decode_varint(&mut buf)?;
- if length > usize::max_value() as u64 {
- return Err(DecodeError::new(
- "length delimiter exceeds maximum usize value",
- ));
- }
- Ok(length as usize)
-}
-
// Re-export #[derive(Message, Enumeration, Oneof)].
// Based on serde's equivalent re-export [1], but enabled by default.
//
### external/vendor/prost/src/message.rs
@@ -3,18 +3,16 @@ use alloc::boxed::Box;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
-use core::fmt::Debug;
-
use bytes::{Buf, BufMut};
-use crate::encoding::{
- decode_key, encode_varint, encoded_len_varint, message, DecodeContext, WireType,
-};
+use crate::encoding::varint::{encode_varint, encoded_len_varint};
+use crate::encoding::wire_type::WireType;
+use crate::encoding::{decode_key, message, DecodeContext};
use crate::DecodeError;
use crate::EncodeError;
/// A Protocol Buffers message.
-pub trait Message: Debug + Send + Sync {
+pub trait Message: Send + Sync {
/// Encodes the message to a buffer.
///
/// This method will panic if the buffer has insufficient capacity.
### external/vendor/prost/src/name.rs
@@ -21,7 +21,11 @@ pub trait Name: Message {
/// By default, this is the package name followed by the message name.
/// Fully-qualified names must be unique within a domain of Type URLs.
fn full_name() -> String {
- format!("{}.{}", Self::PACKAGE, Self::NAME)
+ if Self::PACKAGE.is_empty() {
+ Self::NAME.into()
+ } else {
+ format!("{}.{}", Self::PACKAGE, Self::NAME)
+ }
}
/// Type URL for this [`Message`], which by default is the full name with a
### external/vendor/prost/src/types.rs
@@ -5,19 +5,18 @@
//! the `prost-types` crate in order to avoid a cyclic dependency between `prost` and
//! `prost-build`.
-#[cfg(not(feature = "std"))]
+use alloc::format;
use alloc::string::String;
-#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use ::bytes::{Buf, BufMut, Bytes};
+use crate::encoding::wire_type::WireType;
use crate::{
encoding::{
- bool, bytes, double, float, int32, int64, skip_field, string, uint32, uint64,
- DecodeContext, WireType,
+ bool, bytes, double, float, int32, int64, skip_field, string, uint32, uint64, DecodeContext,
},
- DecodeError, Message,
+ DecodeError, Message, Name,
};
/// `google.protobuf.BoolValue`
@@ -52,6 +51,16 @@ impl Message for bool {
}
}
+/// `google.protobuf.BoolValue`
+impl Name for bool {
+ const NAME: &'static str = "BoolValue";
+ const PACKAGE: &'static str = "google.protobuf";
+
+ fn type_url() -> String {
+ googleapis_type_url_for::<Self>()
+ }
+}
+
/// `google.protobuf.UInt32Value`
impl Message for u32 {
fn encode_raw(&self, buf: &mut impl BufMut) {
@@ -84,6 +93,16 @@ impl Message for u32 {
}
}
+/// `google.protobuf.UInt32Value`
+impl Name for u32 {
+ const NAME: &'static str = "UInt32Value";
+ const PACKAGE: &'static str = "google.protobuf";
+
+ fn type_url() -> String {
+ googleapis_type_url_for::<Self>()
+ }
+}
+
/// `google.protobuf.UInt64Value`
impl Message for u64 {
fn encode_raw(&self, buf: &mut impl BufMut) {
@@ -116,6 +135,16 @@ impl Message for u64 {
}
}
+/// `google.protobuf.UInt64Value`
+impl Name for u64 {
+ const NAME: &'static str = "UInt64Value";
+ const PACKAGE: &'static str = "google.protobuf";
+
+ fn type_url() -> String {
+ googleapis_type_url_for::<Self>()
+ }
+}
+
/// `google.protobuf.Int32Value`
impl Message for i32 {
fn encode_raw(&self, buf: &mut impl BufMut) {
@@ -148,6 +177,16 @@ impl Message for i32 {
}
}
+/// `google.protobuf.Int32Value`
+impl Name for i32 {
+ const NAME: &'static str = "Int32Value";
+ const PACKAGE: &'static str = "google.protobuf";
+
+ fn type_url() -> String {
+ googleapis_type_url_for::<Self>()
+ }
+}
+
/// `google.protobuf.Int64Value`
impl Message for i64 {
fn encode_raw(&self, buf: &mut impl BufMut) {
@@ -180,6 +219,16 @@ impl Message for i64 {
}
}
+/// `google.protobuf.Int64Value`
+impl Name for i64 {
+ const NAME: &'static str = "Int64Value";
+ const PACKAGE: &'static str = "google.protobuf";
+
+ fn type_url() -> String {
+ googleapis_type_url_for::<Self>()
+ }
+}
+
/// `google.protobuf.FloatValue`
impl Message for f32 {
fn encode_raw(&self, buf: &mut impl BufMut) {
@@ -212,6 +261,16 @@ impl Message for f32 {
}
}
+/// `google.protobuf.FloatValue`
+impl Name for f32 {
+ const NAME: &'static str = "FloatValue";
+ const PACKAGE: &'static str = "google.protobuf";
+
+ fn type_url() -> String {
+ googleapis_type_url_for::<Self>()
+ }
+}
+
/// `google.protobuf.DoubleValue`
impl Message for f64 {
fn encode_raw(&self, buf: &mut impl BufMut) {
@@ -244,6 +303,16 @@ impl Message for f64 {
}
}
+/// `google.protobuf.DoubleValue`
+impl Name for f64 {
+ const NAME: &'static str = "DoubleValue";
+ const PACKAGE: &'static str = "google.protobuf";
+
+ fn type_url() -> String {
+ googleapis_type_url_for::<Self>()
+ }
+}
+
/// `google.protobuf.StringValue`
impl Message for String {
fn encode_raw(&self, buf: &mut impl BufMut) {
@@ -276,6 +345,16 @@ impl Message for String {
}
}
+/// `google.protobuf.StringValue`
+impl Name for String {
+ const NAME: &'static str = "StringValue";
+ const PACKAGE: &'static str = "google.protobuf";
+
+ fn type_url() -> String {
+ googleapis_type_url_for::<Self>()
+ }
+}
+
/// `google.protobuf.BytesValue`
impl Message for Vec<u8> {
fn encode_raw(&self, buf: &mut impl BufMut) {
@@ -308,6 +387,16 @@ impl Message for Vec<u8> {
}
}
+/// `google.protobuf.BytesValue`
+impl Name for Vec<u8> {
+ const NAME: &'static str = "BytesValue";
+ const PACKAGE: &'static str = "google.protobuf";
+
+ fn type_url() -> String {
+ googleapis_type_url_for::<Self>()
+ }
+}
+
/// `google.protobuf.BytesValue`
impl Message for Bytes {
fn encode_raw(&self, buf: &mut impl BufMut) {
@@ -340,6 +429,16 @@ impl Message for Bytes {
}
}
+/// `google.protobuf.BytesValue`
+impl Name for Bytes {
+ const NAME: &'static str = "BytesValue";
+ const PACKAGE: &'static str = "google.protobuf";
+
+ fn type_url() -> String {
+ googleapis_type_url_for::<Self>()
+ }
+}
+
/// `google.protobuf.Empty`
impl Message for () {
fn encode_raw(&self, _buf: &mut impl BufMut) {}
@@ -357,3 +456,115 @@ impl Message for () {
}
fn clear(&mut self) {}
}
+
+/// `google.protobuf.Empty`
+impl Name for () {
+ const NAME: &'static str = "Empty";
+ const PACKAGE: &'static str = "google.protobuf";
+
+ fn type_url() -> String {
+ googleapis_type_url_for::<Self>()
+ }
+}
+
+/// Compute the type URL for the given `google.protobuf` type, using `type.googleapis.com` as the
+/// authority for the URL.
+fn googleapis_type_url_for<T: Name>() -> String {
+ format!("type.googleapis.com/{}.{}", T::PACKAGE, T::NAME)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_impl_name() {
+ assert_eq!("BoolValue", bool::NAME);
+ assert_eq!("google.protobuf", bool::PACKAGE);
+ assert_eq!("google.protobuf.BoolValue", bool::full_name());
+ assert_eq!(
+ "type.googleapis.com/google.protobuf.BoolValue",
+ bool::type_url()
+ );
+
+ assert_eq!("UInt32Value", u32::NAME);
+ assert_eq!("google.protobuf", u32::PACKAGE);
+ assert_eq!("google.protobuf.UInt32Value", u32::full_name());
+ assert_eq!(
+ "type.googleapis.com/google.protobuf.UInt32Value",
+ u32::type_url()
+ );
+
+ assert_eq!("UInt64Value", u64::NAME);
+ assert_eq!("google.protobuf", u64::PACKAGE);
+ assert_eq!("google.protobuf.UInt64Value", u64::full_name());
+ assert_eq!(
+ "type.googleapis.com/google.protobuf.UInt64Value",
+ u64::type_url()
+ );
+
+ assert_eq!("Int32Value", i32::NAME);
+ assert_eq!("google.protobuf", i32::PACKAGE);
+ assert_eq!("google.protobuf.Int32Value", i32::full_name());
+ assert_eq!(
+ "type.googleapis.com/google.protobuf.Int32Value",
+ i32::type_url()
+ );
+
+ assert_eq!("Int64Value", i64::NAME);
+ assert_eq!("google.protobuf", i64::PACKAGE);
+ assert_eq!("google.protobuf.Int64Value", i64::full_name());
+ assert_eq!(
+ "type.googleapis.com/google.protobuf.Int64Value",
+ i64::type_url()
+ );
+
+ assert_eq!("FloatValue", f32::NAME);
+ assert_eq!("google.protobuf", f32::PACKAGE);
+ assert_eq!("google.protobuf.FloatValue", f32::full_name());
+ assert_eq!(
+ "type.googleapis.com/google.protobuf.FloatValue",
+ f32::type_url()
+ );
+
+ assert_eq!("DoubleValue", f64::NAME);
+ assert_eq!("google.protobuf", f64::PACKAGE);
+ assert_eq!("google.protobuf.DoubleValue", f64::full_name());
+ assert_eq!(
+ "type.googleapis.com/google.protobuf.DoubleValue",
+ f64::type_url()
+ );
+
+ assert_eq!("StringValue", String::NAME);
+ assert_eq!("google.protobuf", String::PACKAGE);
+ assert_eq!("google.protobuf.StringValue", String::full_name());
+ assert_eq!(
+ "type.googleapis.com/google.protobuf.StringValue",
+ String::type_url()
+ );
+
+ assert_eq!("BytesValue", Vec::<u8>::NAME);
+ assert_eq!("google.protobuf", Vec::<u8>::PACKAGE);
+ assert_eq!("google.protobuf.BytesValue", Vec::<u8>::full_name());
+ assert_eq!(
+ "type.googleapis.com/google.protobuf.BytesValue",
+ Vec::<u8>::type_url()
+ );
+
+ assert_eq!("BytesValue", Bytes::NAME);
+ assert_eq!("google.protobuf", Bytes::PACKAGE);
+ assert_eq!("google.protobuf.BytesValue", Bytes::full_name());
+ assert_eq!(
+ "type.googleapis.com/google.protobuf.BytesValue",
+ Bytes::type_url()
+ );
+
+ assert_eq!("Empty", <()>::NAME);
+ assert_eq!("google.protobuf", <()>::PACKAGE);
+ assert_eq!("google.protobuf.Empty", <()>::full_name());
+ assert_eq!(
+ "type.googleapis.com/google.protobuf.Empty",
+ <()>::type_url()
+ );
+ }
+}
### src/rust/Cargo.lock
@@ -1279,19 +1279,19 @@ dependencies = [
[[package]]
name = "prost"
-version = "0.13.1"
+version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e13db3d3fde688c61e2446b4d843bc27a7e8af269a69440c0308021dc92333cc"
+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
dependencies = [
"bytes",
"prost-derive",
]
[[package]]
name = "prost-derive"
-version = "0.13.1"
+version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "18bec9b0adc4eba778b33684b7ba3e7137789434769ee3ce3930463ef904cfca"
+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
dependencies = [
"anyhow",
"itertools",
### src/rust/bitbox-proto/Cargo.toml
@@ -10,7 +10,7 @@ license = "Apache-2.0"
[dependencies.prost]
# keep version in sync with tools/prost-build-proto/Cargo.toml and src/rust/bitbox02-rust/Cargo.toml.
-version = "0.13.1"
+version = "0.14.4"
default-features = false
features = ["derive"]
### src/rust/bitbox-proto/src/generated/shiftcrypto.bitbox02.backups.rs
@@ -1,6 +1,5 @@
// This file is @generated by prost-build.
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BackupMetaData {
#[prost(uint32, tag = "1")]
pub timestamp: u32,
@@ -13,8 +12,7 @@ pub struct BackupMetaData {
/// BackupData is the plaintext data message of BackupContent.
/// Defining it as a protobuf message allows language/architecture independent
/// encoding/decoding.
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BackupData {
#[prost(uint32, tag = "1")]
pub seed_length: u32,
@@ -25,8 +23,7 @@ pub struct BackupData {
#[prost(string, tag = "4")]
pub generator: ::prost::alloc::string::String,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BackupContent {
#[prost(bytes = "vec", tag = "1")]
pub checksum: ::prost::alloc::vec::Vec<u8>,
@@ -47,22 +44,19 @@ pub struct BackupContent {
#[prost(message, optional, tag = "4")]
pub data: ::core::option::Option<BackupData>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BackupV1 {
#[prost(message, optional, tag = "1")]
pub content: ::core::option::Option<BackupContent>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct Backup {
#[prost(oneof = "backup::BackupVersion", tags = "1")]
pub backup_version: ::core::option::Option<backup::BackupVersion>,
}
/// Nested message and enum types in `Backup`.
pub mod backup {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Oneof)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Oneof)]
pub enum BackupVersion {
/// Backup_V2 backup_V2 = 2;
#[prost(message, tag = "1")]
@@ -81,7 +75,7 @@ impl BackupMode {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- BackupMode::Plaintext => "PLAINTEXT",
+ Self::Plaintext => "PLAINTEXT",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
### src/rust/bitbox-proto/src/generated/shiftcrypto.bitbox02.rs
@@ -1,29 +1,24 @@
// This file is @generated by prost-build.
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct PubResponse {
#[prost(string, tag = "1")]
pub r#pub: ::prost::alloc::string::String,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct PubsResponse {
#[prost(string, repeated, tag = "1")]
pub pubs: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct RootFingerprintRequest {}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct RootFingerprintResponse {
#[prost(bytes = "vec", tag = "1")]
pub fingerprint: ::prost::alloc::vec::Vec<u8>,
}
/// See <https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki.>
/// version field dropped as it will set dynamically based on the context (xpub, ypub, etc.).
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct XPub {
#[prost(bytes = "vec", tag = "1")]
pub depth: ::prost::alloc::vec::Vec<u8>,
@@ -37,14 +32,12 @@ pub struct XPub {
pub public_key: ::prost::alloc::vec::Vec<u8>,
}
/// This message exists for use in oneof or repeated fields, where one can't inline `repeated uint32` due to protobuf rules.
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct Keypath {
#[prost(uint32, repeated, tag = "1")]
pub keypath: ::prost::alloc::vec::Vec<u32>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct KeyOriginInfo {
#[prost(bytes = "vec", tag = "1")]
pub root_fingerprint: ::prost::alloc::vec::Vec<u8>,
@@ -53,32 +46,27 @@ pub struct KeyOriginInfo {
#[prost(message, optional, tag = "3")]
pub xpub: ::core::option::Option<XPub>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct CheckBackupRequest {
#[prost(bool, tag = "1")]
pub silent: bool,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct CheckBackupResponse {
#[prost(string, tag = "1")]
pub id: ::prost::alloc::string::String,
}
/// Timestamp must be in UTC
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct CreateBackupRequest {
#[prost(uint32, tag = "1")]
pub timestamp: u32,
#[prost(int32, tag = "2")]
pub timezone_offset: i32,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct ListBackupsRequest {}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BackupInfo {
#[prost(string, tag = "1")]
pub id: ::prost::alloc::string::String,
@@ -88,14 +76,12 @@ pub struct BackupInfo {
#[prost(string, tag = "4")]
pub name: ::prost::alloc::string::String,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ListBackupsResponse {
#[prost(message, repeated, tag = "1")]
pub info: ::prost::alloc::vec::Vec<BackupInfo>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct RestoreBackupRequest {
#[prost(string, tag = "1")]
pub id: ::prost::alloc::string::String,
@@ -104,20 +90,16 @@ pub struct RestoreBackupRequest {
#[prost(int32, tag = "3")]
pub timezone_offset: i32,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct CheckSdCardRequest {}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct CheckSdCardResponse {
#[prost(bool, tag = "1")]
pub inserted: bool,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct DeviceInfoRequest {}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct DeviceInfoResponse {
#[prost(string, tag = "1")]
pub name: ::prost::alloc::string::String,
@@ -145,8 +127,7 @@ pub struct DeviceInfoResponse {
}
/// Nested message and enum types in `DeviceInfoResponse`.
pub mod device_info_response {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct Bluetooth {
/// Hash of the currently active Bluetooth firmware on the device.
#[prost(bytes = "vec", tag = "1")]
@@ -159,8 +140,7 @@ pub mod device_info_response {
pub enabled: bool,
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct InsertRemoveSdCardRequest {
#[prost(enumeration = "insert_remove_sd_card_request::SdCardAction", tag = "1")]
pub action: i32,
@@ -180,8 +160,8 @@ pub mod insert_remove_sd_card_request {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- SdCardAction::RemoveCard => "REMOVE_CARD",
- SdCardAction::InsertCard => "INSERT_CARD",
+ Self::RemoveCard => "REMOVE_CARD",
+ Self::InsertCard => "INSERT_CARD",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -194,61 +174,50 @@ pub mod insert_remove_sd_card_request {
}
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct ResetRequest {}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct SetDeviceLanguageRequest {
#[prost(string, tag = "1")]
pub language: ::prost::alloc::string::String,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct SetDeviceNameRequest {
#[prost(string, tag = "1")]
pub name: ::prost::alloc::string::String,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct SetPasswordRequest {
#[prost(bytes = "vec", tag = "1")]
pub entropy: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct ChangePasswordRequest {}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncIdentityRequest {}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncIdentityResponse {
#[prost(bytes = "vec", tag = "1")]
pub auth_public_key: ::prost::alloc::vec::Vec<u8>,
#[prost(bytes = "vec", tag = "2")]
pub wrap_public_key: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncSignLoginIntentRequest {
#[prost(bytes = "vec", tag = "1")]
pub challenge: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncSignRefreshIntentRequest {
#[prost(bytes = "vec", tag = "1")]
pub challenge: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncSignRevokeAllTokensIntentRequest {
#[prost(bytes = "vec", tag = "1")]
pub challenge: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncSignCreateNamespaceInviteIntentRequest {
#[prost(bytes = "vec", tag = "1")]
pub challenge: ::prost::alloc::vec::Vec<u8>,
@@ -263,8 +232,7 @@ pub struct BitBoxSyncSignCreateNamespaceInviteIntentRequest {
#[prost(uint32, tag = "6")]
pub max_accepted: u32,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncSignJoinRequestIntentRequest {
#[prost(bytes = "vec", tag = "1")]
pub namespace_id: ::prost::alloc::vec::Vec<u8>,
@@ -275,36 +243,31 @@ pub struct BitBoxSyncSignJoinRequestIntentRequest {
#[prost(uint64, tag = "4")]
pub expires_at: u64,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncUnwrapNamespaceDekRequest {
#[prost(bytes = "vec", tag = "1")]
pub namespace_id: ::prost::alloc::vec::Vec<u8>,
#[prost(bytes = "vec", tag = "2")]
pub wrapped_dek: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncSignatureResponse {
#[prost(bytes = "vec", tag = "1")]
pub signature: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncUnwrapNamespaceDekResponse {
#[prost(bytes = "vec", tag = "1")]
pub namespace_dek: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncRequest {
#[prost(oneof = "bit_box_sync_request::Request", tags = "1, 2, 3, 4, 5, 6, 7")]
pub request: ::core::option::Option<bit_box_sync_request::Request>,
}
/// Nested message and enum types in `BitBoxSyncRequest`.
pub mod bit_box_sync_request {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Oneof)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Oneof)]
pub enum Request {
#[prost(message, tag = "1")]
Identity(super::BitBoxSyncIdentityRequest),
@@ -322,16 +285,14 @@ pub mod bit_box_sync_request {
UnwrapNamespaceDek(super::BitBoxSyncUnwrapNamespaceDekRequest),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BitBoxSyncResponse {
#[prost(oneof = "bit_box_sync_response::Response", tags = "1, 2, 3")]
pub response: ::core::option::Option<bit_box_sync_response::Response>,
}
/// Nested message and enum types in `BitBoxSyncResponse`.
pub mod bit_box_sync_response {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Oneof)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Oneof)]
pub enum Response {
#[prost(message, tag = "1")]
Identity(super::BitBoxSyncIdentityResponse),
@@ -341,42 +302,35 @@ pub mod bit_box_sync_response {
UnwrapNamespaceDek(super::BitBoxSyncUnwrapNamespaceDekResponse),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BluetoothToggleEnabledRequest {}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BluetoothUpgradeInitRequest {
#[prost(uint32, tag = "1")]
pub firmware_length: u32,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BluetoothChunkRequest {
#[prost(bytes = "vec", tag = "1")]
pub data: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BluetoothSuccess {}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BluetoothRequestChunkResponse {
#[prost(uint32, tag = "1")]
pub offset: u32,
#[prost(uint32, tag = "2")]
pub length: u32,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BluetoothRequest {
#[prost(oneof = "bluetooth_request::Request", tags = "1, 2, 3")]
pub request: ::core::option::Option<bluetooth_request::Request>,
}
/// Nested message and enum types in `BluetoothRequest`.
pub mod bluetooth_request {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Oneof)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Oneof)]
pub enum Request {
#[prost(message, tag = "1")]
UpgradeInit(super::BluetoothUpgradeInitRequest),
@@ -386,50 +340,43 @@ pub mod bluetooth_request {
ToggleEnabled(super::BluetoothToggleEnabledRequest),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BluetoothResponse {
#[prost(oneof = "bluetooth_response::Response", tags = "1, 2")]
pub response: ::core::option::Option<bluetooth_response::Response>,
}
/// Nested message and enum types in `BluetoothResponse`.
pub mod bluetooth_response {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, Copy, PartialEq, ::prost::Oneof)]
+ #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Oneof)]
pub enum Response {
#[prost(message, tag = "1")]
Success(super::BluetoothSuccess),
#[prost(message, tag = "2")]
RequestChunk(super::BluetoothRequestChunkResponse),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct AntiKleptoHostNonceCommitment {
#[prost(bytes = "vec", tag = "1")]
pub commitment: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct AntiKleptoSignerCommitment {
#[prost(bytes = "vec", tag = "1")]
pub commitment: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct AntiKleptoSignatureRequest {
#[prost(bytes = "vec", tag = "1")]
pub host_nonce: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcScriptConfig {
#[prost(oneof = "btc_script_config::Config", tags = "1, 2, 3")]
pub config: ::core::option::Option<btc_script_config::Config>,
}
/// Nested message and enum types in `BTCScriptConfig`.
pub mod btc_script_config {
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Multisig {
#[prost(uint32, tag = "1")]
@@ -464,8 +411,8 @@ pub mod btc_script_config {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- ScriptType::P2wsh => "P2WSH",
- ScriptType::P2wshP2sh => "P2WSH_P2SH",
+ Self::P2wsh => "P2WSH",
+ Self::P2wshP2sh => "P2WSH_P2SH",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -480,7 +427,6 @@ pub mod btc_script_config {
}
/// A policy as specified by 'Wallet policies':
/// <https://github.com/bitcoin/bips/pull/1389>
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Policy {
#[prost(string, tag = "1")]
@@ -503,9 +449,9 @@ pub mod btc_script_config {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- SimpleType::P2wpkhP2sh => "P2WPKH_P2SH",
- SimpleType::P2wpkh => "P2WPKH",
- SimpleType::P2tr => "P2TR",
+ Self::P2wpkhP2sh => "P2WPKH_P2SH",
+ Self::P2wpkh => "P2WPKH",
+ Self::P2tr => "P2TR",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -518,7 +464,6 @@ pub mod btc_script_config {
}
}
}
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Config {
#[prost(enumeration = "SimpleType", tag = "1")]
@@ -529,7 +474,6 @@ pub mod btc_script_config {
Policy(Policy),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcPubRequest {
#[prost(enumeration = "BtcCoin", tag = "1")]
@@ -570,16 +514,16 @@ pub mod btc_pub_request {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- XPubType::Tpub => "TPUB",
- XPubType::Xpub => "XPUB",
- XPubType::Ypub => "YPUB",
- XPubType::Zpub => "ZPUB",
- XPubType::Vpub => "VPUB",
- XPubType::Upub => "UPUB",
- XPubType::CapitalVpub => "CAPITAL_VPUB",
- XPubType::CapitalZpub => "CAPITAL_ZPUB",
- XPubType::CapitalUpub => "CAPITAL_UPUB",
- XPubType::CapitalYpub => "CAPITAL_YPUB",
+ Self::Tpub => "TPUB",
+ Self::Xpub => "XPUB",
+ Self::Ypub => "YPUB",
+ Self::Zpub => "ZPUB",
+ Self::Vpub => "VPUB",
+ Self::Upub => "UPUB",
+ Self::CapitalVpub => "CAPITAL_VPUB",
+ Self::CapitalZpub => "CAPITAL_ZPUB",
+ Self::CapitalUpub => "CAPITAL_UPUB",
+ Self::CapitalYpub => "CAPITAL_YPUB",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -599,7 +543,6 @@ pub mod btc_pub_request {
}
}
}
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Output {
#[prost(enumeration = "XPubType", tag = "3")]
@@ -608,7 +551,6 @@ pub mod btc_pub_request {
ScriptConfig(super::BtcScriptConfig),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcXpubsRequest {
#[prost(enumeration = "BtcCoin", tag = "1")]
@@ -634,9 +576,9 @@ pub mod btc_xpubs_request {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- XPubType::Unknown => "UNKNOWN",
- XPubType::Xpub => "XPUB",
- XPubType::Tpub => "TPUB",
+ Self::Unknown => "UNKNOWN",
+ Self::Xpub => "XPUB",
+ Self::Tpub => "TPUB",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -650,15 +592,13 @@ pub mod btc_xpubs_request {
}
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcScriptConfigWithKeypath {
#[prost(message, optional, tag = "2")]
pub script_config: ::core::option::Option<BtcScriptConfig>,
#[prost(uint32, repeated, tag = "3")]
pub keypath: ::prost::alloc::vec::Vec<u32>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcSignInitRequest {
#[prost(enumeration = "BtcCoin", tag = "1")]
@@ -702,8 +642,8 @@ pub mod btc_sign_init_request {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- FormatUnit::Default => "DEFAULT",
- FormatUnit::Sat => "SAT",
+ Self::Default => "DEFAULT",
+ Self::Sat => "SAT",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -716,8 +656,7 @@ pub mod btc_sign_init_request {
}
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BtcSignNextResponse {
#[prost(enumeration = "btc_sign_next_response::Type", tag = "1")]
pub r#type: i32,
@@ -763,14 +702,14 @@ pub mod btc_sign_next_response {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- Type::Input => "INPUT",
- Type::Output => "OUTPUT",
- Type::Done => "DONE",
- Type::PrevtxInit => "PREVTX_INIT",
- Type::PrevtxInput => "PREVTX_INPUT",
- Type::PrevtxOutput => "PREVTX_OUTPUT",
- Type::HostNonce => "HOST_NONCE",
- Type::PaymentRequest => "PAYMENT_REQUEST",
+ Self::Input => "INPUT",
+ Self::Output => "OUTPUT",
+ Self::Done => "DONE",
+ Self::PrevtxInit => "PREVTX_INIT",
+ Self::PrevtxInput => "PREVTX_INPUT",
+ Self::PrevtxOutput => "PREVTX_OUTPUT",
+ Self::HostNonce => "HOST_NONCE",
+ Self::PaymentRequest => "PAYMENT_REQUEST",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -789,8 +728,7 @@ pub mod btc_sign_next_response {
}
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BtcSignInputRequest {
#[prost(bytes = "vec", tag = "1")]
pub prev_out_hash: ::prost::alloc::vec::Vec<u8>,
@@ -812,8 +750,7 @@ pub struct BtcSignInputRequest {
#[prost(message, optional, tag = "8")]
pub host_nonce_commitment: ::core::option::Option<AntiKleptoHostNonceCommitment>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BtcSignOutputRequest {
#[prost(bool, tag = "1")]
pub ours: bool,
@@ -850,14 +787,12 @@ pub struct BtcSignOutputRequest {
/// Nested message and enum types in `BTCSignOutputRequest`.
pub mod btc_sign_output_request {
/// <https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki>
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct SilentPayment {
#[prost(string, tag = "1")]
pub address: ::prost::alloc::string::String,
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcScriptConfigRegistration {
#[prost(enumeration = "BtcCoin", tag = "1")]
@@ -868,22 +803,18 @@ pub struct BtcScriptConfigRegistration {
#[prost(uint32, repeated, tag = "3")]
pub keypath: ::prost::alloc::vec::Vec<u32>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BtcSuccess {}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcIsScriptConfigRegisteredRequest {
#[prost(message, optional, tag = "1")]
pub registration: ::core::option::Option<BtcScriptConfigRegistration>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BtcIsScriptConfigRegisteredResponse {
#[prost(bool, tag = "1")]
pub is_registered: bool,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcRegisterScriptConfigRequest {
#[prost(message, optional, tag = "1")]
@@ -914,8 +845,8 @@ pub mod btc_register_script_config_request {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- XPubType::AutoElectrum => "AUTO_ELECTRUM",
- XPubType::AutoXpubTpub => "AUTO_XPUB_TPUB",
+ Self::AutoElectrum => "AUTO_ELECTRUM",
+ Self::AutoXpubTpub => "AUTO_XPUB_TPUB",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -928,8 +859,7 @@ pub mod btc_register_script_config_request {
}
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BtcPrevTxInitRequest {
#[prost(uint32, tag = "1")]
pub version: u32,
@@ -940,8 +870,7 @@ pub struct BtcPrevTxInitRequest {
#[prost(uint32, tag = "4")]
pub locktime: u32,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BtcPrevTxInputRequest {
#[prost(bytes = "vec", tag = "1")]
pub prev_out_hash: ::prost::alloc::vec::Vec<u8>,
@@ -952,15 +881,13 @@ pub struct BtcPrevTxInputRequest {
#[prost(uint32, tag = "4")]
pub sequence: u32,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BtcPrevTxOutputRequest {
#[prost(uint64, tag = "1")]
pub value: u64,
#[prost(bytes = "vec", tag = "2")]
pub pubkey_script: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcPaymentRequestRequest {
#[prost(string, tag = "1")]
@@ -976,21 +903,18 @@ pub struct BtcPaymentRequestRequest {
}
/// Nested message and enum types in `BTCPaymentRequestRequest`.
pub mod btc_payment_request_request {
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Memo {
#[prost(oneof = "memo::Memo", tags = "1, 2")]
pub memo: ::core::option::Option<memo::Memo>,
}
/// Nested message and enum types in `Memo`.
pub mod memo {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct TextMemo {
#[prost(string, tag = "1")]
pub note: ::prost::alloc::string::String,
}
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CoinPurchaseMemo {
/// SLIP-44 coin type
@@ -1009,22 +933,19 @@ pub mod btc_payment_request_request {
pub mod coin_purchase_memo {
/// Derivation info for verifying address ownership.
/// NOT part of the SLIP-24 sighash.
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct EthAddressDerivation {
/// Keypath to the address
#[prost(uint32, repeated, tag = "1")]
pub keypath: ::prost::alloc::vec::Vec<u32>,
}
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcAddressDerivation {
/// Script config + keypath are needed to derive BTC/LTC-family addresses.
#[prost(message, optional, tag = "1")]
pub script_config:
::core::option::Option<super::super::super::BtcScriptConfigWithKeypath>,
}
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum AddressDerivation {
#[prost(message, tag = "4")]
@@ -1033,7 +954,6 @@ pub mod btc_payment_request_request {
Btc(BtcAddressDerivation),
}
}
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Memo {
#[prost(message, tag = "1")]
@@ -1043,7 +963,6 @@ pub mod btc_payment_request_request {
}
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcSignMessageRequest {
#[prost(enumeration = "BtcCoin", tag = "1")]
@@ -1057,22 +976,19 @@ pub struct BtcSignMessageRequest {
#[prost(message, optional, tag = "4")]
pub host_nonce_commitment: ::core::option::Option<AntiKleptoHostNonceCommitment>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BtcSignMessageResponse {
/// 65 bytes (32 bytes big endian R, 32 bytes big endian S, 1 recid).
#[prost(bytes = "vec", tag = "1")]
pub signature: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BtcRequest {
#[prost(oneof = "btc_request::Request", tags = "1, 2, 3, 4, 5, 6, 7, 8, 9")]
pub request: ::core::option::Option<btc_request::Request>,
}
/// Nested message and enum types in `BTCRequest`.
pub mod btc_request {
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Request {
#[prost(message, tag = "1")]
@@ -1095,16 +1011,14 @@ pub mod btc_request {
Xpubs(super::BtcXpubsRequest),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct BtcResponse {
#[prost(oneof = "btc_response::Response", tags = "1, 2, 3, 4, 5, 6")]
pub response: ::core::option::Option<btc_response::Response>,
}
/// Nested message and enum types in `BTCResponse`.
pub mod btc_response {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Oneof)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Oneof)]
pub enum Response {
#[prost(message, tag = "1")]
Success(super::BtcSuccess),
@@ -1137,11 +1051,11 @@ impl BtcCoin {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- BtcCoin::Btc => "BTC",
- BtcCoin::Tbtc => "TBTC",
- BtcCoin::Ltc => "LTC",
- BtcCoin::Tltc => "TLTC",
- BtcCoin::Rbtc => "RBTC",
+ Self::Btc => "BTC",
+ Self::Tbtc => "TBTC",
+ Self::Ltc => "LTC",
+ Self::Tltc => "TLTC",
+ Self::Rbtc => "RBTC",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -1174,13 +1088,13 @@ impl BtcOutputType {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- BtcOutputType::Unknown => "UNKNOWN",
- BtcOutputType::P2pkh => "P2PKH",
- BtcOutputType::P2sh => "P2SH",
- BtcOutputType::P2wpkh => "P2WPKH",
- BtcOutputType::P2wsh => "P2WSH",
- BtcOutputType::P2tr => "P2TR",
- BtcOutputType::OpReturn => "OP_RETURN",
+ Self::Unknown => "UNKNOWN",
+ Self::P2pkh => "P2PKH",
+ Self::P2sh => "P2SH",
+ Self::P2wpkh => "P2WPKH",
+ Self::P2wsh => "P2WSH",
+ Self::P2tr => "P2TR",
+ Self::OpReturn => "OP_RETURN",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -1197,20 +1111,17 @@ impl BtcOutputType {
}
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CardanoXpubsRequest {
#[prost(message, repeated, tag = "1")]
pub keypaths: ::prost::alloc::vec::Vec<Keypath>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct CardanoXpubsResponse {
#[prost(bytes = "vec", repeated, tag = "1")]
pub xpubs: ::prost::alloc::vec::Vec<::prost::alloc::vec::Vec<u8>>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct CardanoScriptConfig {
/// Entries correspond to address types as described in:
/// <https://github.com/cardano-foundation/CIPs/blob/6c249ef48f8f5b32efc0ec768fadf4321f3173f2/CIP-0019/CIP-0019.md>
@@ -1221,8 +1132,7 @@ pub struct CardanoScriptConfig {
}
/// Nested message and enum types in `CardanoScriptConfig`.
pub mod cardano_script_config {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct PkhSkh {
#[prost(uint32, repeated, tag = "1")]
pub keypath_payment: ::prost::alloc::vec::Vec<u32>,
@@ -1233,16 +1143,14 @@ pub mod cardano_script_config {
/// <https://github.com/cardano-foundation/CIPs/blob/6c249ef48f8f5b32efc0ec768fadf4321f3173f2/CIP-0019/CIP-0019.md>
/// See also:
/// <https://github.com/input-output-hk/cardano-ledger-specs/blob/d0aa86ded0b973b09b629e5aa62aa1e71364d088/eras/alonzo/test-suite/cddl-files/alonzo.cddl#L137>
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Oneof)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Oneof)]
pub enum Config {
/// Shelley PaymentKeyHash & StakeKeyHash
#[prost(message, tag = "1")]
PkhSkh(PkhSkh),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct CardanoAddressRequest {
#[prost(enumeration = "CardanoNetwork", tag = "1")]
pub network: i32,
@@ -1256,7 +1164,6 @@ pub struct CardanoAddressRequest {
/// can fit the whole request in RAM and don't need to stream.
///
/// See also: <https://github.com/input-output-hk/cardano-ledger-specs/blob/d0aa86ded0b973b09b629e5aa62aa1e71364d088/eras/alonzo/test-suite/cddl-files/alonzo.cddl#L50>
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CardanoSignTransactionRequest {
#[prost(enumeration = "CardanoNetwork", tag = "1")]
@@ -1285,8 +1192,7 @@ pub struct CardanoSignTransactionRequest {
}
/// Nested message and enum types in `CardanoSignTransactionRequest`.
pub mod cardano_sign_transaction_request {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct Input {
#[prost(uint32, repeated, tag = "1")]
pub keypath: ::prost::alloc::vec::Vec<u32>,
@@ -1296,7 +1202,6 @@ pub mod cardano_sign_transaction_request {
pub prev_out_index: u32,
}
/// <https://github.com/input-output-hk/cardano-ledger/blob/d0aa86ded0b973b09b629e5aa62aa1e71364d088/eras/alonzo/test-suite/cddl-files/alonzo.cddl#L358>
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct AssetGroup {
#[prost(bytes = "vec", tag = "1")]
@@ -1306,8 +1211,7 @@ pub mod cardano_sign_transaction_request {
}
/// Nested message and enum types in `AssetGroup`.
pub mod asset_group {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct Token {
#[prost(bytes = "vec", tag = "1")]
pub asset_name: ::prost::alloc::vec::Vec<u8>,
@@ -1316,7 +1220,6 @@ pub mod cardano_sign_transaction_request {
pub value: u64,
}
}
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Output {
#[prost(string, tag = "1")]
@@ -1330,24 +1233,21 @@ pub mod cardano_sign_transaction_request {
pub asset_groups: ::prost::alloc::vec::Vec<AssetGroup>,
}
/// See <https://github.com/IntersectMBO/cardano-ledger/blob/cardano-ledger-conway-1.12.0.0/eras/conway/impl/cddl-files/conway.cddl#L273>
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct Certificate {
#[prost(oneof = "certificate::Cert", tags = "1, 2, 3, 10")]
pub cert: ::core::option::Option<certificate::Cert>,
}
/// Nested message and enum types in `Certificate`.
pub mod certificate {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct StakeDelegation {
#[prost(uint32, repeated, tag = "1")]
pub keypath: ::prost::alloc::vec::Vec<u32>,
#[prost(bytes = "vec", tag = "2")]
pub pool_keyhash: ::prost::alloc::vec::Vec<u8>,
}
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct VoteDelegation {
/// keypath in this instance refers to stake credential
#[prost(uint32, repeated, tag = "1")]
@@ -1376,10 +1276,10 @@ pub mod cardano_sign_transaction_request {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- CardanoDRepType::KeyHash => "KEY_HASH",
- CardanoDRepType::ScriptHash => "SCRIPT_HASH",
- CardanoDRepType::AlwaysAbstain => "ALWAYS_ABSTAIN",
- CardanoDRepType::AlwaysNoConfidence => "ALWAYS_NO_CONFIDENCE",
+ Self::KeyHash => "KEY_HASH",
+ Self::ScriptHash => "SCRIPT_HASH",
+ Self::AlwaysAbstain => "ALWAYS_ABSTAIN",
+ Self::AlwaysNoConfidence => "ALWAYS_NO_CONFIDENCE",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -1394,8 +1294,7 @@ pub mod cardano_sign_transaction_request {
}
}
}
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Oneof)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Oneof)]
pub enum Cert {
#[prost(message, tag = "1")]
StakeRegistration(super::super::Keypath),
@@ -1407,16 +1306,14 @@ pub mod cardano_sign_transaction_request {
VoteDelegation(VoteDelegation),
}
}
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct Withdrawal {
#[prost(uint32, repeated, tag = "1")]
pub keypath: ::prost::alloc::vec::Vec<u32>,
#[prost(uint64, tag = "2")]
pub value: u64,
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CardanoSignTransactionResponse {
#[prost(message, repeated, tag = "1")]
@@ -1425,24 +1322,21 @@ pub struct CardanoSignTransactionResponse {
}
/// Nested message and enum types in `CardanoSignTransactionResponse`.
pub mod cardano_sign_transaction_response {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Message)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct ShelleyWitness {
#[prost(bytes = "vec", tag = "1")]
pub public_key: ::prost::alloc::vec::Vec<u8>,
#[prost(bytes = "vec", tag = "2")]
pub signature: ::prost::alloc::vec::Vec<u8>,
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CardanoRequest {
#[prost(oneof = "cardano_request::Request", tags = "1, 2, 3")]
pub request: ::core::option::Option<cardano_request::Request>,
}
/// Nested message and enum types in `CardanoRequest`.
pub mod cardano_request {
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Request {
#[prost(message, tag = "1")]
@@ -1453,15 +1347,13 @@ pub mod cardano_request {
SignTransaction(super::CardanoSignTransactionRequest),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CardanoResponse {
#[prost(oneof = "cardano_response::Response", tags = "1, 2, 3")]
pub response: ::core::option::Option<cardano_response::Response>,
}
/// Nested message and enum types in `CardanoResponse`.
pub mod cardano_response {
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Response {
#[prost(message, tag = "1")]
@@ -1485,8 +1377,8 @@ impl CardanoNetwork {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- CardanoNetwork::CardanoMainnet => "CardanoMainnet",
- CardanoNetwork::CardanoTestnet => "CardanoTestnet",
+ Self::CardanoMainnet => "CardanoMainnet",
+ Self::CardanoTestnet => "CardanoTestnet",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -1498,8 +1390,7 @@ impl CardanoNetwork {
}
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct EthPubRequest {
#[prost(uint32, repeated, tag = "1")]
pub keypath: ::prost::alloc::vec::Vec<u32>,
@@ -1531,8 +1422,8 @@ pub mod eth_pub_request {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- OutputType::Address => "ADDRESS",
- OutputType::Xpub => "XPUB",
+ Self::Address => "ADDRESS",
+ Self::Xpub => "XPUB",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -1546,8 +1437,7 @@ pub mod eth_pub_request {
}
}
/// TX payload for "legacy" (EIP-155) transactions: <https://eips.ethereum.org/EIPS/eip-155>
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct EthSignRequest {
/// Deprecated: use chain_id instead.
#[prost(enumeration = "EthCoin", tag = "1")]
@@ -1585,7 +1475,6 @@ pub struct EthSignRequest {
pub data_length: u32,
}
/// TX payload for an EIP-1559 (type 2) transaction: <https://eips.ethereum.org/EIPS/eip-1559>
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct EthSignEip1559Request {
#[prost(uint64, tag = "1")]
@@ -1624,22 +1513,19 @@ pub struct EthSignEip1559Request {
#[prost(message, optional, tag = "13")]
pub payment_request: ::core::option::Option<BtcPaymentRequestRequest>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct EthSignDataRequestChunkResponse {
#[prost(uint32, tag = "1")]
pub offset: u32,
#[prost(uint32, tag = "2")]
pub length: u32,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct EthSignDataResponseChunkRequest {
#[prost(bytes = "vec", tag = "1")]
pub chunk: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct EthSignMessageRequest {
/// Deprecated: use chain_id instead.
#[prost(enumeration = "EthCoin", tag = "1")]
@@ -1656,14 +1542,12 @@ pub struct EthSignMessageRequest {
#[prost(uint64, tag = "5")]
pub chain_id: u64,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct EthSignResponse {
/// 65 bytes, last byte is the recid
#[prost(bytes = "vec", tag = "1")]
pub signature: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct EthSignTypedMessageRequest {
#[prost(uint64, tag = "1")]
@@ -1680,7 +1564,6 @@ pub struct EthSignTypedMessageRequest {
}
/// Nested message and enum types in `ETHSignTypedMessageRequest`.
pub mod eth_sign_typed_message_request {
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MemberType {
#[prost(enumeration = "DataType", tag = "1")]
@@ -1694,15 +1577,13 @@ pub mod eth_sign_typed_message_request {
#[prost(message, optional, boxed, tag = "4")]
pub array_type: ::core::option::Option<::prost::alloc::boxed::Box<MemberType>>,
}
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Member {
#[prost(string, tag = "1")]
pub name: ::prost::alloc::string::String,
#[prost(message, optional, tag = "2")]
pub r#type: ::core::option::Option<MemberType>,
}
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct StructType {
#[prost(string, tag = "1")]
@@ -1730,15 +1611,15 @@ pub mod eth_sign_typed_message_request {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- DataType::Unknown => "UNKNOWN",
- DataType::Bytes => "BYTES",
- DataType::Uint => "UINT",
- DataType::Int => "INT",
- DataType::Bool => "BOOL",
- DataType::Address => "ADDRESS",
- DataType::String => "STRING",
- DataType::Array => "ARRAY",
- DataType::Struct => "STRUCT",
+ Self::Unknown => "UNKNOWN",
+ Self::Bytes => "BYTES",
+ Self::Uint => "UINT",
+ Self::Int => "INT",
+ Self::Bool => "BOOL",
+ Self::Address => "ADDRESS",
+ Self::String => "STRING",
+ Self::Array => "ARRAY",
+ Self::Struct => "STRUCT",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -1758,8 +1639,7 @@ pub mod eth_sign_typed_message_request {
}
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct EthTypedMessageValueResponse {
#[prost(
enumeration = "eth_typed_message_value_response::RootObject",
@@ -1785,9 +1665,9 @@ pub mod eth_typed_message_value_response {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- RootObject::Unknown => "UNKNOWN",
- RootObject::Domain => "DOMAIN",
- RootObject::Message => "MESSAGE",
+ Self::Unknown => "UNKNOWN",
+ Self::Domain => "DOMAIN",
+ Self::Message => "MESSAGE",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -1801,8 +1681,7 @@ pub mod eth_typed_message_value_response {
}
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct EthTypedMessageValueRequest {
#[prost(bytes = "vec", tag = "1")]
pub value: ::prost::alloc::vec::Vec<u8>,
@@ -1811,15 +1690,13 @@ pub struct EthTypedMessageValueRequest {
#[prost(uint32, tag = "2")]
pub data_length: u32,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct EthRequest {
#[prost(oneof = "eth_request::Request", tags = "1, 2, 3, 4, 5, 6, 7, 8")]
pub request: ::core::option::Option<eth_request::Request>,
}
/// Nested message and enum types in `ETHRequest`.
pub mod eth_request {
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Request {
#[prost(message, tag = "1")]
@@ -1840,16 +1717,14 @@ pub mod eth_request {
DataResponseChunk(super::EthSignDataResponseChunkRequest),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct EthResponse {
#[prost(oneof = "eth_response::Response", tags = "1, 2, 3, 4, 5")]
pub response: ::core::option::Option<eth_response::Response>,
}
/// Nested message and enum types in `ETHResponse`.
pub mod eth_response {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Oneof)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Oneof)]
pub enum Response {
#[prost(message, tag = "1")]
Pub(super::PubResponse),
@@ -1880,9 +1755,9 @@ impl EthCoin {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- EthCoin::Eth => "ETH",
- EthCoin::RopstenEth => "RopstenETH",
- EthCoin::RinkebyEth => "RinkebyETH",
+ Self::Eth => "ETH",
+ Self::RopstenEth => "RopstenETH",
+ Self::RinkebyEth => "RinkebyETH",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -1909,9 +1784,9 @@ impl EthAddressCase {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- EthAddressCase::Mixed => "ETH_ADDRESS_CASE_MIXED",
- EthAddressCase::Upper => "ETH_ADDRESS_CASE_UPPER",
- EthAddressCase::Lower => "ETH_ADDRESS_CASE_LOWER",
+ Self::Mixed => "ETH_ADDRESS_CASE_MIXED",
+ Self::Upper => "ETH_ADDRESS_CASE_UPPER",
+ Self::Lower => "ETH_ADDRESS_CASE_LOWER",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -1929,28 +1804,24 @@ impl EthAddressCase {
/// this workflow.
/// If the passphrase feature is enabled, device entry returns PASSPHRASE_PENDING. The host
/// polls with UnlockContinueRequest until entry completes or it requests host entry.
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct UnlockRequest {}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct UnlockContinueRequest {
/// False polls device entry; true interrupts it to ask for host-entry consent.
/// After PASSPHRASE_ENTERED, continue to await confirmation and unlock;
/// host entry is ignored.
#[prost(bool, tag = "1")]
pub request_host_entry: bool,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct UnlockHostInfoRequest {
/// Only sent after HOST_ENTRY_READY. Absent cancels host input and restarts device entry;
/// the empty string submits the empty passphrase. The device confirms the actual value.
#[prost(string, optional, tag = "1")]
pub passphrase: ::core::option::Option<::prost::alloc::string::String>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct UnlockResponse {
#[prost(enumeration = "unlock_response::State", tag = "1")]
pub state: i32,
@@ -1974,10 +1845,10 @@ pub mod unlock_response {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- State::PassphrasePending => "PASSPHRASE_PENDING",
- State::HostEntryReady => "HOST_ENTRY_READY",
- State::PassphraseEntered => "PASSPHRASE_ENTERED",
- State::Done => "DONE",
+ Self::PassphrasePending => "PASSPHRASE_PENDING",
+ Self::HostEntryReady => "HOST_ENTRY_READY",
+ Self::PassphraseEntered => "PASSPHRASE_ENTERED",
+ Self::Done => "DONE",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -1992,77 +1863,66 @@ pub mod unlock_response {
}
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct ElectrumEncryptionKeyRequest {
#[prost(uint32, repeated, tag = "1")]
pub keypath: ::prost::alloc::vec::Vec<u32>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct ElectrumEncryptionKeyResponse {
#[prost(string, tag = "1")]
pub key: ::prost::alloc::string::String,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct Bip85Request {
#[prost(oneof = "bip85_request::App", tags = "1, 2")]
pub app: ::core::option::Option<bip85_request::App>,
}
/// Nested message and enum types in `BIP85Request`.
pub mod bip85_request {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, Copy, PartialEq, ::prost::Message)]
+ #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct AppLn {
#[prost(uint32, tag = "1")]
pub account_number: u32,
}
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, Copy, PartialEq, ::prost::Oneof)]
+ #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Oneof)]
pub enum App {
#[prost(message, tag = "1")]
Bip39(()),
#[prost(message, tag = "2")]
Ln(AppLn),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct Bip85Response {
#[prost(oneof = "bip85_response::App", tags = "1, 2")]
pub app: ::core::option::Option<bip85_response::App>,
}
/// Nested message and enum types in `BIP85Response`.
pub mod bip85_response {
- #[allow(clippy::derive_partial_eq_without_eq)]
- #[derive(Clone, PartialEq, ::prost::Oneof)]
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Oneof)]
pub enum App {
#[prost(message, tag = "1")]
Bip39(()),
#[prost(bytes, tag = "2")]
Ln(::prost::alloc::vec::Vec<u8>),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct ShowMnemonicRequest {}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct RestoreFromMnemonicRequest {
#[prost(uint32, tag = "1")]
pub timestamp: u32,
#[prost(int32, tag = "2")]
pub timezone_offset: i32,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct SetMnemonicPassphraseEnabledRequest {
#[prost(bool, tag = "1")]
pub enabled: bool,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct RebootRequest {
#[prost(enumeration = "reboot_request::Purpose", tag = "1")]
pub purpose: i32,
@@ -2082,8 +1942,8 @@ pub mod reboot_request {
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
- Purpose::Upgrade => "UPGRADE",
- Purpose::Settings => "SETTINGS",
+ Self::Upgrade => "UPGRADE",
+ Self::Settings => "SETTINGS",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
@@ -2097,16 +1957,14 @@ pub mod reboot_request {
}
}
/// Deprecated, last used in v1.0.0
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct PerformAttestationRequest {
/// 32 bytes challenge.
#[prost(bytes = "vec", tag = "1")]
pub challenge: ::prost::alloc::vec::Vec<u8>,
}
/// Deprecated, last used in v1.0.0
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct PerformAttestationResponse {
#[prost(bytes = "vec", tag = "1")]
pub bootloader_hash: ::prost::alloc::vec::Vec<u8>,
@@ -2119,18 +1977,15 @@ pub struct PerformAttestationResponse {
#[prost(bytes = "vec", tag = "5")]
pub challenge_signature: ::prost::alloc::vec::Vec<u8>,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct Error {
#[prost(int32, tag = "1")]
pub code: i32,
#[prost(string, tag = "2")]
pub message: ::prost::alloc::string::String,
}
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, Copy, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
pub struct Success {}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Request {
#[prost(
@@ -2141,7 +1996,6 @@ pub struct Request {
}
/// Nested message and enum types in `Request`.
pub mod request {
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Request {
/// removed: RandomNumberRequest random_number = 1;
@@ -2212,7 +2066,6 @@ pub mod request {
UnlockHostInfo(super::UnlockHostInfoRequest),
}
}
-#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Response {
#[prost(
@@ -2223,7 +2076,6 @@ pub struct Response {
}
/// Nested message and enum types in `Response`.
pub mod response {
- #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Response {
#[prost(message, tag = "1")]
### src/rust/bitbox02-rust/Cargo.toml
@@ -61,8 +61,8 @@ futures-lite = { workspace = true }
hex_lit = { workspace = true }
[dependencies.prost]
-# keep version in sync with tools/prost-build/Cargo.toml.
-version = "0.13.1"
+# keep version in sync with tools/prost-build-proto/Cargo.toml and src/rust/bitbox-proto/Cargo.toml.
+version = "0.14.4"
default-features = false
features = ["derive"]
### test/simulator-graphical-bb03/Cargo.lock
@@ -2536,19 +2536,19 @@ dependencies = [
[[package]]
name = "prost"
-version = "0.13.5"
+version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5"
+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
dependencies = [
"bytes",
"prost-derive",
]
[[package]]
name = "prost-derive"
-version = "0.13.5"
+version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
dependencies = [
"anyhow",
"itertools",
### test/simulator-graphical/Cargo.lock
@@ -2463,22 +2463,22 @@ dependencies = [
[[package]]
name = "prost"
-version = "0.13.1"
+version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e13db3d3fde688c61e2446b4d843bc27a7e8af269a69440c0308021dc92333cc"
+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
dependencies = [
"bytes",
"prost-derive",
]
[[package]]
name = "prost-derive"
-version = "0.13.1"
+version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "18bec9b0adc4eba778b33684b7ba3e7137789434769ee3ce3930463ef904cfca"
+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
dependencies = [
"anyhow",
- "itertools 0.12.1",
+ "itertools 0.14.0",
"proc-macro2",
"quote",
"syn",
### tools/prost-build-proto/Cargo.lock
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
-version = 3
+version = 4
[[package]]
name = "aho-corasick"
@@ -71,15 +71,30 @@ checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5"
[[package]]
name = "fixedbitset"
-version = "0.4.2"
+version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
+
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash",
+]
[[package]]
name = "hashbrown"
-version = "0.14.2"
+version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "heck"
@@ -89,12 +104,12 @@ checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "indexmap"
-version = "2.1.0"
+version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
- "hashbrown",
+ "hashbrown 0.17.1",
]
[[package]]
@@ -136,19 +151,14 @@ version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a"
-[[package]]
-name = "once_cell"
-version = "1.18.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
-
[[package]]
name = "petgraph"
-version = "0.6.4"
+version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e1d3afd2628e69da2be385eb6f2fd57c8ac7977ceeff6dc166ff1657b0e386a9"
+checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
dependencies = [
"fixedbitset",
+ "hashbrown 0.15.5",
"indexmap",
]
@@ -173,26 +183,24 @@ dependencies = [
[[package]]
name = "prost"
-version = "0.13.1"
+version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e13db3d3fde688c61e2446b4d843bc27a7e8af269a69440c0308021dc92333cc"
+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
dependencies = [
"bytes",
"prost-derive",
]
[[package]]
name = "prost-build"
-version = "0.13.1"
+version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5bb182580f71dd070f88d01ce3de9f4da5021db7115d2e1c3605a754153b77c1"
+checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042"
dependencies = [
- "bytes",
"heck",
"itertools",
"log",
"multimap",
- "once_cell",
"petgraph",
"prettyplease",
"prost",
@@ -211,9 +219,9 @@ dependencies = [
[[package]]
name = "prost-derive"
-version = "0.13.1"
+version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "18bec9b0adc4eba778b33684b7ba3e7137789434769ee3ce3930463ef904cfca"
+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
dependencies = [
"anyhow",
"itertools",
@@ -224,9 +232,9 @@ dependencies = [
[[package]]
name = "prost-types"
-version = "0.13.1"
+version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cee5168b05f49d4b0ca581206eb14a7b22fafd963efe729ac48eb03266e25cc2"
+checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"
dependencies = [
"prost",
]
### tools/prost-build-proto/Cargo.toml
@@ -8,5 +8,5 @@ edition = "2021"
license = "Apache-2.0"
[dependencies.prost-build]
-# keep version in sync with src/rust/bitbox02-rust/Cargo.toml
-version = "0.13.1"
+# keep version in sync with src/rust/bitbox02-rust/Cargo.toml and src/rust/bitbox-proto/Cargo.toml.
+version = "0.14.4"Why this scored 24/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.