Vendor dependencies for 0.3.0 release

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

View File

@@ -0,0 +1 @@
{"files":{"CHANGELOG.md":"85fdf8e820edd87073019ec27c85ad225cbe2f5f40fb07c179e83d9a7e54073e","Cargo.toml":"e7afe5c97eebabff0273878e4a9f8d15712ab2657e6e747da72fb2fae2077a90","LICENSE-APACHE":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"b7115dd8064dd2ba28e856bd82ca35801f122667f9509247b56e6cc9725a3778","build.rs":"2c6f887d6ff6c277254a19973318c92e3e99c3379f4c801a0931705a7c166eb8","src/arc.rs":"6f118a0c097dc70b3445f86e54cb7c8e473c20c0b4dfc971c97eaeb83390dc54","src/lib.rs":"7f7efc79e169422de23d8f469036267b4ef10d9df5f2587a353965394d7a6111","src/task.rs":"377a8f30d4b29eae997a554d7bebbf2127e409178dd2a7512cc7aa9c00fbc984","tests/arc.rs":"2c9144a45d0ce59d17b27aa332eaf048165e447ffb191fa0528ddeab8aaf92e6","version.rs":"07fb421f30f7be7788f85223bca1e38074e3ec8d0415abc8566f3ef9e3933f88"},"package":"d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507"}

106
vendor/portable-atomic-util/CHANGELOG.md vendored Normal file
View File

@@ -0,0 +1,106 @@
# Changelog
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org).
Releases may yanked if there is a security bug, a soundness bug, or a regression.
<!--
Note: In this file, do not use the hard wrap in the middle of a sentence for compatibility with GitHub comment style markdown rendering.
-->
## [Unreleased]
## [0.2.4] - 2024-11-23
- Add unstable `portable_atomic_unstable_coerce_unsized` cfg (requires Rust nightly). ([#195](https://github.com/taiki-e/portable-atomic/pull/195), thanks @brodycj)
- Respect [`RUSTC_BOOTSTRAP=-1` recently added in nightly](https://github.com/rust-lang/rust/pull/132993) in rustc version detection. ([5b2847a](https://github.com/taiki-e/portable-atomic/commit/5b2847a8b99aa2a57a6c80f5a47327b2764f08cc))
## [0.2.3] - 2024-10-17
- Add `new_uninit`/`new_uninit_slice`/`assume_init` to `Arc` at Rust 1.36+. (align to the [std `Arc` change in Rust 1.82](https://github.com/rust-lang/rust/pull/129401)) ([362dc9a](https://github.com/taiki-e/portable-atomic/commit/362dc9af2779c81aa346e89c4d3f3eef71cf29ed))
- Support `make_mut` on `Arc<[T]>` and `Arc<str>` at Rust 1.36+. (align to the [std `Arc` change in Rust 1.81](https://github.com/rust-lang/rust/pull/116113)) ([362dc9a](https://github.com/taiki-e/portable-atomic/commit/362dc9af2779c81aa346e89c4d3f3eef71cf29ed))
## [0.2.2] - 2024-07-11
- Fix [build issue with `esp` toolchain](https://github.com/taiki-e/semihosting/issues/11). ([f8ea85e](https://github.com/taiki-e/portable-atomic/commit/f8ea85e1aa46fa00bc865633fb40b05f8a0c823b))
## [0.2.1] - 2024-06-22
**Note:** This release has been yanked due to an issue fixed in 0.2.2.
- Support `impl Error for Arc<T: Error>` in no-std at Rust 1.81+. ([30b9f90](https://github.com/taiki-e/portable-atomic/commit/30b9f90346dfad14ab00f1c7e1f988f941330bcf))
- Implement `Default` for `Arc<[T]>` and `Arc<str>` at Rust 1.51+. (align to the [std `Arc` change in Rust 1.80](https://github.com/rust-lang/rust/pull/124640)) ([c6ee296](https://github.com/taiki-e/portable-atomic/commit/c6ee29606984863d008c2cf2209751ed0fa43b14))
- Implement `{AsFd, AsRawFd}` for `Arc<T>` on HermitOS. ([b778244](https://github.com/taiki-e/portable-atomic/commit/b778244917e17bfc431c9add4d028ff26d00e3b7))
## [0.2.0] - 2024-05-07
- Rewrite `Arc` based on `std::sync::Arc`'s implementation. ([#142](https://github.com/taiki-e/portable-atomic/pull/142))
This fixes accidental API differences with std ([#139](https://github.com/taiki-e/portable-atomic/issues/139), [#140](https://github.com/taiki-e/portable-atomic/issues/140)) and adds many missing APIs compared to std:
- Add `Arc::{downcast, into_inner, make_mut, new_cyclic}` ([#142](https://github.com/taiki-e/portable-atomic/pull/142))
- Implement `{fmt::Display, fmt::Pointer, Error, From<T>, From<Box<T>>, From<Cow<'a,T>>, AsFd, AsRawFd, AsHandle, AsSocket}` for `Arc<T>` ([#142](https://github.com/taiki-e/portable-atomic/pull/142), [78690d7](https://github.com/taiki-e/portable-atomic/commit/78690d7cad3b394119ea147c5773f67806a6ac09), [aba0930](https://github.com/taiki-e/portable-atomic/commit/aba0930269d7075b81810b49bbbbb6c5edc85ea0))
- Implement `{From<&[T]>, From<Vec<T>>, From<[T; N]>, FromIterator<T>}` for `Arc<[T]>` ([#142](https://github.com/taiki-e/portable-atomic/pull/142), [5e9f693](https://github.com/taiki-e/portable-atomic/commit/5e9f693dcb43c35187ca95ce1c824e0cb1d3c4f8))
- Implement `TryFrom<Arc<[T]>>` for `Arc<[T; N]>` ([#142](https://github.com/taiki-e/portable-atomic/pull/142))
- Implement `From<Arc<str>>` for `Arc<[u8]>` ([#142](https://github.com/taiki-e/portable-atomic/pull/142))
- Implement `{From<&str>, From<String>}` for `Arc<str>` ([#142](https://github.com/taiki-e/portable-atomic/pull/142))
- Implement `{Read, Write, Seek}` for `Arc<File>` ([591ece5](https://github.com/taiki-e/portable-atomic/commit/591ece5bde0f19f1895853791924ee55c51ee61e))
- Remove `T: UnwindSafe` bound from `impl UnwindSafe for Arc<T>` ([#142](https://github.com/taiki-e/portable-atomic/pull/142))
- Add `task::Wake`. ([#145](https://github.com/taiki-e/portable-atomic/pull/145))
This is equivalent to `std::task::Wake`, but using `portable_atomic_util::Arc` as a reference-counted pointer.
- Respect `RUSTC_WRAPPER` in rustc version detection.
## [0.1.5] - 2023-12-17
- Improve offset calculation in `Arc::{into_raw,as_ptr,from_ptr}`. ([#141](https://github.com/taiki-e/portable-atomic/pull/141), thanks @gtsiam)
## [0.1.4] - 2023-12-16
- Fix a bug where `Arc::{into_raw,as_ptr}` returned invalid pointers for larger alignment types. ([#138](https://github.com/taiki-e/portable-atomic/pull/138), thanks @notgull)
## [0.1.3] - 2023-05-06
**Note:** This release has been yanked due to a bug fixed in 0.1.4.
- Enable `portable-atomic`'s `require-cas` feature to display helpful error messages to users on targets requiring additional action on the user side to provide atomic CAS. ([#100](https://github.com/taiki-e/portable-atomic/pull/100))
## [0.1.2] - 2023-04-04
**Note:** This release has been yanked due to a bug fixed in 0.1.4.
- Implement `AsRef`, `Borrow`, and `Unpin` on `Arc`. ([#92](https://github.com/taiki-e/portable-atomic/pull/92) [#93](https://github.com/taiki-e/portable-atomic/pull/93), thanks @notgull)
## [0.1.1] - 2023-03-24
**Note:** This release has been yanked due to a bug fixed in 0.1.4.
- Prevent weak counter overflow in `Arc::downgrade`. ([#83](https://github.com/taiki-e/portable-atomic/pull/83))
This fixes [a potential unsoundness recently found in the standard library's `Arc`](https://github.com/rust-lang/rust/issues/108706).
## [0.1.0] - 2023-01-15
**Note:** This release has been yanked due to a bug fixed in 0.1.4.
Initial release
[Unreleased]: https://github.com/taiki-e/portable-atomic/compare/portable-atomic-util-0.2.4...HEAD
[0.2.4]: https://github.com/taiki-e/portable-atomic/compare/portable-atomic-util-0.2.3...portable-atomic-util-0.2.4
[0.2.3]: https://github.com/taiki-e/portable-atomic/compare/portable-atomic-util-0.2.2...portable-atomic-util-0.2.3
[0.2.2]: https://github.com/taiki-e/portable-atomic/compare/portable-atomic-util-0.2.1...portable-atomic-util-0.2.2
[0.2.1]: https://github.com/taiki-e/portable-atomic/compare/portable-atomic-util-0.2.0...portable-atomic-util-0.2.1
[0.2.0]: https://github.com/taiki-e/portable-atomic/compare/portable-atomic-util-0.1.5...portable-atomic-util-0.2.0
[0.1.5]: https://github.com/taiki-e/portable-atomic/compare/portable-atomic-util-0.1.4...portable-atomic-util-0.1.5
[0.1.4]: https://github.com/taiki-e/portable-atomic/compare/portable-atomic-util-0.1.3...portable-atomic-util-0.1.4
[0.1.3]: https://github.com/taiki-e/portable-atomic/compare/portable-atomic-util-0.1.2...portable-atomic-util-0.1.3
[0.1.2]: https://github.com/taiki-e/portable-atomic/compare/portable-atomic-util-0.1.1...portable-atomic-util-0.1.2
[0.1.1]: https://github.com/taiki-e/portable-atomic/compare/portable-atomic-util-0.1.0...portable-atomic-util-0.1.1
[0.1.0]: https://github.com/taiki-e/portable-atomic/releases/tag/portable-atomic-util-0.1.0

195
vendor/portable-atomic-util/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,195 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
rust-version = "1.34"
name = "portable-atomic-util"
version = "0.2.4"
build = "build.rs"
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = """
Synchronization primitives built with portable-atomic.
"""
readme = "README.md"
keywords = ["atomic"]
categories = [
"concurrency",
"data-structures",
"embedded",
"no-std",
]
license = "Apache-2.0 OR MIT"
repository = "https://github.com/taiki-e/portable-atomic"
[package.metadata.cargo_check_external_types]
allowed_external_types = []
[package.metadata.docs.rs]
all-features = true
targets = ["x86_64-unknown-linux-gnu"]
[lib]
name = "portable_atomic_util"
path = "src/lib.rs"
doc-scrape-examples = false
[[test]]
name = "arc"
path = "tests/arc.rs"
[dependencies.portable-atomic]
version = "1.5.1"
features = ["require-cas"]
default-features = false
[dev-dependencies.build-context]
version = "0.1"
[features]
alloc = []
default = []
std = ["alloc"]
[lints.clippy]
all = "warn"
as_ptr_cast_mut = "warn"
as_underscore = "warn"
default_union_representation = "warn"
inline_asm_x86_att_syntax = "warn"
pedantic = "warn"
trailing_empty_array = "warn"
transmute_undefined_repr = "warn"
undocumented_unsafe_blocks = "warn"
[lints.clippy.bool_assert_comparison]
level = "allow"
priority = 1
[lints.clippy.borrow_as_ptr]
level = "allow"
priority = 1
[lints.clippy.cast_lossless]
level = "allow"
priority = 1
[lints.clippy.declare_interior_mutable_const]
level = "allow"
priority = 1
[lints.clippy.doc_markdown]
level = "allow"
priority = 1
[lints.clippy.float_cmp]
level = "allow"
priority = 1
[lints.clippy.incompatible_msrv]
level = "allow"
priority = 1
[lints.clippy.lint_groups_priority]
level = "allow"
priority = 1
[lints.clippy.manual_assert]
level = "allow"
priority = 1
[lints.clippy.manual_range_contains]
level = "allow"
priority = 1
[lints.clippy.missing_errors_doc]
level = "allow"
priority = 1
[lints.clippy.module_name_repetitions]
level = "allow"
priority = 1
[lints.clippy.naive_bytecount]
level = "allow"
priority = 1
[lints.clippy.nonminimal_bool]
level = "allow"
priority = 1
[lints.clippy.range_plus_one]
level = "allow"
priority = 1
[lints.clippy.similar_names]
level = "allow"
priority = 1
[lints.clippy.single_match]
level = "allow"
priority = 1
[lints.clippy.single_match_else]
level = "allow"
priority = 1
[lints.clippy.struct_excessive_bools]
level = "allow"
priority = 1
[lints.clippy.struct_field_names]
level = "allow"
priority = 1
[lints.clippy.too_many_arguments]
level = "allow"
priority = 1
[lints.clippy.too_many_lines]
level = "allow"
priority = 1
[lints.clippy.type_complexity]
level = "allow"
priority = 1
[lints.clippy.unreadable_literal]
level = "allow"
priority = 1
[lints.rust]
deprecated_safe = "warn"
improper_ctypes = "warn"
improper_ctypes_definitions = "warn"
non_ascii_idents = "warn"
rust_2018_idioms = "warn"
single_use_lifetimes = "warn"
unreachable_pub = "warn"
[lints.rust.unexpected_cfgs]
level = "warn"
priority = 0
check-cfg = [
'cfg(target_arch,values("xtensa"))',
'cfg(target_os,values("psx"))',
'cfg(target_env,values("psx"))',
'cfg(target_feature,values("lse2","lse128","rcpc3"))',
'cfg(target_feature,values("quadword-atomics"))',
'cfg(target_feature,values("zaamo","zabha"))',
'cfg(target_pointer_width,values("128"))',
"cfg(portable_atomic_test_outline_atomics_detect_false,qemu,valgrind)",
"cfg(portable_atomic_no_outline_atomics,portable_atomic_outline_atomics)",
"cfg(portable_atomic_unstable_coerce_unsized)",
]

View File

@@ -0,0 +1,177 @@
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

23
vendor/portable-atomic-util/LICENSE-MIT vendored Normal file
View File

@@ -0,0 +1,23 @@
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.

77
vendor/portable-atomic-util/README.md vendored Normal file
View File

@@ -0,0 +1,77 @@
# portable-atomic-util
[![crates.io](https://img.shields.io/crates/v/portable-atomic-util?style=flat-square&logo=rust)](https://crates.io/crates/portable-atomic-util)
[![docs.rs](https://img.shields.io/badge/docs.rs-portable--atomic--util-blue?style=flat-square&logo=docs.rs)](https://docs.rs/portable-atomic-util)
[![license](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue?style=flat-square)](#license)
[![msrv](https://img.shields.io/badge/msrv-1.34-blue?style=flat-square&logo=rust)](https://www.rust-lang.org)
[![github actions](https://img.shields.io/github/actions/workflow/status/taiki-e/portable-atomic/ci.yml?branch=main&style=flat-square&logo=github)](https://github.com/taiki-e/portable-atomic/actions)
[![cirrus ci](https://img.shields.io/cirrus/github/taiki-e/portable-atomic/main?style=flat-square&logo=cirrusci)](https://cirrus-ci.com/github/taiki-e/portable-atomic)
<!-- tidy:crate-doc:start -->
Synchronization primitives built with [portable-atomic].
- Provide `Arc`. (optional, requires the `std` or `alloc` feature)
- Provide `task::Wake`. (optional, requires the `std` or `alloc` feature)
<!-- - Provide generic `Atomic<T>` type. (optional, requires the `generic` feature) -->
See [#1] for other primitives being considered for addition to this crate.
## Optional features
- **`std`**<br>
Use `std`.
Note:
- This implicitly enables the `alloc` feature.
- **`alloc`**<br>
Use `alloc`.
Note:
- The MSRV when this feature is enabled and the `std` feature is *not* enabled is Rust 1.36 that `alloc` crate stabilized.
<!-- TODO: https://github.com/taiki-e/portable-atomic/issues/1
- **`generic`**<br>
Provides generic `Atomic<T>` type.
-->
[portable-atomic]: https://github.com/taiki-e/portable-atomic
[#1]: https://github.com/taiki-e/portable-atomic/issues/1
## Optional cfg
One of the ways to enable cfg is to set [rustflags in the cargo config](https://doc.rust-lang.org/cargo/reference/config.html#targettriplerustflags):
```toml
# .cargo/config.toml
[target.<target>]
rustflags = ["--cfg", "portable_atomic_unstable_coerce_unsized"]
```
Or set environment variable:
```sh
RUSTFLAGS="--cfg portable_atomic_unstable_coerce_unsized" cargo ...
```
- <a name="optional-cfg-unstable-coerce-unsized"></a>**`--cfg portable_atomic_unstable_coerce_unsized`**<br>
Support coercing of `Arc<T>` to `Arc<U>` as in `std::sync::Arc`.
<!-- TODO: add coercing of `Weak<T>` to `Weak<U>` as well, with testing & documentation updates -->
This cfg requires Rust nightly because this coercing requires [unstable `CoerceUnsized` trait](https://doc.rust-lang.org/nightly/core/ops/trait.CoerceUnsized.html).
See [this issue comment](https://github.com/taiki-e/portable-atomic/issues/143#issuecomment-1866488569) for another known workaround.
**Note:** This cfg is unstable and outside of the normal semver guarantees and minor or patch versions of portable-atomic-util may make breaking changes to them at any time.
<!-- tidy:crate-doc:end -->
## License
Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
[MIT license](LICENSE-MIT) at your option.
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.

96
vendor/portable-atomic-util/build.rs vendored Normal file
View File

@@ -0,0 +1,96 @@
// SPDX-License-Identifier: Apache-2.0 OR MIT
// The rustc-cfg emitted by the build script are *not* public API.
// version.rs is shared with portable-atomic's build script, and portable-atomic-util only uses a part of it.
#[allow(dead_code)]
#[path = "version.rs"]
mod version;
use self::version::{rustc_version, Version};
use std::env;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=version.rs");
let version = match rustc_version() {
Some(version) => version,
None => {
if env::var_os("PORTABLE_ATOMIC_DENY_WARNINGS").is_some() {
panic!("unable to determine rustc version")
}
println!(
"cargo:warning={}: unable to determine rustc version; assuming latest stable rustc (1.{})",
env!("CARGO_PKG_NAME"),
Version::LATEST.minor
);
Version::LATEST
}
};
if version.minor >= 80 {
// Custom cfgs set by build script. Not public API.
// grep -F 'cargo:rustc-cfg=' build.rs | grep -Ev '^ *//' | sed -E 's/^.*cargo:rustc-cfg=//; s/(=\\)?".*$//' | LC_ALL=C sort -u | tr '\n' ',' | sed -E 's/,$/\n/'
println!(
"cargo:rustc-check-cfg=cfg(portable_atomic_no_alloc,portable_atomic_no_alloc_layout_extras,portable_atomic_no_core_unwind_safe,portable_atomic_no_error_in_core,portable_atomic_no_futures_api,portable_atomic_no_io_safety,portable_atomic_no_io_vec,portable_atomic_no_maybe_uninit,portable_atomic_no_min_const_generics,portable_atomic_no_track_caller,portable_atomic_no_unsafe_op_in_unsafe_fn,portable_atomic_sanitize_thread)"
);
}
// Note that cfgs are `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.
// alloc stabilized in Rust 1.36 (nightly-2019-04-15) https://github.com/rust-lang/rust/pull/59675
if !version.probe(36, 2019, 4, 14) {
println!("cargo:rustc-cfg=portable_atomic_no_alloc");
}
// std::{future,task} stabilized in Rust 1.36 (nightly-2019-04-25) https://github.com/rust-lang/rust/pull/59739
if !version.probe(36, 2019, 4, 24) {
println!("cargo:rustc-cfg=portable_atomic_no_futures_api");
}
// {read,write}_vectored stabilized in Rust 1.36 (nightly-2019-04-30) https://github.com/rust-lang/rust/pull/60334
if !version.probe(36, 2019, 4, 29) {
println!("cargo:rustc-cfg=portable_atomic_no_io_vec");
}
// MaybeUninit stabilized in Rust 1.36 (nightly-2019-05-21) https://github.com/rust-lang/rust/pull/60445
if !version.probe(36, 2019, 5, 20) {
println!("cargo:rustc-cfg=portable_atomic_no_maybe_uninit");
}
// Layout::{align_to,pad_to_align,extend,array} stabilized in Rust 1.44 (nightly-2020-04-22) https://github.com/rust-lang/rust/pull/69362
if !version.probe(44, 2020, 4, 21) {
println!("cargo:rustc-cfg=portable_atomic_no_alloc_layout_extras");
}
// track_caller stabilized in Rust 1.46 (nightly-2020-07-02): https://github.com/rust-lang/rust/pull/72445
if !version.probe(46, 2020, 7, 1) {
println!("cargo:rustc-cfg=portable_atomic_no_track_caller");
}
// min_const_generics stabilized in Rust 1.51 (nightly-2020-12-28): https://github.com/rust-lang/rust/pull/79135
if !version.probe(51, 2020, 12, 27) {
println!("cargo:rustc-cfg=portable_atomic_no_min_const_generics");
}
// unsafe_op_in_unsafe_fn stabilized in Rust 1.52 (nightly-2021-03-11): https://github.com/rust-lang/rust/pull/79208
if !version.probe(52, 2021, 3, 10) {
println!("cargo:rustc-cfg=portable_atomic_no_unsafe_op_in_unsafe_fn");
}
// https://github.com/rust-lang/rust/pull/84662 merged in Rust 1.56 (nightly-2021-08-02).
if !version.probe(56, 2021, 8, 1) {
println!("cargo:rustc-cfg=portable_atomic_no_core_unwind_safe");
}
// io_safety stabilized in Rust 1.63 (nightly-2022-06-16): https://github.com/rust-lang/rust/pull/95118
if !version.probe(63, 2022, 6, 15) {
println!("cargo:rustc-cfg=portable_atomic_no_io_safety");
}
// error_in_core stabilized in Rust 1.81 (nightly-2024-06-09): https://github.com/rust-lang/rust/pull/125951
if !version.probe(81, 2024, 6, 8) {
println!("cargo:rustc-cfg=portable_atomic_no_error_in_core");
}
if version.nightly {
// `cfg(sanitize = "..")` is not stabilized.
let sanitize = env::var("CARGO_CFG_SANITIZE").unwrap_or_default();
if sanitize.contains("thread") {
println!("cargo:rustc-cfg=portable_atomic_sanitize_thread");
}
}
}

3114
vendor/portable-atomic-util/src/arc.rs vendored Normal file

File diff suppressed because it is too large Load Diff

109
vendor/portable-atomic-util/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,109 @@
// SPDX-License-Identifier: Apache-2.0 OR MIT
/*!
<!-- tidy:crate-doc:start -->
Synchronization primitives built with [portable-atomic].
- Provide `Arc`. (optional, requires the `std` or `alloc` feature)
- Provide `task::Wake`. (optional, requires the `std` or `alloc` feature)
<!-- - Provide generic `Atomic<T>` type. (optional, requires the `generic` feature) -->
See [#1] for other primitives being considered for addition to this crate.
## Optional features
- **`std`**<br>
Use `std`.
Note:
- This implicitly enables the `alloc` feature.
- **`alloc`**<br>
Use `alloc`.
Note:
- The MSRV when this feature is enabled and the `std` feature is *not* enabled is Rust 1.36 that `alloc` crate stabilized.
<!-- TODO: https://github.com/taiki-e/portable-atomic/issues/1
- **`generic`**<br>
Provides generic `Atomic<T>` type.
-->
[portable-atomic]: https://github.com/taiki-e/portable-atomic
[#1]: https://github.com/taiki-e/portable-atomic/issues/1
## Optional cfg
One of the ways to enable cfg is to set [rustflags in the cargo config](https://doc.rust-lang.org/cargo/reference/config.html#targettriplerustflags):
```toml
# .cargo/config.toml
[target.<target>]
rustflags = ["--cfg", "portable_atomic_unstable_coerce_unsized"]
```
Or set environment variable:
```sh
RUSTFLAGS="--cfg portable_atomic_unstable_coerce_unsized" cargo ...
```
- <a name="optional-cfg-unstable-coerce-unsized"></a>**`--cfg portable_atomic_unstable_coerce_unsized`**<br>
Support coercing of `Arc<T>` to `Arc<U>` as in `std::sync::Arc`.
<!-- TODO: add coercing of `Weak<T>` to `Weak<U>` as well, with testing & documentation updates -->
This cfg requires Rust nightly because this coercing requires [unstable `CoerceUnsized` trait](https://doc.rust-lang.org/nightly/core/ops/trait.CoerceUnsized.html).
See [this issue comment](https://github.com/taiki-e/portable-atomic/issues/143#issuecomment-1866488569) for another known workaround.
**Note:** This cfg is unstable and outside of the normal semver guarantees and minor or patch versions of portable-atomic-util may make breaking changes to them at any time.
<!-- tidy:crate-doc:end -->
*/
#![no_std]
#![doc(test(
no_crate_inject,
attr(
deny(warnings, rust_2018_idioms, single_use_lifetimes),
allow(dead_code, unused_variables)
)
))]
#![cfg_attr(not(portable_atomic_no_unsafe_op_in_unsafe_fn), warn(unsafe_op_in_unsafe_fn))] // unsafe_op_in_unsafe_fn requires Rust 1.52
#![cfg_attr(portable_atomic_no_unsafe_op_in_unsafe_fn, allow(unused_unsafe))]
#![warn(
// Lints that may help when writing public library.
missing_debug_implementations,
missing_docs,
clippy::alloc_instead_of_core,
clippy::exhaustive_enums,
clippy::exhaustive_structs,
clippy::impl_trait_in_params,
// clippy::missing_inline_in_public_items,
clippy::std_instead_of_alloc,
clippy::std_instead_of_core,
)]
#![allow(clippy::inline_always)]
// docs.rs only (cfg is enabled by docs.rs, not build script)
#![cfg_attr(docsrs, feature(doc_cfg))]
// Enable custom unsized coercions if the user explicitly opts-in to unstable cfg
#![cfg_attr(portable_atomic_unstable_coerce_unsized, feature(coerce_unsized, unsize))]
#[cfg(all(feature = "alloc", not(portable_atomic_no_alloc)))]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
#[cfg(all(feature = "std", portable_atomic_no_alloc))]
extern crate std as alloc;
#[cfg(any(all(feature = "alloc", not(portable_atomic_no_alloc)), feature = "std"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "alloc", feature = "std"))))]
mod arc;
#[cfg(any(all(feature = "alloc", not(portable_atomic_no_alloc)), feature = "std"))]
pub use self::arc::{Arc, Weak};
#[cfg(not(portable_atomic_no_futures_api))]
#[cfg(any(all(feature = "alloc", not(portable_atomic_no_alloc)), feature = "std"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "alloc", feature = "std"))))]
pub mod task;

167
vendor/portable-atomic-util/src/task.rs vendored Normal file
View File

@@ -0,0 +1,167 @@
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Types and Traits for working with asynchronous tasks.
// This module is based on alloc::task::Wake.
//
// The code has been adjusted to work with stable Rust.
//
// Source: https://github.com/rust-lang/rust/blob/1.80.0/library/alloc/src/task.rs.
//
// Copyright & License of the original code:
// - https://github.com/rust-lang/rust/blob/1.80.0/COPYRIGHT
// - https://github.com/rust-lang/rust/blob/1.80.0/LICENSE-APACHE
// - https://github.com/rust-lang/rust/blob/1.80.0/LICENSE-MIT
use core::{
mem::ManuallyDrop,
task::{RawWaker, RawWakerVTable, Waker},
};
use crate::Arc;
/// The implementation of waking a task on an executor.
///
/// This is an equivalent to [`std::task::Wake`], but using [`portable_atomic_util::Arc`](crate::Arc)
/// as a reference-counted pointer. See the documentation for [`std::task::Wake`] for more details.
///
/// **Note:** Unlike `std::task::Wake`, all methods take `this:` instead of `self:`.
/// This is because using `portable_atomic_util::Arc` as a receiver requires the
/// [unstable `arbitrary_self_types` feature](https://github.com/rust-lang/rust/issues/44874).
///
/// # Examples
///
/// A basic `block_on` function that takes a future and runs it to completion on
/// the current thread.
///
/// **Note:** This example trades correctness for simplicity. In order to prevent
/// deadlocks, production-grade implementations will also need to handle
/// intermediate calls to `thread::unpark` as well as nested invocations.
///
/// ```
/// use portable_atomic_util::{task::Wake, Arc};
/// use std::{
/// future::Future,
/// task::{Context, Poll},
/// thread::{self, Thread},
/// };
///
/// /// A waker that wakes up the current thread when called.
/// struct ThreadWaker(Thread);
///
/// impl Wake for ThreadWaker {
/// fn wake(this: Arc<Self>) {
/// this.0.unpark();
/// }
/// }
///
/// /// Run a future to completion on the current thread.
/// fn block_on<T>(fut: impl Future<Output = T>) -> T {
/// // Pin the future so it can be polled.
/// let mut fut = Box::pin(fut);
///
/// // Create a new context to be passed to the future.
/// let t = thread::current();
/// let waker = Arc::new(ThreadWaker(t)).into();
/// let mut cx = Context::from_waker(&waker);
///
/// // Run the future to completion.
/// loop {
/// match fut.as_mut().poll(&mut cx) {
/// Poll::Ready(res) => return res,
/// Poll::Pending => thread::park(),
/// }
/// }
/// }
///
/// block_on(async {
/// println!("Hi from inside a future!");
/// });
/// ```
pub trait Wake {
/// Wake this task.
fn wake(this: Arc<Self>);
/// Wake this task without consuming the waker.
///
/// If an executor supports a cheaper way to wake without consuming the
/// waker, it should override this method. By default, it clones the
/// [`Arc`] and calls [`wake`] on the clone.
///
/// [`wake`]: Wake::wake
fn wake_by_ref(this: &Arc<Self>) {
Self::wake(this.clone());
}
}
impl<W: Wake + Send + Sync + 'static> From<Arc<W>> for Waker {
/// Use a `Wake`-able type as a `Waker`.
///
/// No heap allocations or atomic operations are used for this conversion.
fn from(waker: Arc<W>) -> Self {
// SAFETY: This is safe because raw_waker safely constructs
// a RawWaker from Arc<W>.
unsafe { Self::from_raw(raw_waker(waker)) }
}
}
impl<W: Wake + Send + Sync + 'static> From<Arc<W>> for RawWaker {
/// Use a `Wake`-able type as a `RawWaker`.
///
/// No heap allocations or atomic operations are used for this conversion.
fn from(waker: Arc<W>) -> Self {
raw_waker(waker)
}
}
// NB: This private function for constructing a RawWaker is used, rather than
// inlining this into the `From<Arc<W>> for RawWaker` impl, to ensure that
// the safety of `From<Arc<W>> for Waker` does not depend on the correct
// trait dispatch - instead both impls call this function directly and
// explicitly.
#[inline(always)]
fn raw_waker<W: Wake + Send + Sync + 'static>(waker: Arc<W>) -> RawWaker {
// Increment the reference count of the arc to clone it.
//
// The #[inline(always)] is to ensure that raw_waker and clone_waker are
// always generated in the same code generation unit as one another, and
// therefore that the structurally identical const-promoted RawWakerVTable
// within both functions is deduplicated at LLVM IR code generation time.
// This allows optimizing Waker::will_wake to a single pointer comparison of
// the vtable pointers, rather than comparing all four function pointers
// within the vtables.
#[inline(always)]
unsafe fn clone_waker<W: Wake + Send + Sync + 'static>(waker: *const ()) -> RawWaker {
// SAFETY: the caller must uphold the safety contract.
unsafe { Arc::increment_strong_count(waker as *const W) };
RawWaker::new(
waker,
&RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
)
}
// Wake by value, moving the Arc into the Wake::wake function
unsafe fn wake<W: Wake + Send + Sync + 'static>(waker: *const ()) {
// SAFETY: the caller must uphold the safety contract.
let waker = unsafe { Arc::from_raw(waker as *const W) };
<W as Wake>::wake(waker);
}
// Wake by reference, wrap the waker in ManuallyDrop to avoid dropping it
unsafe fn wake_by_ref<W: Wake + Send + Sync + 'static>(waker: *const ()) {
// SAFETY: the caller must uphold the safety contract.
let waker = unsafe { ManuallyDrop::new(Arc::from_raw(waker as *const W)) };
<W as Wake>::wake_by_ref(&waker);
}
// Decrement the reference count of the Arc on drop
unsafe fn drop_waker<W: Wake + Send + Sync + 'static>(waker: *const ()) {
// SAFETY: the caller must uphold the safety contract.
unsafe { Arc::decrement_strong_count(waker as *const W) };
}
RawWaker::new(
Arc::into_raw(waker) as *const (),
&RawWakerVTable::new(clone_waker::<W>, wake::<W>, wake_by_ref::<W>, drop_waker::<W>),
)
}

784
vendor/portable-atomic-util/tests/arc.rs vendored Normal file
View File

@@ -0,0 +1,784 @@
// SPDX-License-Identifier: Apache-2.0 OR MIT
#![cfg(any(feature = "std", feature = "alloc"))]
#![allow(clippy::undocumented_unsafe_blocks)]
use std::{borrow::Cow, panic};
use portable_atomic_util::{Arc, Weak};
#[derive(Debug, PartialEq)]
#[repr(align(128))]
struct Aligned(u32);
// https://github.com/taiki-e/portable-atomic/issues/37
#[test]
fn over_aligned() {
let value = Arc::new(Aligned(128));
let ptr = Arc::into_raw(value);
// SAFETY: `ptr` should always be a valid `Aligned`.
assert_eq!(unsafe { (*ptr).0 }, 128);
// SAFETY: `ptr` is a valid reference to an `Arc<Aligned>`.
let value = unsafe { Arc::from_raw(ptr) };
assert_eq!(value.0, 128);
}
#[test]
fn default() {
let v = Arc::<[Aligned]>::default();
assert_eq!(v[..], []);
let v = Arc::<[()]>::default();
assert_eq!(v[..], []);
let v = Arc::<str>::default();
assert_eq!(&v[..], "");
}
#[test]
fn cow_from() {
let o = Cow::Owned("abc".to_owned());
let b = Cow::Borrowed("def");
let o: Arc<str> = Arc::from(o);
let b: Arc<str> = Arc::from(b);
assert_eq!(&*o, "abc");
assert_eq!(&*b, "def");
}
#[test]
fn make_mut_unsized() {
let mut v: Arc<[i32]> = Arc::from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
Arc::make_mut(&mut v)[0] += 10;
assert_eq!(&*v, [11, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let v1 = Arc::clone(&v);
let v2 = Arc::make_mut(&mut v);
v2[1] += 10;
assert_eq!(&*v1, [11, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert_eq!(&*v2, [11, 12, 3, 4, 5, 6, 7, 8, 9, 10]);
assert_eq!(&*v, [11, 12, 3, 4, 5, 6, 7, 8, 9, 10]);
drop(v1);
let w = Arc::downgrade(&v);
Arc::make_mut(&mut v)[2] += 10;
assert_eq!(&*v, [11, 12, 13, 4, 5, 6, 7, 8, 9, 10]);
assert!(w.upgrade().is_none());
}
#[test]
fn make_mut_clone_panic() {
struct C(#[allow(dead_code)] Box<u8>);
impl Clone for C {
fn clone(&self) -> Self {
panic!()
}
}
let mut v: Arc<[C]> = Arc::from([C(Box::new(1)), C(Box::new(2))]);
let _v = Arc::make_mut(&mut v);
let v1 = Arc::clone(&v);
if !is_panic_abort() {
panic::catch_unwind(panic::AssertUnwindSafe(|| {
let _v = Arc::make_mut(&mut v);
}))
.unwrap_err();
}
drop(v1);
}
#[test]
fn weak_dangling() {
let w = Weak::<Aligned>::new();
let p = Weak::into_raw(w);
let w = unsafe { Weak::from_raw(p) };
let w2 = Weak::clone(&w);
assert!(w.upgrade().is_none());
assert!(w2.upgrade().is_none());
}
// For -C panic=abort -Z panic_abort_tests: https://github.com/rust-lang/rust/issues/67650
fn is_panic_abort() -> bool {
build_context::PANIC.contains("abort")
}
// https://github.com/rust-lang/rust/blob/1.80.0/library/alloc/src/sync/tests.rs
#[allow(clippy::many_single_char_names)]
mod alloc_tests {
use std::{
convert::TryInto,
sync::{mpsc::channel, Mutex},
thread,
};
use portable_atomic::{
AtomicBool, AtomicUsize,
Ordering::{Acquire, SeqCst},
};
use portable_atomic_util::{Arc, Weak};
struct Canary(*mut AtomicUsize);
impl Drop for Canary {
fn drop(&mut self) {
unsafe {
match *self {
Canary(c) => {
(*c).fetch_add(1, SeqCst);
}
}
}
}
}
#[test]
#[cfg_attr(target_os = "emscripten", ignore)]
fn manually_share_arc() {
let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let arc_v = Arc::new(v);
let (tx, rx) = channel();
let _t = thread::spawn(move || {
let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
assert_eq!((*arc_v)[3], 4);
});
tx.send(arc_v.clone()).unwrap();
assert_eq!((*arc_v)[2], 3);
assert_eq!((*arc_v)[4], 5);
}
#[test]
fn test_arc_get_mut() {
let mut x = Arc::new(3);
*Arc::get_mut(&mut x).unwrap() = 4;
assert_eq!(*x, 4);
let y = x.clone();
assert!(Arc::get_mut(&mut x).is_none());
drop(y);
assert!(Arc::get_mut(&mut x).is_some());
let _w = Arc::downgrade(&x);
assert!(Arc::get_mut(&mut x).is_none());
}
#[test]
fn weak_counts() {
assert_eq!(Weak::weak_count(&Weak::<u64>::new()), 0);
assert_eq!(Weak::strong_count(&Weak::<u64>::new()), 0);
let a = Arc::new(0);
let w = Arc::downgrade(&a);
assert_eq!(Weak::strong_count(&w), 1);
assert_eq!(Weak::weak_count(&w), 1);
let w2 = w.clone();
assert_eq!(Weak::strong_count(&w), 1);
assert_eq!(Weak::weak_count(&w), 2);
assert_eq!(Weak::strong_count(&w2), 1);
assert_eq!(Weak::weak_count(&w2), 2);
drop(w);
assert_eq!(Weak::strong_count(&w2), 1);
assert_eq!(Weak::weak_count(&w2), 1);
let a2 = a.clone();
assert_eq!(Weak::strong_count(&w2), 2);
assert_eq!(Weak::weak_count(&w2), 1);
drop(a2);
drop(a);
assert_eq!(Weak::strong_count(&w2), 0);
assert_eq!(Weak::weak_count(&w2), 0);
drop(w2);
}
#[test]
fn try_unwrap() {
let x = Arc::new(3);
assert_eq!(Arc::try_unwrap(x), Ok(3));
let x = Arc::new(4);
let _y = x.clone();
assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
let x = Arc::new(5);
let _w = Arc::downgrade(&x);
assert_eq!(Arc::try_unwrap(x), Ok(5));
}
#[test]
fn into_inner() {
for _ in 0..100
// ^ Increase chances of hitting potential race conditions
{
let x = Arc::new(3);
let y = Arc::clone(&x);
let r_thread = std::thread::spawn(|| Arc::into_inner(x));
let s_thread = std::thread::spawn(|| Arc::into_inner(y));
let r = r_thread.join().expect("r_thread panicked");
let s = s_thread.join().expect("s_thread panicked");
assert!(
matches!((r, s), (None, Some(3)) | (Some(3), None)),
"assertion failed: unexpected result `{:?}`\
\n expected `(None, Some(3))` or `(Some(3), None)`",
(r, s),
);
}
let x = Arc::new(3);
assert_eq!(Arc::into_inner(x), Some(3));
let x = Arc::new(4);
let y = Arc::clone(&x);
assert_eq!(Arc::into_inner(x), None);
assert_eq!(Arc::into_inner(y), Some(4));
let x = Arc::new(5);
let _w = Arc::downgrade(&x);
assert_eq!(Arc::into_inner(x), Some(5));
}
#[test]
fn into_from_raw() {
let x = Arc::new(Box::new("hello"));
let y = x.clone();
let x_ptr = Arc::into_raw(x);
drop(y);
unsafe {
assert_eq!(**x_ptr, "hello");
let x = Arc::from_raw(x_ptr);
assert_eq!(**x, "hello");
assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
}
}
#[test]
fn test_into_from_raw_unsized() {
use std::fmt::Display;
let arc: Arc<str> = Arc::from("foo");
let ptr = Arc::into_raw(arc.clone());
let arc2 = unsafe { Arc::from_raw(ptr) };
assert_eq!(unsafe { &*ptr }, "foo");
assert_eq!(arc, arc2);
#[cfg(portable_atomic_unstable_coerce_unsized)]
let arc: Arc<dyn Display> = Arc::new(123);
// TODO: This is a workaround in case CoerceUnsized is not available - remove this once it is no longer needed
#[cfg(not(portable_atomic_unstable_coerce_unsized))]
let arc: Arc<dyn Display> = Arc::from(Box::new(123) as Box<dyn Display>);
let ptr = Arc::into_raw(arc.clone());
let arc2 = unsafe { Arc::from_raw(ptr) };
assert_eq!(unsafe { &*ptr }.to_string(), "123");
assert_eq!(arc2.to_string(), "123");
}
#[test]
fn into_from_weak_raw() {
let x = Arc::new(Box::new("hello"));
let y = Arc::downgrade(&x);
let y_ptr = Weak::into_raw(y);
unsafe {
assert_eq!(**y_ptr, "hello");
let y = Weak::from_raw(y_ptr);
let y_up = Weak::upgrade(&y).unwrap();
assert_eq!(**y_up, "hello");
drop(y_up);
assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
}
}
// TODO: See Weak::from_raw
// #[test]
// fn test_into_from_weak_raw_unsized() {
// use std::fmt::Display;
// let arc: Arc<str> = Arc::from("foo");
// let weak: Weak<str> = Arc::downgrade(&arc);
// let ptr = Weak::into_raw(weak.clone());
// let weak2 = unsafe { Weak::from_raw(ptr) };
// assert_eq!(unsafe { &*ptr }, "foo");
// assert!(weak.ptr_eq(&weak2));
// // TODO: CoerceUnsized is needed to cast to Arc<dyn ..>
// // (may be possible to support this with portable_atomic_unstable_coerce_unsized cfg option)
// // let arc: Arc<dyn Display> = Arc::new(123);
// let arc: Arc<dyn Display> = Arc::from(Box::new(123) as Box<dyn Display>);
// let weak: Weak<dyn Display> = Arc::downgrade(&arc);
// let ptr = Weak::into_raw(weak.clone());
// let weak2 = unsafe { Weak::from_raw(ptr) };
// assert_eq!(unsafe { &*ptr }.to_string(), "123");
// assert!(weak.ptr_eq(&weak2));
// }
#[test]
fn test_cow_arc_clone_make_mut() {
let mut cow0 = Arc::new(75);
let mut cow1 = cow0.clone();
let mut cow2 = cow1.clone();
assert!(75 == *Arc::make_mut(&mut cow0));
assert!(75 == *Arc::make_mut(&mut cow1));
assert!(75 == *Arc::make_mut(&mut cow2));
*Arc::make_mut(&mut cow0) += 1;
*Arc::make_mut(&mut cow1) += 2;
*Arc::make_mut(&mut cow2) += 3;
assert!(76 == *cow0);
assert!(77 == *cow1);
assert!(78 == *cow2);
// none should point to the same backing memory
assert!(*cow0 != *cow1);
assert!(*cow0 != *cow2);
assert!(*cow1 != *cow2);
}
#[test]
fn test_cow_arc_clone_unique2() {
let mut cow0 = Arc::new(75);
let cow1 = cow0.clone();
let cow2 = cow1.clone();
assert!(75 == *cow0);
assert!(75 == *cow1);
assert!(75 == *cow2);
*Arc::make_mut(&mut cow0) += 1;
assert!(76 == *cow0);
assert!(75 == *cow1);
assert!(75 == *cow2);
// cow1 and cow2 should share the same contents
// cow0 should have a unique reference
assert!(*cow0 != *cow1);
assert!(*cow0 != *cow2);
assert!(*cow1 == *cow2);
}
#[test]
fn test_cow_arc_clone_weak() {
let mut cow0 = Arc::new(75);
let cow1_weak = Arc::downgrade(&cow0);
assert!(75 == *cow0);
assert!(75 == *cow1_weak.upgrade().unwrap());
*Arc::make_mut(&mut cow0) += 1;
assert!(76 == *cow0);
assert!(cow1_weak.upgrade().is_none());
}
#[test]
fn test_live() {
let x = Arc::new(5);
let y = Arc::downgrade(&x);
assert!(y.upgrade().is_some());
}
#[test]
fn test_dead() {
let x = Arc::new(5);
let y = Arc::downgrade(&x);
drop(x);
assert!(y.upgrade().is_none());
}
#[test]
fn weak_self_cyclic() {
struct Cycle {
x: Mutex<Option<Weak<Cycle>>>,
}
let a = Arc::new(Cycle { x: Mutex::new(None) });
let b = Arc::downgrade(&a.clone());
*a.x.lock().unwrap() = Some(b);
// hopefully we don't double-free (or leak)...
}
#[test]
fn drop_arc() {
let mut canary = AtomicUsize::new(0);
let x = Arc::new(Canary(&mut canary as *mut AtomicUsize));
drop(x);
assert!(canary.load(Acquire) == 1);
}
#[test]
fn drop_arc_weak() {
let mut canary = AtomicUsize::new(0);
let arc = Arc::new(Canary(&mut canary as *mut AtomicUsize));
let arc_weak = Arc::downgrade(&arc);
assert!(canary.load(Acquire) == 0);
drop(arc);
assert!(canary.load(Acquire) == 1);
drop(arc_weak);
}
#[test]
fn test_strong_count() {
let a = Arc::new(0);
assert!(Arc::strong_count(&a) == 1);
let w = Arc::downgrade(&a);
assert!(Arc::strong_count(&a) == 1);
let b = w.upgrade().expect("");
assert!(Arc::strong_count(&b) == 2);
assert!(Arc::strong_count(&a) == 2);
drop(w);
drop(a);
assert!(Arc::strong_count(&b) == 1);
let c = b.clone();
assert!(Arc::strong_count(&b) == 2);
assert!(Arc::strong_count(&c) == 2);
}
#[test]
fn test_weak_count() {
let a = Arc::new(0);
assert!(Arc::strong_count(&a) == 1);
assert!(Arc::weak_count(&a) == 0);
let w = Arc::downgrade(&a);
assert!(Arc::strong_count(&a) == 1);
assert!(Arc::weak_count(&a) == 1);
let x = w.clone();
assert!(Arc::weak_count(&a) == 2);
drop(w);
drop(x);
assert!(Arc::strong_count(&a) == 1);
assert!(Arc::weak_count(&a) == 0);
let c = a.clone();
assert!(Arc::strong_count(&a) == 2);
assert!(Arc::weak_count(&a) == 0);
let d = Arc::downgrade(&c);
assert!(Arc::weak_count(&c) == 1);
assert!(Arc::strong_count(&c) == 2);
drop(a);
drop(c);
drop(d);
}
#[test]
fn show_arc() {
let a = Arc::new(5);
assert_eq!(format!("{:?}", a), "5");
}
// Make sure deriving works with Arc<T>
#[allow(dead_code)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
struct Foo {
inner: Arc<i32>,
}
#[test]
fn test_unsized() {
#[cfg(portable_atomic_unstable_coerce_unsized)]
let x: Arc<[i32]> = Arc::new([1, 2, 3]);
// TODO: This is a workaround in case CoerceUnsized is not available - remove this once it is no longer needed
#[cfg(not(portable_atomic_unstable_coerce_unsized))]
let x: Arc<[i32]> = Arc::from(Box::new([1, 2, 3]) as Box<[i32]>);
assert_eq!(format!("{:?}", x), "[1, 2, 3]");
let y = Arc::downgrade(&x.clone());
drop(x);
assert!(y.upgrade().is_none());
}
#[test]
fn test_maybe_thin_unsized() {
// If/when custom thin DSTs exist, this test should be updated to use one
use std::ffi::{CStr, CString};
let x: Arc<CStr> = Arc::from(CString::new("swordfish").unwrap().into_boxed_c_str());
assert_eq!(format!("{:?}", x), "\"swordfish\"");
let y: Weak<CStr> = Arc::downgrade(&x);
drop(x);
// At this point, the weak points to a dropped DST
assert!(y.upgrade().is_none());
// But we still need to be able to get the alloc layout to drop.
// CStr has no drop glue, but custom DSTs might, and need to work.
drop(y);
}
#[test]
fn test_from_owned() {
let foo = 123;
let foo_arc = Arc::from(foo);
assert!(123 == *foo_arc);
}
#[test]
fn test_new_weak() {
let foo: Weak<usize> = Weak::new();
assert!(foo.upgrade().is_none());
}
#[test]
fn test_ptr_eq() {
let five = Arc::new(5);
let same_five = five.clone();
let other_five = Arc::new(5);
assert!(Arc::ptr_eq(&five, &same_five));
assert!(!Arc::ptr_eq(&five, &other_five));
}
#[test]
#[cfg_attr(target_os = "emscripten", ignore)]
fn test_weak_count_locked() {
let mut a = Arc::new(AtomicBool::new(false));
let a2 = a.clone();
let t = thread::spawn(move || {
// Miri is too slow
let count = if cfg!(miri) { 1_000 } else { 1_000_000 };
for _i in 0..count {
Arc::get_mut(&mut a);
}
a.store(true, SeqCst);
});
while !a2.load(SeqCst) {
let n = Arc::weak_count(&a2);
assert!(n < 2, "bad weak count: {}", n);
#[cfg(miri)] // Miri's scheduler does not guarantee liveness, and thus needs this hint.
std::hint::spin_loop();
}
t.join().unwrap();
}
#[test]
fn test_from_str() {
let r: Arc<str> = Arc::from("foo");
assert_eq!(&r[..], "foo");
}
#[test]
fn test_copy_from_slice() {
let s: &[u32] = &[1, 2, 3];
let r: Arc<[u32]> = Arc::from(s);
assert_eq!(&r[..], [1, 2, 3]);
}
#[test]
fn test_clone_from_slice() {
#[derive(Clone, Debug, Eq, PartialEq)]
struct X(u32);
let s: &[X] = &[X(1), X(2), X(3)];
let r: Arc<[X]> = Arc::from(s);
assert_eq!(&r[..], s);
}
#[test]
#[should_panic = "test_clone_from_slice_panic"]
fn test_clone_from_slice_panic() {
struct Fail(u32, String);
impl Clone for Fail {
fn clone(&self) -> Fail {
if self.0 == 2 {
panic!("test_clone_from_slice_panic");
}
Fail(self.0, self.1.clone())
}
}
let s: &[Fail] =
&[Fail(0, "foo".to_owned()), Fail(1, "bar".to_owned()), Fail(2, "baz".to_owned())];
// Should panic, but not cause memory corruption
let _r: Arc<[Fail]> = Arc::from(s);
}
#[test]
fn test_from_box() {
let b: Box<u32> = Box::new(123);
let r: Arc<u32> = Arc::from(b);
assert_eq!(*r, 123);
}
#[test]
fn test_from_box_str() {
let s = String::from("foo").into_boxed_str();
let r: Arc<str> = Arc::from(s);
assert_eq!(&r[..], "foo");
}
#[test]
fn test_from_box_slice() {
let s = vec![1, 2, 3].into_boxed_slice();
let r: Arc<[u32]> = Arc::from(s);
assert_eq!(&r[..], [1, 2, 3]);
}
#[test]
fn test_from_box_trait() {
use std::fmt::Display;
let b: Box<dyn Display> = Box::new(123);
let r: Arc<dyn Display> = Arc::from(b);
assert_eq!(r.to_string(), "123");
}
#[test]
fn test_from_box_trait_zero_sized() {
use std::fmt::Debug;
let b: Box<dyn Debug> = Box::new(());
let r: Arc<dyn Debug> = Arc::from(b);
assert_eq!(format!("{:?}", r), "()");
}
#[test]
fn test_from_vec() {
let v = vec![1, 2, 3];
let r: Arc<[u32]> = Arc::from(v);
assert_eq!(&r[..], [1, 2, 3]);
}
#[test]
fn test_downcast() {
use std::any::Any;
#[cfg(portable_atomic_unstable_coerce_unsized)]
let r1: Arc<dyn Any + Send + Sync> = Arc::new(i32::MAX);
// TODO: This is a workaround in case CoerceUnsized is not available - remove this once it is no longer needed
#[cfg(not(portable_atomic_unstable_coerce_unsized))]
let r1: Arc<dyn Any + Send + Sync> =
Arc::from(Box::new(i32::MAX) as Box<dyn Any + Send + Sync>);
#[cfg(portable_atomic_unstable_coerce_unsized)]
let r2: Arc<dyn Any + Send + Sync> = Arc::new("abc");
// TODO: This is a workaround in case CoerceUnsized is not available - remove this once it is no longer needed
#[cfg(not(portable_atomic_unstable_coerce_unsized))]
let r2: Arc<dyn Any + Send + Sync> =
Arc::from(Box::new("abc") as Box<dyn Any + Send + Sync>);
assert!(r1.clone().downcast::<u32>().is_err());
let r1i32 = r1.downcast::<i32>();
assert!(r1i32.is_ok());
assert_eq!(r1i32.unwrap(), Arc::new(i32::MAX));
assert!(r2.clone().downcast::<i32>().is_err());
let r2str = r2.downcast::<&'static str>();
assert!(r2str.is_ok());
assert_eq!(r2str.unwrap(), Arc::new("abc"));
}
#[test]
fn test_array_from_slice() {
let v = vec![1, 2, 3];
let r: Arc<[u32]> = Arc::from(v);
let a: Result<Arc<[u32; 3]>, _> = r.clone().try_into();
assert!(a.is_ok());
let a: Result<Arc<[u32; 2]>, _> = r.clone().try_into();
assert!(a.is_err());
}
#[test]
fn test_arc_cyclic_with_zero_refs() {
struct ZeroRefs {
inner: Weak<ZeroRefs>,
}
let zero_refs = Arc::new_cyclic(|inner| {
assert_eq!(inner.strong_count(), 0);
assert!(inner.upgrade().is_none());
ZeroRefs { inner: Weak::new() }
});
assert_eq!(Arc::strong_count(&zero_refs), 1);
assert_eq!(Arc::weak_count(&zero_refs), 0);
assert_eq!(zero_refs.inner.strong_count(), 0);
assert_eq!(zero_refs.inner.weak_count(), 0);
}
#[test]
fn test_arc_new_cyclic_one_ref() {
struct OneRef {
inner: Weak<OneRef>,
}
let one_ref = Arc::new_cyclic(|inner| {
assert_eq!(inner.strong_count(), 0);
assert!(inner.upgrade().is_none());
OneRef { inner: inner.clone() }
});
assert_eq!(Arc::strong_count(&one_ref), 1);
assert_eq!(Arc::weak_count(&one_ref), 1);
let one_ref2 = Weak::upgrade(&one_ref.inner).unwrap();
assert!(Arc::ptr_eq(&one_ref, &one_ref2));
assert_eq!(Arc::strong_count(&one_ref), 2);
assert_eq!(Arc::weak_count(&one_ref), 1);
}
#[test]
fn test_arc_cyclic_two_refs() {
struct TwoRefs {
inner1: Weak<TwoRefs>,
inner2: Weak<TwoRefs>,
}
let two_refs = Arc::new_cyclic(|inner| {
assert_eq!(inner.strong_count(), 0);
assert!(inner.upgrade().is_none());
let inner1 = inner.clone();
let inner2 = inner1.clone();
TwoRefs { inner1, inner2 }
});
assert_eq!(Arc::strong_count(&two_refs), 1);
assert_eq!(Arc::weak_count(&two_refs), 2);
let two_refs1 = Weak::upgrade(&two_refs.inner1).unwrap();
assert!(Arc::ptr_eq(&two_refs, &two_refs1));
let two_refs2 = Weak::upgrade(&two_refs.inner2).unwrap();
assert!(Arc::ptr_eq(&two_refs, &two_refs2));
assert_eq!(Arc::strong_count(&two_refs), 3);
assert_eq!(Arc::weak_count(&two_refs), 2);
}
/// Test for Arc::drop bug (https://github.com/rust-lang/rust/issues/55005)
#[test]
#[cfg(miri)] // relies on Stacked Borrows in Miri
fn arc_drop_dereferenceable_race() {
// The bug seems to take up to 700 iterations to reproduce with most seeds (tested 0-9).
for _ in 0..750 {
let arc_1 = Arc::new(());
let arc_2 = arc_1.clone();
let thread = thread::spawn(|| drop(arc_2));
// Spin a bit; makes the race more likely to appear
let mut i = 0;
while i < 256 {
i += 1;
}
drop(arc_1);
thread.join().unwrap();
}
}
}

136
vendor/portable-atomic-util/version.rs vendored Normal file
View File

@@ -0,0 +1,136 @@
// SPDX-License-Identifier: Apache-2.0 OR MIT
use std::{env, iter, process::Command, str};
pub(crate) fn rustc_version() -> Option<Version> {
let rustc = env::var_os("RUSTC")?;
let rustc_wrapper = if env::var_os("CARGO_ENCODED_RUSTFLAGS").is_some() {
env::var_os("RUSTC_WRAPPER").filter(|v| !v.is_empty())
} else {
// Cargo sets environment variables for wrappers correctly only since https://github.com/rust-lang/cargo/pull/9601.
None
};
// Do not apply RUSTC_WORKSPACE_WRAPPER: https://github.com/cuviper/autocfg/issues/58#issuecomment-2067625980
let mut rustc = rustc_wrapper.into_iter().chain(iter::once(rustc));
let mut cmd = Command::new(rustc.next().unwrap());
cmd.args(rustc);
// Use verbose version output because the packagers add extra strings to the normal version output.
// Do not use long flags (--version --verbose) because clippy-deriver doesn't handle them properly.
// -vV is also matched with that cargo internally uses: https://github.com/rust-lang/cargo/blob/0.80.0/src/cargo/util/rustc.rs#L65
let output = cmd.arg("-vV").output().ok()?;
let verbose_version = str::from_utf8(&output.stdout).ok()?;
Version::parse(verbose_version)
}
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) struct Version {
pub(crate) minor: u32,
pub(crate) nightly: bool,
commit_date: Date,
pub(crate) llvm: u32,
}
impl Version {
// The known latest stable version. If we unable to determine
// the rustc version, we assume this is the current version.
// It is no problem if this is older than the actual latest stable.
// LLVM version is assumed to be the minimum external LLVM version:
// https://github.com/rust-lang/rust/blob/1.82.0/src/bootstrap/src/core/build_steps/llvm.rs#L586
pub(crate) const LATEST: Self = Self::stable(82, 17);
pub(crate) const fn stable(rustc_minor: u32, llvm_major: u32) -> Self {
Self { minor: rustc_minor, nightly: false, commit_date: Date::UNKNOWN, llvm: llvm_major }
}
pub(crate) fn probe(&self, minor: u32, year: u16, month: u8, day: u8) -> bool {
if self.nightly {
self.minor > minor
|| self.minor == minor && self.commit_date >= Date::new(year, month, day)
} else {
self.minor >= minor
}
}
#[cfg(test)]
pub(crate) fn commit_date(&self) -> &Date {
&self.commit_date
}
pub(crate) fn parse(verbose_version: &str) -> Option<Self> {
let mut release = verbose_version
.lines()
.find(|line| line.starts_with("release: "))
.map(|line| &line["release: ".len()..])?
.splitn(2, '-');
let version = release.next().unwrap();
let channel = release.next().unwrap_or_default();
let mut digits = version.splitn(3, '.');
let major = digits.next()?;
if major != "1" {
return None;
}
let minor = digits.next()?.parse::<u32>().ok()?;
let _patch = digits.next().unwrap_or("0").parse::<u32>().ok()?;
let nightly = match env::var_os("RUSTC_BOOTSTRAP") {
// When -1 is passed rustc works like stable, e.g., cfg(target_feature = "unstable_target_feature") will never be set. https://github.com/rust-lang/rust/pull/132993
Some(ref v) if v == "-1" => false,
_ => channel == "nightly" || channel == "dev",
};
// Note that rustc 1.49-1.50 (and 1.13 or older) don't print LLVM version.
let llvm_major = (|| {
let version = verbose_version
.lines()
.find(|line| line.starts_with("LLVM version: "))
.map(|line| &line["LLVM version: ".len()..])?;
let mut digits = version.splitn(3, '.');
let major = digits.next()?.parse::<u32>().ok()?;
let _minor = digits.next()?.parse::<u32>().ok()?;
let _patch = digits.next().unwrap_or("0").parse::<u32>().ok()?;
Some(major)
})()
.unwrap_or(0);
// we don't refer commit date on stable/beta.
if nightly {
let commit_date = (|| {
let mut commit_date = verbose_version
.lines()
.find(|line| line.starts_with("commit-date: "))
.map(|line| &line["commit-date: ".len()..])?
.splitn(3, '-');
let year = commit_date.next()?.parse::<u16>().ok()?;
let month = commit_date.next()?.parse::<u8>().ok()?;
let day = commit_date.next()?.parse::<u8>().ok()?;
if month > 12 || day > 31 {
return None;
}
Some(Date::new(year, month, day))
})();
Some(Self {
minor,
nightly,
commit_date: commit_date.unwrap_or(Date::UNKNOWN),
llvm: llvm_major,
})
} else {
Some(Self::stable(minor, llvm_major))
}
}
}
#[derive(PartialEq, PartialOrd)]
#[cfg_attr(test, derive(Debug))]
pub(crate) struct Date {
pub(crate) year: u16,
pub(crate) month: u8,
pub(crate) day: u8,
}
impl Date {
const UNKNOWN: Self = Self::new(0, 0, 0);
const fn new(year: u16, month: u8, day: u8) -> Self {
Self { year, month, day }
}
}