diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000000000..223b61456c267 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,489 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "addr2line" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" +dependencies = [ + "compiler_builtins", + "gimli 0.29.0", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-core", +] + +[[package]] +name = "alloc" +version = "0.0.0" +dependencies = [ + "compiler_builtins", + "core", + "rand", + "rand_xorshift", +] + +[[package]] +name = "allocator-api2" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" + +[[package]] +name = "cc" +version = "1.0.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c51067fd44124faa7f870b4b1c969379ad32b2ba805aa959430ceaa384f695" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-core", +] + +[[package]] +name = "compiler_builtins" +version = "0.1.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb58b199190fcfe0846f55a3b545cd6b07a34bdd5930a476ff856f3ebcc5558a" +dependencies = [ + "cc", + "rustc-std-workspace-core", +] + +[[package]] +name = "core" +version = "0.0.0" +dependencies = [ + "rand", + "rand_xorshift", +] + +[[package]] +name = "dlmalloc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3264b043b8e977326c1ee9e723da2c1f8d09a99df52cacf00b4dbce5ac54414d" +dependencies = [ + "cfg-if", + "compiler_builtins", + "libc", + "rustc-std-workspace-core", + "windows-sys", +] + +[[package]] +name = "fortanix-sgx-abi" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57cafc2274c10fab234f176b25903ce17e690fca7597090d50880e047a0389c5" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-core", +] + +[[package]] +name = "getopts" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" +dependencies = [ + "rustc-std-workspace-core", + "rustc-std-workspace-std", + "unicode-width", +] + +[[package]] +name = "gimli" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "gimli" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "allocator-api2", + "compiler_builtins", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "libc" +version = "0.2.155" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" +dependencies = [ + "rustc-std-workspace-core", +] + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-core", +] + +[[package]] +name = "miniz_oxide" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" +dependencies = [ + "adler", + "compiler_builtins", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "object" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f203fa8daa7bb185f760ae12bd8e097f63d17041dcdcaf675ac54cdf863170e" +dependencies = [ + "compiler_builtins", + "memchr", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "panic_abort" +version = "0.0.0" +dependencies = [ + "alloc", + "cfg-if", + "compiler_builtins", + "core", + "libc", +] + +[[package]] +name = "panic_unwind" +version = "0.0.0" +dependencies = [ + "alloc", + "cfg-if", + "compiler_builtins", + "core", + "libc", + "unwind", +] + +[[package]] +name = "proc_macro" +version = "0.0.0" +dependencies = [ + "core", + "std", +] + +[[package]] +name = "profiler_builtins" +version = "0.0.0" +dependencies = [ + "cc", + "compiler_builtins", + "core", +] + +[[package]] +name = "r-efi" +version = "4.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9e935efc5854715dfc0a4c9ef18dc69dee0ec3bf9cc3ab740db831c0fdd86a3" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-core", +] + +[[package]] +name = "r-efi-alloc" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31d6f09fe2b6ad044bc3d2c34ce4979796581afd2f1ebc185837e02421e02fd7" +dependencies = [ + "compiler_builtins", + "r-efi", + "rustc-std-workspace-core", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "rand_xorshift" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-core", +] + +[[package]] +name = "rustc-std-workspace-alloc" +version = "1.99.0" +dependencies = [ + "alloc", +] + +[[package]] +name = "rustc-std-workspace-core" +version = "1.99.0" +dependencies = [ + "core", +] + +[[package]] +name = "rustc-std-workspace-std" +version = "1.99.0" +dependencies = [ + "std", +] + +[[package]] +name = "std" +version = "0.0.0" +dependencies = [ + "addr2line", + "alloc", + "cfg-if", + "compiler_builtins", + "core", + "dlmalloc", + "fortanix-sgx-abi", + "hashbrown", + "hermit-abi", + "libc", + "miniz_oxide", + "object", + "panic_abort", + "panic_unwind", + "profiler_builtins", + "r-efi", + "r-efi-alloc", + "rand", + "rand_xorshift", + "rustc-demangle", + "std_detect", + "unwind", + "wasi", +] + +[[package]] +name = "std_detect" +version = "0.1.5" +dependencies = [ + "cfg-if", + "compiler_builtins", + "libc", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "sysroot" +version = "0.0.0" +dependencies = [ + "proc_macro", + "std", + "test", +] + +[[package]] +name = "test" +version = "0.0.0" +dependencies = [ + "core", + "getopts", + "libc", + "std", +] + +[[package]] +name = "unicode-width" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-core", + "rustc-std-workspace-std", +] + +[[package]] +name = "unwind" +version = "0.0.0" +dependencies = [ + "cfg-if", + "compiler_builtins", + "core", + "libc", + "unwinding", +] + +[[package]] +name = "unwinding" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37a19a21a537f635c16c7576f22d0f2f7d63353c1337ad4ce0d8001c7952a25b" +dependencies = [ + "compiler_builtins", + "gimli 0.28.1", + "rustc-std-workspace-core", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000000000..c4513b4c127d8 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,44 @@ +[workspace] +resolver = "1" +members = [ + "std", + "sysroot", +] + +exclude = [ + # stdarch has its own Cargo workspace + "stdarch", +] + +[profile.release.package.compiler_builtins] +# For compiler-builtins we always use a high number of codegen units. +# The goal here is to place every single intrinsic into its own object +# file to avoid symbol clashes with the system libgcc if possible. Note +# that this number doesn't actually produce this many object files, we +# just don't create more than this number of object files. +# +# It's a bit of a bummer that we have to pass this here, unfortunately. +# Ideally this would be specified through an env var to Cargo so Cargo +# knows how many CGUs are for this specific crate, but for now +# per-crate configuration isn't specifiable in the environment. +codegen-units = 10000 + +# These dependencies of the standard library implement symbolication for +# backtraces on most platforms. Their debuginfo causes both linking to be slower +# (more data to chew through) and binaries to be larger without really all that +# much benefit. This section turns them all to down to have no debuginfo which +# helps to improve link times a little bit. +[profile.release.package] +addr2line.debug = 0 +adler.debug = 0 +gimli.debug = 0 +miniz_oxide.debug = 0 +object.debug = 0 +rustc-demangle.debug = 0 + +[patch.crates-io] +# See comments in `library/rustc-std-workspace-core/README.md` for what's going on +# here +rustc-std-workspace-core = { path = 'rustc-std-workspace-core' } +rustc-std-workspace-alloc = { path = 'rustc-std-workspace-alloc' } +rustc-std-workspace-std = { path = 'rustc-std-workspace-std' } diff --git a/alloc/Cargo.toml b/alloc/Cargo.toml index 612452a960a37..479eb0a2ba743 100644 --- a/alloc/Cargo.toml +++ b/alloc/Cargo.toml @@ -10,7 +10,10 @@ edition = "2021" [dependencies] core = { path = "../core" } -compiler_builtins = { version = "0.1.40", features = ['rustc-dep-of-std'] } +compiler_builtins = { version = "0.1.114", features = ['rustc-dep-of-std'] } + +[target.'cfg(not(any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")))'.dependencies] +compiler_builtins = { version = "0.1.114", features = ["no-f16-f128"] } [dev-dependencies] rand = { version = "0.8.5", default-features = false, features = ["alloc"] } @@ -38,8 +41,8 @@ harness = false compiler-builtins-mem = ['compiler_builtins/mem'] compiler-builtins-c = ["compiler_builtins/c"] compiler-builtins-no-asm = ["compiler_builtins/no-asm"] +compiler-builtins-no-f16-f128 = ["compiler_builtins/no-f16-f128"] compiler-builtins-mangled-names = ["compiler_builtins/mangled-names"] -compiler-builtins-weak-intrinsics = ["compiler_builtins/weak-intrinsics"] # Make panics and failed asserts immediately abort without formatting any message panic_immediate_abort = ["core/panic_immediate_abort"] # Choose algorithms that are optimized for binary size instead of runtime performance diff --git a/alloc/benches/btree/map.rs b/alloc/benches/btree/map.rs index 4fe07eb02139f..3bddef5045a00 100644 --- a/alloc/benches/btree/map.rs +++ b/alloc/benches/btree/map.rs @@ -1,7 +1,8 @@ use std::collections::BTreeMap; use std::ops::RangeBounds; -use rand::{seq::SliceRandom, Rng}; +use rand::seq::SliceRandom; +use rand::Rng; use test::{black_box, Bencher}; macro_rules! map_insert_rand_bench { diff --git a/alloc/benches/linked_list.rs b/alloc/benches/linked_list.rs index 29c5ad2bc6eb2..b9322b6d4c3ea 100644 --- a/alloc/benches/linked_list.rs +++ b/alloc/benches/linked_list.rs @@ -1,4 +1,5 @@ use std::collections::LinkedList; + use test::Bencher; #[bench] diff --git a/alloc/benches/string.rs b/alloc/benches/string.rs index 5c95160ba2d14..e0dbe80d28896 100644 --- a/alloc/benches/string.rs +++ b/alloc/benches/string.rs @@ -1,4 +1,5 @@ use std::iter::repeat; + use test::{black_box, Bencher}; #[bench] diff --git a/alloc/benches/vec.rs b/alloc/benches/vec.rs index 8ebfe313dc5d5..13d784d3fd40e 100644 --- a/alloc/benches/vec.rs +++ b/alloc/benches/vec.rs @@ -1,5 +1,6 @@ -use rand::RngCore; use std::iter::repeat; + +use rand::RngCore; use test::{black_box, Bencher}; #[bench] diff --git a/alloc/benches/vec_deque.rs b/alloc/benches/vec_deque.rs index 35939f489b45d..fb1e2685cc333 100644 --- a/alloc/benches/vec_deque.rs +++ b/alloc/benches/vec_deque.rs @@ -1,7 +1,6 @@ -use std::{ - collections::{vec_deque, VecDeque}, - mem, -}; +use std::collections::{vec_deque, VecDeque}; +use std::mem; + use test::{black_box, Bencher}; #[bench] diff --git a/alloc/benches/vec_deque_append.rs b/alloc/benches/vec_deque_append.rs index 30b6e600e5adc..7c805da973763 100644 --- a/alloc/benches/vec_deque_append.rs +++ b/alloc/benches/vec_deque_append.rs @@ -1,4 +1,5 @@ -use std::{collections::VecDeque, time::Instant}; +use std::collections::VecDeque; +use std::time::Instant; const VECDEQUE_LEN: i32 = 100000; const WARMUP_N: usize = 100; diff --git a/alloc/src/alloc.rs b/alloc/src/alloc.rs index 1833a7f477f00..db2d752cfde1c 100644 --- a/alloc/src/alloc.rs +++ b/alloc/src/alloc.rs @@ -2,16 +2,14 @@ #![stable(feature = "alloc_module", since = "1.28.0")] +#[stable(feature = "alloc_module", since = "1.28.0")] +#[doc(inline)] +pub use core::alloc::*; #[cfg(not(test))] use core::hint; - #[cfg(not(test))] use core::ptr::{self, NonNull}; -#[stable(feature = "alloc_module", since = "1.28.0")] -#[doc(inline)] -pub use core::alloc::*; - #[cfg(test)] mod tests; @@ -57,7 +55,7 @@ pub struct Global; #[cfg(test)] pub use std::alloc::Global; -/// Allocate memory with the global allocator. +/// Allocates memory with the global allocator. /// /// This function forwards calls to the [`GlobalAlloc::alloc`] method /// of the allocator registered with the `#[global_allocator]` attribute @@ -101,7 +99,7 @@ pub unsafe fn alloc(layout: Layout) -> *mut u8 { } } -/// Deallocate memory with the global allocator. +/// Deallocates memory with the global allocator. /// /// This function forwards calls to the [`GlobalAlloc::dealloc`] method /// of the allocator registered with the `#[global_allocator]` attribute @@ -119,7 +117,7 @@ pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) { unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) } } -/// Reallocate memory with the global allocator. +/// Reallocates memory with the global allocator. /// /// This function forwards calls to the [`GlobalAlloc::realloc`] method /// of the allocator registered with the `#[global_allocator]` attribute @@ -138,7 +136,7 @@ pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) } } -/// Allocate zero-initialized memory with the global allocator. +/// Allocates zero-initialized memory with the global allocator. /// /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method /// of the allocator registered with the `#[global_allocator]` attribute @@ -345,7 +343,7 @@ extern "Rust" { fn __rust_alloc_error_handler(size: usize, align: usize) -> !; } -/// Signal a memory allocation error. +/// Signals a memory allocation error. /// /// Callers of memory allocation APIs wishing to cease execution /// in response to an allocation error are encouraged to call this function, diff --git a/alloc/src/alloc/tests.rs b/alloc/src/alloc/tests.rs index 1a5938fd34cf1..5d6077f057a2c 100644 --- a/alloc/src/alloc/tests.rs +++ b/alloc/src/alloc/tests.rs @@ -1,9 +1,10 @@ use super::*; extern crate test; -use crate::boxed::Box; use test::Bencher; +use crate::boxed::Box; + #[test] fn allocate_zeroed() { unsafe { diff --git a/alloc/src/borrow.rs b/alloc/src/borrow.rs index 42f8a08a9e4ee..f86face3f90cb 100644 --- a/alloc/src/borrow.rs +++ b/alloc/src/borrow.rs @@ -2,21 +2,20 @@ #![stable(feature = "rust1", since = "1.0.0")] +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::borrow::{Borrow, BorrowMut}; use core::cmp::Ordering; use core::hash::{Hash, Hasher}; #[cfg(not(no_global_oom_handling))] use core::ops::{Add, AddAssign}; use core::ops::{Deref, DerefPure}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::borrow::{Borrow, BorrowMut}; +use Cow::*; use crate::fmt; #[cfg(not(no_global_oom_handling))] use crate::string::String; -use Cow::*; - #[stable(feature = "rust1", since = "1.0.0")] impl<'a, B: ?Sized> Borrow for Cow<'a, B> where diff --git a/alloc/src/boxed.rs b/alloc/src/boxed.rs index f299aa0124dbe..38f50955b122e 100644 --- a/alloc/src/boxed.rs +++ b/alloc/src/boxed.rs @@ -187,26 +187,26 @@ use core::any::Any; use core::async_iter::AsyncIterator; -use core::borrow; #[cfg(not(no_global_oom_handling))] use core::clone::CloneToUninit; use core::cmp::Ordering; use core::error::Error; -use core::fmt; use core::future::Future; use core::hash::{Hash, Hasher}; use core::iter::FusedIterator; -use core::marker::Tuple; -use core::marker::Unsize; +use core::marker::{Tuple, Unsize}; use core::mem::{self, SizedTypeProperties}; -use core::ops::{AsyncFn, AsyncFnMut, AsyncFnOnce}; use core::ops::{ - CoerceUnsized, Coroutine, CoroutineState, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver, + AsyncFn, AsyncFnMut, AsyncFnOnce, CoerceUnsized, Coroutine, CoroutineState, Deref, DerefMut, + DerefPure, DispatchFromDyn, Receiver, }; use core::pin::Pin; use core::ptr::{self, addr_of_mut, NonNull, Unique}; -use core::slice; use core::task::{Context, Poll}; +use core::{borrow, fmt, slice}; + +#[unstable(feature = "thin_box", issue = "92791")] +pub use thin::ThinBox; #[cfg(not(no_global_oom_handling))] use crate::alloc::handle_alloc_error; @@ -222,9 +222,6 @@ use crate::vec; #[cfg(not(no_global_oom_handling))] use crate::vec::Vec; -#[unstable(feature = "thin_box", issue = "92791")] -pub use thin::ThinBox; - mod thin; /// A pointer type that uniquely owns a heap allocation of type `T`. @@ -704,7 +701,7 @@ impl Box<[T]> { } /// Constructs a new boxed slice with uninitialized contents. Returns an error if - /// the allocation fails + /// the allocation fails. /// /// # Examples /// @@ -739,7 +736,7 @@ impl Box<[T]> { } /// Constructs a new boxed slice with uninitialized contents, with the memory - /// being filled with `0` bytes. Returns an error if the allocation fails + /// being filled with `0` bytes. Returns an error if the allocation fails. /// /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage /// of this method. @@ -831,6 +828,85 @@ impl Box<[T], A> { pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit], A> { unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) } } + + /// Constructs a new boxed slice with uninitialized contents in the provided allocator. Returns an error if + /// the allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_api, new_uninit)] + /// + /// use std::alloc::System; + /// + /// let mut values = Box::<[u32], _>::try_new_uninit_slice_in(3, System)?; + /// let values = unsafe { + /// // Deferred initialization: + /// values[0].as_mut_ptr().write(1); + /// values[1].as_mut_ptr().write(2); + /// values[2].as_mut_ptr().write(3); + /// values.assume_init() + /// }; + /// + /// assert_eq!(*values, [1, 2, 3]); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_api", issue = "32838")] + #[inline] + pub fn try_new_uninit_slice_in( + len: usize, + alloc: A, + ) -> Result], A>, AllocError> { + let ptr = if T::IS_ZST || len == 0 { + NonNull::dangling() + } else { + let layout = match Layout::array::>(len) { + Ok(l) => l, + Err(_) => return Err(AllocError), + }; + alloc.allocate(layout)?.cast() + }; + unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, alloc).into_box(len)) } + } + + /// Constructs a new boxed slice with uninitialized contents in the provided allocator, with the memory + /// being filled with `0` bytes. Returns an error if the allocation fails. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_api, new_uninit)] + /// + /// use std::alloc::System; + /// + /// let values = Box::<[u32], _>::try_new_zeroed_slice_in(3, System)?; + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [0, 0, 0]); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[unstable(feature = "allocator_api", issue = "32838")] + #[inline] + pub fn try_new_zeroed_slice_in( + len: usize, + alloc: A, + ) -> Result], A>, AllocError> { + let ptr = if T::IS_ZST || len == 0 { + NonNull::dangling() + } else { + let layout = match Layout::array::>(len) { + Ok(l) => l, + Err(_) => return Err(AllocError), + }; + alloc.allocate_zeroed(layout)?.cast() + }; + unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, alloc).into_box(len)) } + } } impl Box, A> { @@ -1097,6 +1173,7 @@ impl Box { /// ``` /// /// [memory layout]: self#memory-layout + #[must_use = "losing the pointer will leak memory"] #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub fn into_raw(b: Self) -> *mut T { @@ -1150,6 +1227,7 @@ impl Box { /// ``` /// /// [memory layout]: self#memory-layout + #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "allocator_api", issue = "32838")] #[inline] pub fn into_raw_with_allocator(b: Self) -> (*mut T, A) { @@ -1189,9 +1267,11 @@ impl Box { } /// Consumes and leaks the `Box`, returning a mutable reference, - /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime - /// `'a`. If the type has only static references, or none at all, then this - /// may be chosen to be `'static`. + /// `&'a mut T`. + /// + /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type + /// has only static references, or none at all, then this may be chosen to be + /// `'static`. /// /// This function is mainly useful for data that lives for the remainder of /// the program's life. Dropping the returned reference will cause a memory @@ -1774,7 +1854,7 @@ impl TryFrom> for Box<[T; N]> { } impl Box { - /// Attempt to downcast the box to a concrete type. + /// Attempts to downcast the box to a concrete type. /// /// # Examples /// @@ -1833,7 +1913,7 @@ impl Box { } impl Box { - /// Attempt to downcast the box to a concrete type. + /// Attempts to downcast the box to a concrete type. /// /// # Examples /// @@ -1892,7 +1972,7 @@ impl Box { } impl Box { - /// Attempt to downcast the box to a concrete type. + /// Attempts to downcast the box to a concrete type. /// /// # Examples /// diff --git a/alloc/src/boxed/thin.rs b/alloc/src/boxed/thin.rs index e9bfecba160a0..9baded3a52141 100644 --- a/alloc/src/boxed/thin.rs +++ b/alloc/src/boxed/thin.rs @@ -2,7 +2,6 @@ //! //! by matthieu-m -use crate::alloc::{self, Layout, LayoutError}; use core::error::Error; use core::fmt::{self, Debug, Display, Formatter}; #[cfg(not(no_global_oom_handling))] @@ -14,8 +13,9 @@ use core::mem; #[cfg(not(no_global_oom_handling))] use core::mem::SizedTypeProperties; use core::ops::{Deref, DerefMut}; -use core::ptr::Pointee; -use core::ptr::{self, NonNull}; +use core::ptr::{self, NonNull, Pointee}; + +use crate::alloc::{self, Layout, LayoutError}; /// ThinBox. /// diff --git a/alloc/src/collections/binary_heap/mod.rs b/alloc/src/collections/binary_heap/mod.rs index af01db19139e3..cc5f33c368542 100644 --- a/alloc/src/collections/binary_heap/mod.rs +++ b/alloc/src/collections/binary_heap/mod.rs @@ -144,12 +144,11 @@ #![stable(feature = "rust1", since = "1.0.0")] use core::alloc::Allocator; -use core::fmt; use core::iter::{FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen}; use core::mem::{self, swap, ManuallyDrop}; use core::num::NonZero; use core::ops::{Deref, DerefMut}; -use core::ptr; +use core::{fmt, ptr}; use crate::alloc::Global; use crate::collections::TryReserveError; @@ -484,7 +483,7 @@ impl BinaryHeap { /// heap.push(4); /// ``` #[unstable(feature = "allocator_api", issue = "32838")] - #[rustc_const_unstable(feature = "const_binary_heap_new_in", issue = "112353")] + #[rustc_const_unstable(feature = "const_binary_heap_new_in", issue = "125961")] #[must_use] pub const fn new_in(alloc: A) -> BinaryHeap { BinaryHeap { data: Vec::new_in(alloc) } @@ -965,6 +964,7 @@ impl BinaryHeap { } /// Returns an iterator which retrieves elements in heap order. + /// /// This method consumes the original heap. /// /// # Examples @@ -1361,7 +1361,7 @@ struct Hole<'a, T: 'a> { } impl<'a, T> Hole<'a, T> { - /// Create a new `Hole` at index `pos`. + /// Creates a new `Hole` at index `pos`. /// /// Unsafe because pos must be within the data slice. #[inline] diff --git a/alloc/src/collections/binary_heap/tests.rs b/alloc/src/collections/binary_heap/tests.rs index d4bc6226a14a8..1cb07c6214953 100644 --- a/alloc/src/collections/binary_heap/tests.rs +++ b/alloc/src/collections/binary_heap/tests.rs @@ -1,7 +1,8 @@ +use std::panic::{catch_unwind, AssertUnwindSafe}; + use super::*; use crate::boxed::Box; use crate::testing::crash_test::{CrashTestDummy, Panic}; -use std::panic::{catch_unwind, AssertUnwindSafe}; #[test] fn test_iterator() { @@ -504,11 +505,12 @@ fn test_retain_catch_unwind() { #[cfg(not(target_os = "emscripten"))] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn panic_safe() { - use rand::seq::SliceRandom; use std::cmp; use std::panic::{self, AssertUnwindSafe}; use std::sync::atomic::{AtomicUsize, Ordering}; + use rand::seq::SliceRandom; + static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0); #[derive(Eq, PartialEq, Ord, Clone, Debug)] diff --git a/alloc/src/collections/btree/append.rs b/alloc/src/collections/btree/append.rs index b6989afb6255d..47372938fbeda 100644 --- a/alloc/src/collections/btree/append.rs +++ b/alloc/src/collections/btree/append.rs @@ -1,8 +1,9 @@ -use super::merge_iter::MergeIterInner; -use super::node::{self, Root}; use core::alloc::Allocator; use core::iter::FusedIterator; +use super::merge_iter::MergeIterInner; +use super::node::{self, Root}; + impl Root { /// Appends all key-value pairs from the union of two ascending iterators, /// incrementing a `length` variable along the way. The latter makes it diff --git a/alloc/src/collections/btree/fix.rs b/alloc/src/collections/btree/fix.rs index 91b61218005a6..4c1e19ead4031 100644 --- a/alloc/src/collections/btree/fix.rs +++ b/alloc/src/collections/btree/fix.rs @@ -1,7 +1,10 @@ -use super::map::MIN_LEN; -use super::node::{marker, ForceResult::*, Handle, LeftOrRight::*, NodeRef, Root}; use core::alloc::Allocator; +use super::map::MIN_LEN; +use super::node::ForceResult::*; +use super::node::LeftOrRight::*; +use super::node::{marker, Handle, NodeRef, Root}; + impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { /// Stocks up a possibly underfull node by merging with or stealing from a /// sibling. If successful but at the cost of shrinking the parent node, diff --git a/alloc/src/collections/btree/map.rs b/alloc/src/collections/btree/map.rs index 3875f61efafdf..d84654e36d776 100644 --- a/alloc/src/collections/btree/map.rs +++ b/alloc/src/collections/btree/map.rs @@ -1,4 +1,3 @@ -use crate::vec::Vec; use core::borrow::Borrow; use core::cmp::Ordering; use core::error::Error; @@ -10,20 +9,21 @@ use core::mem::{self, ManuallyDrop}; use core::ops::{Bound, Index, RangeBounds}; use core::ptr; -use crate::alloc::{Allocator, Global}; - use super::borrow::DormantMutRef; use super::dedup_sorted_iter::DedupSortedIter; use super::navigate::{LazyLeafRange, LeafRange}; -use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root}; -use super::search::{SearchBound, SearchResult::*}; +use super::node::ForceResult::*; +use super::node::{self, marker, Handle, NodeRef, Root}; +use super::search::SearchBound; +use super::search::SearchResult::*; use super::set_val::SetValZST; +use crate::alloc::{Allocator, Global}; +use crate::vec::Vec; mod entry; #[stable(feature = "rust1", since = "1.0.0")] pub use entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry}; - use Entry::*; /// Minimum number of elements in a node that is not a root. @@ -2921,7 +2921,7 @@ impl<'a, K, V> Cursor<'a, K, V> { /// Returns a reference to the key and value of the next element without /// moving the cursor. /// - /// If the cursor is at the end of the map then `None` is returned + /// If the cursor is at the end of the map then `None` is returned. #[unstable(feature = "btree_cursors", issue = "107540")] pub fn peek_next(&self) -> Option<(&'a K, &'a V)> { self.clone().next() @@ -2963,7 +2963,7 @@ impl<'a, K, V, A> CursorMut<'a, K, V, A> { /// Returns a reference to the key and value of the next element without /// moving the cursor. /// - /// If the cursor is at the end of the map then `None` is returned + /// If the cursor is at the end of the map then `None` is returned. #[unstable(feature = "btree_cursors", issue = "107540")] pub fn peek_next(&mut self) -> Option<(&K, &mut V)> { let (k, v) = self.inner.peek_next()?; @@ -3061,7 +3061,7 @@ impl<'a, K, V, A> CursorMutKey<'a, K, V, A> { /// Returns a reference to the key and value of the next element without /// moving the cursor. /// - /// If the cursor is at the end of the map then `None` is returned + /// If the cursor is at the end of the map then `None` is returned. #[unstable(feature = "btree_cursors", issue = "107540")] pub fn peek_next(&mut self) -> Option<(&mut K, &mut V)> { let current = self.current.as_mut()?; diff --git a/alloc/src/collections/btree/map/entry.rs b/alloc/src/collections/btree/map/entry.rs index 66eb991c6d4b8..d128ad8ee5f6d 100644 --- a/alloc/src/collections/btree/map/entry.rs +++ b/alloc/src/collections/btree/map/entry.rs @@ -2,13 +2,12 @@ use core::fmt::{self, Debug}; use core::marker::PhantomData; use core::mem; -use crate::alloc::{Allocator, Global}; +use Entry::*; use super::super::borrow::DormantMutRef; use super::super::node::{marker, Handle, NodeRef}; use super::BTreeMap; - -use Entry::*; +use crate::alloc::{Allocator, Global}; /// A view into a single entry in a map, which may either be vacant or occupied. /// @@ -189,6 +188,7 @@ impl<'a, K: Ord, V, A: Allocator + Clone> Entry<'a, K, V, A> { } /// Ensures a value is in the entry by inserting, if empty, the result of the default function. + /// /// This method allows for generating key-derived values for insertion by providing the default /// function a reference to the key that was moved during the `.entry(key)` method call. /// diff --git a/alloc/src/collections/btree/map/tests.rs b/alloc/src/collections/btree/map/tests.rs index ba1f38dcc3e52..ff1254a5a0c42 100644 --- a/alloc/src/collections/btree/map/tests.rs +++ b/alloc/src/collections/btree/map/tests.rs @@ -1,3 +1,10 @@ +use core::assert_matches::assert_matches; +use std::iter; +use std::ops::Bound::{Excluded, Included, Unbounded}; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering::SeqCst; + use super::*; use crate::boxed::Box; use crate::fmt::Debug; @@ -6,11 +13,6 @@ use crate::string::{String, ToString}; use crate::testing::crash_test::{CrashTestDummy, Panic}; use crate::testing::ord_chaos::{Cyclic3, Governed, Governor}; use crate::testing::rng::DeterministicRng; -use core::assert_matches::assert_matches; -use std::iter; -use std::ops::Bound::{Excluded, Included, Unbounded}; -use std::panic::{catch_unwind, AssertUnwindSafe}; -use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; // Minimum number of elements to insert, to guarantee a tree with 2 levels, // i.e., a tree who's root is an internal node at height 1, with edges to leaf nodes. diff --git a/alloc/src/collections/btree/mem.rs b/alloc/src/collections/btree/mem.rs index e1363d1ae1f6b..d738c5c47b4cc 100644 --- a/alloc/src/collections/btree/mem.rs +++ b/alloc/src/collections/btree/mem.rs @@ -1,6 +1,4 @@ -use core::intrinsics; -use core::mem; -use core::ptr; +use core::{intrinsics, mem, ptr}; /// This replaces the value behind the `v` unique reference by calling the /// relevant function. diff --git a/alloc/src/collections/btree/navigate.rs b/alloc/src/collections/btree/navigate.rs index 5e6a26f65c41e..f5c621e2c1759 100644 --- a/alloc/src/collections/btree/navigate.rs +++ b/alloc/src/collections/btree/navigate.rs @@ -1,11 +1,10 @@ use core::borrow::Borrow; -use core::hint; use core::ops::RangeBounds; -use core::ptr; +use core::{hint, ptr}; -use super::node::{marker, ForceResult::*, Handle, NodeRef}; +use super::node::ForceResult::*; +use super::node::{marker, Handle, NodeRef}; use super::search::SearchBound; - use crate::alloc::Allocator; // `front` and `back` are always both `None` or both `Some`. pub struct LeafRange { diff --git a/alloc/src/collections/btree/remove.rs b/alloc/src/collections/btree/remove.rs index 0904299254f0a..c46422c2f1d45 100644 --- a/alloc/src/collections/btree/remove.rs +++ b/alloc/src/collections/btree/remove.rs @@ -1,7 +1,10 @@ -use super::map::MIN_LEN; -use super::node::{marker, ForceResult::*, Handle, LeftOrRight::*, NodeRef}; use core::alloc::Allocator; +use super::map::MIN_LEN; +use super::node::ForceResult::*; +use super::node::LeftOrRight::*; +use super::node::{marker, Handle, NodeRef}; + impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::KV> { /// Removes a key-value pair from the tree, and returns that pair, as well as /// the leaf edge corresponding to that former pair. It's possible this empties diff --git a/alloc/src/collections/btree/search.rs b/alloc/src/collections/btree/search.rs index ad3522b4e0418..1d5c927175ea6 100644 --- a/alloc/src/collections/btree/search.rs +++ b/alloc/src/collections/btree/search.rs @@ -2,11 +2,12 @@ use core::borrow::Borrow; use core::cmp::Ordering; use core::ops::{Bound, RangeBounds}; -use super::node::{marker, ForceResult::*, Handle, NodeRef}; - use SearchBound::*; use SearchResult::*; +use super::node::ForceResult::*; +use super::node::{marker, Handle, NodeRef}; + pub enum SearchBound { /// An inclusive bound to look for, just like `Bound::Included(T)`. Included(T), diff --git a/alloc/src/collections/btree/set.rs b/alloc/src/collections/btree/set.rs index b0bd6ef2d3c63..973e7c660670c 100644 --- a/alloc/src/collections/btree/set.rs +++ b/alloc/src/collections/btree/set.rs @@ -1,4 +1,3 @@ -use crate::vec::Vec; use core::borrow::Borrow; use core::cmp::Ordering::{self, Equal, Greater, Less}; use core::cmp::{max, min}; @@ -6,14 +5,14 @@ use core::fmt::{self, Debug}; use core::hash::{Hash, Hasher}; use core::iter::{FusedIterator, Peekable}; use core::mem::ManuallyDrop; -use core::ops::{BitAnd, BitOr, BitXor, RangeBounds, Sub}; +use core::ops::{BitAnd, BitOr, BitXor, Bound, RangeBounds, Sub}; use super::map::{BTreeMap, Keys}; use super::merge_iter::MergeIterInner; use super::set_val::SetValZST; use super::Recover; - use crate::alloc::{Allocator, Global}; +use crate::vec::Vec; /// An ordered set based on a B-Tree. /// @@ -1183,6 +1182,178 @@ impl BTreeSet { pub const fn is_empty(&self) -> bool { self.len() == 0 } + + /// Returns a [`Cursor`] pointing at the gap before the smallest element + /// greater than the given bound. + /// + /// Passing `Bound::Included(x)` will return a cursor pointing to the + /// gap before the smallest element greater than or equal to `x`. + /// + /// Passing `Bound::Excluded(x)` will return a cursor pointing to the + /// gap before the smallest element greater than `x`. + /// + /// Passing `Bound::Unbounded` will return a cursor pointing to the + /// gap before the smallest element in the set. + /// + /// # Examples + /// + /// ``` + /// #![feature(btree_cursors)] + /// + /// use std::collections::BTreeSet; + /// use std::ops::Bound; + /// + /// let set = BTreeSet::from([1, 2, 3, 4]); + /// + /// let cursor = set.lower_bound(Bound::Included(&2)); + /// assert_eq!(cursor.peek_prev(), Some(&1)); + /// assert_eq!(cursor.peek_next(), Some(&2)); + /// + /// let cursor = set.lower_bound(Bound::Excluded(&2)); + /// assert_eq!(cursor.peek_prev(), Some(&2)); + /// assert_eq!(cursor.peek_next(), Some(&3)); + /// + /// let cursor = set.lower_bound(Bound::Unbounded); + /// assert_eq!(cursor.peek_prev(), None); + /// assert_eq!(cursor.peek_next(), Some(&1)); + /// ``` + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn lower_bound(&self, bound: Bound<&Q>) -> Cursor<'_, T> + where + T: Borrow + Ord, + Q: Ord, + { + Cursor { inner: self.map.lower_bound(bound) } + } + + /// Returns a [`CursorMut`] pointing at the gap before the smallest element + /// greater than the given bound. + /// + /// Passing `Bound::Included(x)` will return a cursor pointing to the + /// gap before the smallest element greater than or equal to `x`. + /// + /// Passing `Bound::Excluded(x)` will return a cursor pointing to the + /// gap before the smallest element greater than `x`. + /// + /// Passing `Bound::Unbounded` will return a cursor pointing to the + /// gap before the smallest element in the set. + /// + /// # Examples + /// + /// ``` + /// #![feature(btree_cursors)] + /// + /// use std::collections::BTreeSet; + /// use std::ops::Bound; + /// + /// let mut set = BTreeSet::from([1, 2, 3, 4]); + /// + /// let mut cursor = set.lower_bound_mut(Bound::Included(&2)); + /// assert_eq!(cursor.peek_prev(), Some(&1)); + /// assert_eq!(cursor.peek_next(), Some(&2)); + /// + /// let mut cursor = set.lower_bound_mut(Bound::Excluded(&2)); + /// assert_eq!(cursor.peek_prev(), Some(&2)); + /// assert_eq!(cursor.peek_next(), Some(&3)); + /// + /// let mut cursor = set.lower_bound_mut(Bound::Unbounded); + /// assert_eq!(cursor.peek_prev(), None); + /// assert_eq!(cursor.peek_next(), Some(&1)); + /// ``` + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn lower_bound_mut(&mut self, bound: Bound<&Q>) -> CursorMut<'_, T, A> + where + T: Borrow + Ord, + Q: Ord, + { + CursorMut { inner: self.map.lower_bound_mut(bound) } + } + + /// Returns a [`Cursor`] pointing at the gap after the greatest element + /// smaller than the given bound. + /// + /// Passing `Bound::Included(x)` will return a cursor pointing to the + /// gap after the greatest element smaller than or equal to `x`. + /// + /// Passing `Bound::Excluded(x)` will return a cursor pointing to the + /// gap after the greatest element smaller than `x`. + /// + /// Passing `Bound::Unbounded` will return a cursor pointing to the + /// gap after the greatest element in the set. + /// + /// # Examples + /// + /// ``` + /// #![feature(btree_cursors)] + /// + /// use std::collections::BTreeSet; + /// use std::ops::Bound; + /// + /// let set = BTreeSet::from([1, 2, 3, 4]); + /// + /// let cursor = set.upper_bound(Bound::Included(&3)); + /// assert_eq!(cursor.peek_prev(), Some(&3)); + /// assert_eq!(cursor.peek_next(), Some(&4)); + /// + /// let cursor = set.upper_bound(Bound::Excluded(&3)); + /// assert_eq!(cursor.peek_prev(), Some(&2)); + /// assert_eq!(cursor.peek_next(), Some(&3)); + /// + /// let cursor = set.upper_bound(Bound::Unbounded); + /// assert_eq!(cursor.peek_prev(), Some(&4)); + /// assert_eq!(cursor.peek_next(), None); + /// ``` + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn upper_bound(&self, bound: Bound<&Q>) -> Cursor<'_, T> + where + T: Borrow + Ord, + Q: Ord, + { + Cursor { inner: self.map.upper_bound(bound) } + } + + /// Returns a [`CursorMut`] pointing at the gap after the greatest element + /// smaller than the given bound. + /// + /// Passing `Bound::Included(x)` will return a cursor pointing to the + /// gap after the greatest element smaller than or equal to `x`. + /// + /// Passing `Bound::Excluded(x)` will return a cursor pointing to the + /// gap after the greatest element smaller than `x`. + /// + /// Passing `Bound::Unbounded` will return a cursor pointing to the + /// gap after the greatest element in the set. + /// + /// # Examples + /// + /// ``` + /// #![feature(btree_cursors)] + /// + /// use std::collections::BTreeSet; + /// use std::ops::Bound; + /// + /// let mut set = BTreeSet::from([1, 2, 3, 4]); + /// + /// let mut cursor = unsafe { set.upper_bound_mut(Bound::Included(&3)) }; + /// assert_eq!(cursor.peek_prev(), Some(&3)); + /// assert_eq!(cursor.peek_next(), Some(&4)); + /// + /// let mut cursor = unsafe { set.upper_bound_mut(Bound::Excluded(&3)) }; + /// assert_eq!(cursor.peek_prev(), Some(&2)); + /// assert_eq!(cursor.peek_next(), Some(&3)); + /// + /// let mut cursor = unsafe { set.upper_bound_mut(Bound::Unbounded) }; + /// assert_eq!(cursor.peek_prev(), Some(&4)); + /// assert_eq!(cursor.peek_next(), None); + /// ``` + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn upper_bound_mut(&mut self, bound: Bound<&Q>) -> CursorMut<'_, T, A> + where + T: Borrow + Ord, + Q: Ord, + { + CursorMut { inner: self.map.upper_bound_mut(bound) } + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -1817,5 +1988,414 @@ impl<'a, T: Ord> Iterator for Union<'a, T> { #[stable(feature = "fused", since = "1.26.0")] impl FusedIterator for Union<'_, T> {} +/// A cursor over a `BTreeSet`. +/// +/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth. +/// +/// Cursors always point to a gap between two elements in the set, and can +/// operate on the two immediately adjacent elements. +/// +/// A `Cursor` is created with the [`BTreeSet::lower_bound`] and [`BTreeSet::upper_bound`] methods. +#[derive(Clone)] +#[unstable(feature = "btree_cursors", issue = "107540")] +pub struct Cursor<'a, K: 'a> { + inner: super::map::Cursor<'a, K, SetValZST>, +} + +#[unstable(feature = "btree_cursors", issue = "107540")] +impl Debug for Cursor<'_, K> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Cursor") + } +} + +/// A cursor over a `BTreeSet` with editing operations. +/// +/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can +/// safely mutate the set during iteration. This is because the lifetime of its yielded +/// references is tied to its own lifetime, instead of just the underlying map. This means +/// cursors cannot yield multiple elements at once. +/// +/// Cursors always point to a gap between two elements in the set, and can +/// operate on the two immediately adjacent elements. +/// +/// A `CursorMut` is created with the [`BTreeSet::lower_bound_mut`] and [`BTreeSet::upper_bound_mut`] +/// methods. +#[unstable(feature = "btree_cursors", issue = "107540")] +pub struct CursorMut<'a, K: 'a, #[unstable(feature = "allocator_api", issue = "32838")] A = Global> +{ + inner: super::map::CursorMut<'a, K, SetValZST, A>, +} + +#[unstable(feature = "btree_cursors", issue = "107540")] +impl Debug for CursorMut<'_, K, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CursorMut") + } +} + +/// A cursor over a `BTreeSet` with editing operations, and which allows +/// mutating elements. +/// +/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can +/// safely mutate the set during iteration. This is because the lifetime of its yielded +/// references is tied to its own lifetime, instead of just the underlying set. This means +/// cursors cannot yield multiple elements at once. +/// +/// Cursors always point to a gap between two elements in the set, and can +/// operate on the two immediately adjacent elements. +/// +/// A `CursorMutKey` is created from a [`CursorMut`] with the +/// [`CursorMut::with_mutable_key`] method. +/// +/// # Safety +/// +/// Since this cursor allows mutating elements, you must ensure that the +/// `BTreeSet` invariants are maintained. Specifically: +/// +/// * The newly inserted element must be unique in the tree. +/// * All elements in the tree must remain in sorted order. +#[unstable(feature = "btree_cursors", issue = "107540")] +pub struct CursorMutKey< + 'a, + K: 'a, + #[unstable(feature = "allocator_api", issue = "32838")] A = Global, +> { + inner: super::map::CursorMutKey<'a, K, SetValZST, A>, +} + +#[unstable(feature = "btree_cursors", issue = "107540")] +impl Debug for CursorMutKey<'_, K, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CursorMutKey") + } +} + +impl<'a, K> Cursor<'a, K> { + /// Advances the cursor to the next gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the end of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn next(&mut self) -> Option<&'a K> { + self.inner.next().map(|(k, _)| k) + } + + /// Advances the cursor to the previous gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the start of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn prev(&mut self) -> Option<&'a K> { + self.inner.prev().map(|(k, _)| k) + } + + /// Returns a reference to next element without moving the cursor. + /// + /// If the cursor is at the end of the set then `None` is returned + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_next(&self) -> Option<&'a K> { + self.inner.peek_next().map(|(k, _)| k) + } + + /// Returns a reference to the previous element without moving the cursor. + /// + /// If the cursor is at the start of the set then `None` is returned. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_prev(&self) -> Option<&'a K> { + self.inner.peek_prev().map(|(k, _)| k) + } +} + +impl<'a, T, A> CursorMut<'a, T, A> { + /// Advances the cursor to the next gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the end of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn next(&mut self) -> Option<&T> { + self.inner.next().map(|(k, _)| k) + } + + /// Advances the cursor to the previous gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the start of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn prev(&mut self) -> Option<&T> { + self.inner.prev().map(|(k, _)| k) + } + + /// Returns a reference to the next element without moving the cursor. + /// + /// If the cursor is at the end of the set then `None` is returned. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_next(&mut self) -> Option<&T> { + self.inner.peek_next().map(|(k, _)| k) + } + + /// Returns a reference to the previous element without moving the cursor. + /// + /// If the cursor is at the start of the set then `None` is returned. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_prev(&mut self) -> Option<&T> { + self.inner.peek_prev().map(|(k, _)| k) + } + + /// Returns a read-only cursor pointing to the same location as the + /// `CursorMut`. + /// + /// The lifetime of the returned `Cursor` is bound to that of the + /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the + /// `CursorMut` is frozen for the lifetime of the `Cursor`. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn as_cursor(&self) -> Cursor<'_, T> { + Cursor { inner: self.inner.as_cursor() } + } + + /// Converts the cursor into a [`CursorMutKey`], which allows mutating + /// elements in the tree. + /// + /// # Safety + /// + /// Since this cursor allows mutating elements, you must ensure that the + /// `BTreeSet` invariants are maintained. Specifically: + /// + /// * The newly inserted element must be unique in the tree. + /// * All elements in the tree must remain in sorted order. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, T, A> { + CursorMutKey { inner: unsafe { self.inner.with_mutable_key() } } + } +} + +impl<'a, T, A> CursorMutKey<'a, T, A> { + /// Advances the cursor to the next gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the end of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn next(&mut self) -> Option<&mut T> { + self.inner.next().map(|(k, _)| k) + } + + /// Advances the cursor to the previous gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the start of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn prev(&mut self) -> Option<&mut T> { + self.inner.prev().map(|(k, _)| k) + } + + /// Returns a reference to the next element without moving the cursor. + /// + /// If the cursor is at the end of the set then `None` is returned + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_next(&mut self) -> Option<&mut T> { + self.inner.peek_next().map(|(k, _)| k) + } + + /// Returns a reference to the previous element without moving the cursor. + /// + /// If the cursor is at the start of the set then `None` is returned. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_prev(&mut self) -> Option<&mut T> { + self.inner.peek_prev().map(|(k, _)| k) + } + + /// Returns a read-only cursor pointing to the same location as the + /// `CursorMutKey`. + /// + /// The lifetime of the returned `Cursor` is bound to that of the + /// `CursorMutKey`, which means it cannot outlive the `CursorMutKey` and that the + /// `CursorMutKey` is frozen for the lifetime of the `Cursor`. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn as_cursor(&self) -> Cursor<'_, T> { + Cursor { inner: self.inner.as_cursor() } + } +} + +impl<'a, T: Ord, A: Allocator + Clone> CursorMut<'a, T, A> { + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap before the + /// newly inserted element. + /// + /// # Safety + /// + /// You must ensure that the `BTreeSet` invariants are maintained. + /// Specifically: + /// + /// * The newly inserted element must be unique in the tree. + /// * All elements in the tree must remain in sorted order. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn insert_after_unchecked(&mut self, value: T) { + unsafe { self.inner.insert_after_unchecked(value, SetValZST) } + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap after the + /// newly inserted element. + /// + /// # Safety + /// + /// You must ensure that the `BTreeSet` invariants are maintained. + /// Specifically: + /// + /// * The newly inserted element must be unique in the tree. + /// * All elements in the tree must remain in sorted order. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn insert_before_unchecked(&mut self, value: T) { + unsafe { self.inner.insert_before_unchecked(value, SetValZST) } + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap before the + /// newly inserted element. + /// + /// If the inserted element is not greater than the element before the + /// cursor (if any), or if it not less than the element after the cursor (if + /// any), then an [`UnorderedKeyError`] is returned since this would + /// invalidate the [`Ord`] invariant between the elements of the set. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn insert_after(&mut self, value: T) -> Result<(), UnorderedKeyError> { + self.inner.insert_after(value, SetValZST) + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap after the + /// newly inserted element. + /// + /// If the inserted element is not greater than the element before the + /// cursor (if any), or if it not less than the element after the cursor (if + /// any), then an [`UnorderedKeyError`] is returned since this would + /// invalidate the [`Ord`] invariant between the elements of the set. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn insert_before(&mut self, value: T) -> Result<(), UnorderedKeyError> { + self.inner.insert_before(value, SetValZST) + } + + /// Removes the next element from the `BTreeSet`. + /// + /// The element that was removed is returned. The cursor position is + /// unchanged (before the removed element). + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn remove_next(&mut self) -> Option { + self.inner.remove_next().map(|(k, _)| k) + } + + /// Removes the precending element from the `BTreeSet`. + /// + /// The element that was removed is returned. The cursor position is + /// unchanged (after the removed element). + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn remove_prev(&mut self) -> Option { + self.inner.remove_prev().map(|(k, _)| k) + } +} + +impl<'a, T: Ord, A: Allocator + Clone> CursorMutKey<'a, T, A> { + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap before the + /// newly inserted element. + /// + /// # Safety + /// + /// You must ensure that the `BTreeSet` invariants are maintained. + /// Specifically: + /// + /// * The key of the newly inserted element must be unique in the tree. + /// * All elements in the tree must remain in sorted order. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn insert_after_unchecked(&mut self, value: T) { + unsafe { self.inner.insert_after_unchecked(value, SetValZST) } + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap after the + /// newly inserted element. + /// + /// # Safety + /// + /// You must ensure that the `BTreeSet` invariants are maintained. + /// Specifically: + /// + /// * The newly inserted element must be unique in the tree. + /// * All elements in the tree must remain in sorted order. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn insert_before_unchecked(&mut self, value: T) { + unsafe { self.inner.insert_before_unchecked(value, SetValZST) } + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap before the + /// newly inserted element. + /// + /// If the inserted element is not greater than the element before the + /// cursor (if any), or if it not less than the element after the cursor (if + /// any), then an [`UnorderedKeyError`] is returned since this would + /// invalidate the [`Ord`] invariant between the elements of the set. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn insert_after(&mut self, value: T) -> Result<(), UnorderedKeyError> { + self.inner.insert_after(value, SetValZST) + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap after the + /// newly inserted element. + /// + /// If the inserted element is not greater than the element before the + /// cursor (if any), or if it not less than the element after the cursor (if + /// any), then an [`UnorderedKeyError`] is returned since this would + /// invalidate the [`Ord`] invariant between the elements of the set. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn insert_before(&mut self, value: T) -> Result<(), UnorderedKeyError> { + self.inner.insert_before(value, SetValZST) + } + + /// Removes the next element from the `BTreeSet`. + /// + /// The element that was removed is returned. The cursor position is + /// unchanged (before the removed element). + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn remove_next(&mut self) -> Option { + self.inner.remove_next().map(|(k, _)| k) + } + + /// Removes the precending element from the `BTreeSet`. + /// + /// The element that was removed is returned. The cursor position is + /// unchanged (after the removed element). + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn remove_prev(&mut self) -> Option { + self.inner.remove_prev().map(|(k, _)| k) + } +} + +#[unstable(feature = "btree_cursors", issue = "107540")] +pub use super::map::UnorderedKeyError; + #[cfg(test)] mod tests; diff --git a/alloc/src/collections/btree/set/tests.rs b/alloc/src/collections/btree/set/tests.rs index 48bf767413835..f947b6108c9a7 100644 --- a/alloc/src/collections/btree/set/tests.rs +++ b/alloc/src/collections/btree/set/tests.rs @@ -1,8 +1,9 @@ +use std::ops::Bound::{Excluded, Included}; +use std::panic::{catch_unwind, AssertUnwindSafe}; + use super::*; use crate::testing::crash_test::{CrashTestDummy, Panic}; use crate::testing::rng::DeterministicRng; -use std::ops::Bound::{Excluded, Included}; -use std::panic::{catch_unwind, AssertUnwindSafe}; #[test] fn test_clone_eq() { diff --git a/alloc/src/collections/btree/split.rs b/alloc/src/collections/btree/split.rs index 638dc98fc3e41..c188ed1da6113 100644 --- a/alloc/src/collections/btree/split.rs +++ b/alloc/src/collections/btree/split.rs @@ -1,8 +1,10 @@ -use super::node::{ForceResult::*, Root}; -use super::search::SearchResult::*; use core::alloc::Allocator; use core::borrow::Borrow; +use super::node::ForceResult::*; +use super::node::Root; +use super::search::SearchResult::*; + impl Root { /// Calculates the length of both trees that result from splitting up /// a given number of distinct key-value pairs. diff --git a/alloc/src/collections/linked_list.rs b/alloc/src/collections/linked_list.rs index 077483a174b10..0cd410c0fb7c1 100644 --- a/alloc/src/collections/linked_list.rs +++ b/alloc/src/collections/linked_list.rs @@ -13,12 +13,11 @@ #![stable(feature = "rust1", since = "1.0.0")] use core::cmp::Ordering; -use core::fmt; use core::hash::{Hash, Hasher}; use core::iter::FusedIterator; use core::marker::PhantomData; -use core::mem; use core::ptr::NonNull; +use core::{fmt, mem}; use super::SpecExtend; use crate::alloc::{Allocator, Global}; diff --git a/alloc/src/collections/linked_list/tests.rs b/alloc/src/collections/linked_list/tests.rs index d3744c5a9d0c9..9b3c9ac5ce52e 100644 --- a/alloc/src/collections/linked_list/tests.rs +++ b/alloc/src/collections/linked_list/tests.rs @@ -1,12 +1,12 @@ -use super::*; -use crate::testing::crash_test::{CrashTestDummy, Panic}; -use crate::vec::Vec; - use std::panic::{catch_unwind, AssertUnwindSafe}; use std::thread; use rand::RngCore; +use super::*; +use crate::testing::crash_test::{CrashTestDummy, Panic}; +use crate::vec::Vec; + #[test] fn test_basic() { let mut m = LinkedList::>::new(); @@ -1167,9 +1167,7 @@ fn test_drop_panic() { #[test] fn test_allocator() { - use core::alloc::AllocError; - use core::alloc::Allocator; - use core::alloc::Layout; + use core::alloc::{AllocError, Allocator, Layout}; use core::cell::Cell; struct A { diff --git a/alloc/src/collections/mod.rs b/alloc/src/collections/mod.rs index 705b81535c279..020cf4d736510 100644 --- a/alloc/src/collections/mod.rs +++ b/alloc/src/collections/mod.rs @@ -27,33 +27,30 @@ pub mod btree_set { pub use super::btree::set::*; } +use core::fmt::Display; + #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use binary_heap::BinaryHeap; - #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use btree_map::BTreeMap; - #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use btree_set::BTreeSet; - #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use linked_list::LinkedList; - #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use vec_deque::VecDeque; use crate::alloc::{Layout, LayoutError}; -use core::fmt::Display; /// The error type for `try_reserve` methods. #[derive(Clone, PartialEq, Eq, Debug)] diff --git a/alloc/src/collections/vec_deque/drain.rs b/alloc/src/collections/vec_deque/drain.rs index 1373e60149274..44fcef4ed7dc4 100644 --- a/alloc/src/collections/vec_deque/drain.rs +++ b/alloc/src/collections/vec_deque/drain.rs @@ -4,9 +4,8 @@ use core::mem::{self, SizedTypeProperties}; use core::ptr::NonNull; use core::{fmt, ptr}; -use crate::alloc::{Allocator, Global}; - use super::VecDeque; +use crate::alloc::{Allocator, Global}; /// A draining iterator over the elements of a `VecDeque`. /// diff --git a/alloc/src/collections/vec_deque/into_iter.rs b/alloc/src/collections/vec_deque/into_iter.rs index 4747517393c66..2d283dac9a97a 100644 --- a/alloc/src/collections/vec_deque/into_iter.rs +++ b/alloc/src/collections/vec_deque/into_iter.rs @@ -1,10 +1,11 @@ use core::iter::{FusedIterator, TrustedLen}; +use core::mem::MaybeUninit; use core::num::NonZero; -use core::{array, fmt, mem::MaybeUninit, ops::Try, ptr}; - -use crate::alloc::{Allocator, Global}; +use core::ops::Try; +use core::{array, fmt, ptr}; use super::VecDeque; +use crate::alloc::{Allocator, Global}; /// An owning iterator over the elements of a `VecDeque`. /// diff --git a/alloc/src/collections/vec_deque/mod.rs b/alloc/src/collections/vec_deque/mod.rs index a07f250d7d88c..dc725ec0f56e4 100644 --- a/alloc/src/collections/vec_deque/mod.rs +++ b/alloc/src/collections/vec_deque/mod.rs @@ -8,23 +8,19 @@ #![stable(feature = "rust1", since = "1.0.0")] use core::cmp::{self, Ordering}; -use core::fmt; use core::hash::{Hash, Hasher}; use core::iter::{repeat_n, repeat_with, ByRefSized}; -use core::mem::{ManuallyDrop, SizedTypeProperties}; -use core::ops::{Index, IndexMut, Range, RangeBounds}; -use core::ptr; -use core::slice; - // This is used in a bunch of intra-doc links. // FIXME: For some reason, `#[cfg(doc)]` wasn't sufficient, resulting in // failures in linkchecker even though rustdoc built the docs just fine. #[allow(unused_imports)] use core::mem; +use core::mem::{ManuallyDrop, SizedTypeProperties}; +use core::ops::{Index, IndexMut, Range, RangeBounds}; +use core::{fmt, ptr, slice}; use crate::alloc::{Allocator, Global}; -use crate::collections::TryReserveError; -use crate::collections::TryReserveErrorKind; +use crate::collections::{TryReserveError, TryReserveErrorKind}; use crate::raw_vec::RawVec; use crate::vec::Vec; diff --git a/alloc/src/collections/vec_deque/spec_extend.rs b/alloc/src/collections/vec_deque/spec_extend.rs index 6a89abc3ef9b6..a9b0fd073b548 100644 --- a/alloc/src/collections/vec_deque/spec_extend.rs +++ b/alloc/src/collections/vec_deque/spec_extend.rs @@ -1,9 +1,9 @@ -use crate::alloc::Allocator; -use crate::vec; use core::iter::TrustedLen; use core::slice; use super::VecDeque; +use crate::alloc::Allocator; +use crate::vec; // Specialization trait used for VecDeque::extend pub(super) trait SpecExtend { diff --git a/alloc/src/ffi/c_str.rs b/alloc/src/ffi/c_str.rs index f1eb195b88462..e32676a65432b 100644 --- a/alloc/src/ffi/c_str.rs +++ b/alloc/src/ffi/c_str.rs @@ -3,25 +3,21 @@ #[cfg(test)] mod tests; -use crate::borrow::{Cow, ToOwned}; -use crate::boxed::Box; -use crate::rc::Rc; -use crate::slice::hack::into_vec; -use crate::string::String; -use crate::vec::Vec; use core::borrow::Borrow; use core::ffi::{c_char, CStr}; -use core::fmt; -use core::mem; use core::num::NonZero; -use core::ops; -use core::ptr; -use core::slice; use core::slice::memchr; use core::str::{self, Utf8Error}; +use core::{fmt, mem, ops, ptr, slice}; +use crate::borrow::{Cow, ToOwned}; +use crate::boxed::Box; +use crate::rc::Rc; +use crate::slice::hack::into_vec; +use crate::string::String; #[cfg(target_has_atomic = "ptr")] use crate::sync::Arc; +use crate::vec::Vec; /// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the /// middle. diff --git a/alloc/src/ffi/c_str/tests.rs b/alloc/src/ffi/c_str/tests.rs index 9f51e17a427f5..8b7172b3f20a9 100644 --- a/alloc/src/ffi/c_str/tests.rs +++ b/alloc/src/ffi/c_str/tests.rs @@ -1,10 +1,10 @@ -use super::*; use core::assert_matches::assert_matches; use core::ffi::FromBytesUntilNulError; -use core::hash::{Hash, Hasher}; - #[allow(deprecated)] use core::hash::SipHasher13 as DefaultHasher; +use core::hash::{Hash, Hasher}; + +use super::*; #[test] fn c_to_rust() { diff --git a/alloc/src/ffi/mod.rs b/alloc/src/ffi/mod.rs index 9fc1acc231bff..4f9dc40a3cfc9 100644 --- a/alloc/src/ffi/mod.rs +++ b/alloc/src/ffi/mod.rs @@ -80,13 +80,12 @@ #![stable(feature = "alloc_ffi", since = "1.64.0")] -#[doc(no_inline)] -#[stable(feature = "alloc_c_string", since = "1.64.0")] -pub use self::c_str::{FromVecWithNulError, IntoStringError, NulError}; - #[doc(inline)] #[stable(feature = "alloc_c_string", since = "1.64.0")] pub use self::c_str::CString; +#[doc(no_inline)] +#[stable(feature = "alloc_c_string", since = "1.64.0")] +pub use self::c_str::{FromVecWithNulError, IntoStringError, NulError}; #[unstable(feature = "c_str_module", issue = "112134")] pub mod c_str; diff --git a/alloc/src/fmt.rs b/alloc/src/fmt.rs index c6bba619ae646..4b9b90fc1f157 100644 --- a/alloc/src/fmt.rs +++ b/alloc/src/fmt.rs @@ -600,8 +600,7 @@ pub use core::fmt::{LowerHex, Pointer, UpperHex}; #[cfg(not(no_global_oom_handling))] use crate::string; -/// The `format` function takes an [`Arguments`] struct and returns the resulting -/// formatted string. +/// Takes an [`Arguments`] struct and returns the resulting formatted string. /// /// The [`Arguments`] instance can be created with the [`format_args!`] macro. /// diff --git a/alloc/src/lib.rs b/alloc/src/lib.rs index a7715740cbd8f..28b08ef561143 100644 --- a/alloc/src/lib.rs +++ b/alloc/src/lib.rs @@ -86,13 +86,13 @@ #![warn(multiple_supertrait_upcastable)] #![allow(internal_features)] #![allow(rustdoc::redundant_explicit_links)] +#![warn(rustdoc::unescaped_backticks)] #![deny(ffi_unwind_calls)] // // Library features: // tidy-alphabetical-start #![cfg_attr(not(no_global_oom_handling), feature(const_alloc_error))] #![cfg_attr(not(no_global_oom_handling), feature(const_btree_len))] -#![cfg_attr(test, feature(is_sorted))] #![cfg_attr(test, feature(new_uninit))] #![feature(alloc_layout_extra)] #![feature(allocator_api)] @@ -101,6 +101,7 @@ #![feature(array_windows)] #![feature(ascii_char)] #![feature(assert_matches)] +#![feature(async_closure)] #![feature(async_fn_traits)] #![feature(async_iterator)] #![feature(clone_to_uninit)] @@ -116,7 +117,6 @@ #![feature(const_pin)] #![feature(const_refs_to_cell)] #![feature(const_size_of_val)] -#![feature(const_waker)] #![feature(core_intrinsics)] #![feature(deprecated_suggestion)] #![feature(deref_pure_trait)] @@ -165,7 +165,6 @@ // // Language features: // tidy-alphabetical-start -#![cfg_attr(bootstrap, feature(c_unwind))] #![cfg_attr(not(test), feature(coroutine_trait))] #![cfg_attr(test, feature(panic_update_hook))] #![cfg_attr(test, feature(test))] diff --git a/alloc/src/raw_vec.rs b/alloc/src/raw_vec.rs index 7b7dae5a057f0..5b84df9ecef30 100644 --- a/alloc/src/raw_vec.rs +++ b/alloc/src/raw_vec.rs @@ -1,10 +1,9 @@ #![unstable(feature = "raw_vec_internals", reason = "unstable const warnings", issue = "none")] use core::alloc::LayoutError; -use core::cmp; -use core::hint; use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties}; use core::ptr::{self, NonNull, Unique}; +use core::{cmp, hint}; #[cfg(not(no_global_oom_handling))] use crate::alloc::handle_alloc_error; @@ -52,7 +51,7 @@ impl Cap { /// * Produces `Unique::dangling()` on zero-length allocations. /// * Avoids freeing `Unique::dangling()`. /// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics). -/// * Guards against 32-bit systems allocating more than isize::MAX bytes. +/// * Guards against 32-bit systems allocating more than `isize::MAX` bytes. /// * Guards against overflowing your length. /// * Calls `handle_alloc_error` for fallible allocations. /// * Contains a `ptr::Unique` and thus endows the user with all related benefits. @@ -484,7 +483,7 @@ impl RawVec { // `finish_grow` is non-generic over `T`. let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; - // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than isize::MAX items + // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than `isize::MAX` items unsafe { self.set_ptr_and_cap(ptr, cap) }; Ok(()) } @@ -504,7 +503,7 @@ impl RawVec { // `finish_grow` is non-generic over `T`. let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; - // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than isize::MAX items + // SAFETY: `finish_grow` would have resulted in a capacity overflow if we tried to allocate more than `isize::MAX` items unsafe { self.set_ptr_and_cap(ptr, cap); } diff --git a/alloc/src/raw_vec/tests.rs b/alloc/src/raw_vec/tests.rs index 4194be530612d..48c6e5f46f8db 100644 --- a/alloc/src/raw_vec/tests.rs +++ b/alloc/src/raw_vec/tests.rs @@ -1,7 +1,8 @@ -use super::*; use core::mem::size_of; use std::cell::Cell; +use super::*; + #[test] fn allocator_param() { use crate::alloc::AllocError; diff --git a/alloc/src/rc.rs b/alloc/src/rc.rs index 9982c8ea6dcbe..13d218e43a7af 100644 --- a/alloc/src/rc.rs +++ b/alloc/src/rc.rs @@ -241,25 +241,17 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[cfg(not(test))] -use crate::boxed::Box; -#[cfg(test)] -use std::boxed::Box; - use core::any::Any; -use core::borrow; use core::cell::Cell; #[cfg(not(no_global_oom_handling))] use core::clone::CloneToUninit; use core::cmp::Ordering; -use core::fmt; use core::hash::{Hash, Hasher}; -use core::hint; use core::intrinsics::abort; #[cfg(not(no_global_oom_handling))] use core::iter; use core::marker::{PhantomData, Unsize}; -use core::mem::{self, align_of_val_raw, forget, ManuallyDrop}; +use core::mem::{self, align_of_val_raw, ManuallyDrop}; use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver}; use core::panic::{RefUnwindSafe, UnwindSafe}; #[cfg(not(no_global_oom_handling))] @@ -267,11 +259,16 @@ use core::pin::Pin; use core::ptr::{self, drop_in_place, NonNull}; #[cfg(not(no_global_oom_handling))] use core::slice::from_raw_parts_mut; +use core::{borrow, fmt, hint}; +#[cfg(test)] +use std::boxed::Box; #[cfg(not(no_global_oom_handling))] use crate::alloc::handle_alloc_error; use crate::alloc::{AllocError, Allocator, Global, Layout}; use crate::borrow::{Cow, ToOwned}; +#[cfg(not(test))] +use crate::boxed::Box; #[cfg(not(no_global_oom_handling))] use crate::string::String; #[cfg(not(no_global_oom_handling))] @@ -439,7 +436,7 @@ impl Rc { /// } /// /// impl Gadget { - /// /// Construct a reference counted Gadget. + /// /// Constructs a reference counted Gadget. /// fn new() -> Rc { /// // `me` is a `Weak` pointing at the new allocation of the /// // `Rc` we're constructing. @@ -449,7 +446,7 @@ impl Rc { /// }) /// } /// - /// /// Return a reference counted pointer to Self. + /// /// Returns a reference counted pointer to Self. /// fn me(&self) -> Rc { /// self.me.upgrade().unwrap() /// } @@ -908,19 +905,18 @@ impl Rc { #[stable(feature = "rc_unique", since = "1.4.0")] pub fn try_unwrap(this: Self) -> Result { if Rc::strong_count(&this) == 1 { - unsafe { - let val = ptr::read(&*this); // copy the contained object - let alloc = ptr::read(&this.alloc); // copy the allocator - - // Indicate to Weaks that they can't be promoted by decrementing - // the strong count, and then remove the implicit "strong weak" - // pointer while also handling drop logic by just crafting a - // fake Weak. - this.inner().dec_strong(); - let _weak = Weak { ptr: this.ptr, alloc }; - forget(this); - Ok(val) - } + let this = ManuallyDrop::new(this); + + let val: T = unsafe { ptr::read(&**this) }; // copy the contained object + let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator + + // Indicate to Weaks that they can't be promoted by decrementing + // the strong count, and then remove the implicit "strong weak" + // pointer while also handling drop logic by just crafting a + // fake Weak. + this.inner().dec_strong(); + let _weak = Weak { ptr: this.ptr, alloc }; + Ok(val) } else { Err(this) } @@ -1354,9 +1350,8 @@ impl Rc { #[stable(feature = "rc_raw", since = "1.17.0")] #[rustc_never_returns_null_ptr] pub fn into_raw(this: Self) -> *const T { - let ptr = Self::as_ptr(&this); - mem::forget(this); - ptr + let this = ManuallyDrop::new(this); + Self::as_ptr(&*this) } /// Consumes the `Rc`, returning the wrapped pointer and allocator. @@ -1377,6 +1372,7 @@ impl Rc { /// let x = unsafe { Rc::from_raw_in(ptr, alloc) }; /// assert_eq!(&*x, "hello"); /// ``` + #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "allocator_api", issue = "32838")] pub fn into_raw_with_allocator(this: Self) -> (*const T, A) { let this = mem::ManuallyDrop::new(this); @@ -1902,7 +1898,7 @@ impl Rc { } impl Rc { - /// Attempt to downcast the `Rc` to a concrete type. + /// Attempts to downcast the `Rc` to a concrete type. /// /// # Examples /// @@ -2127,7 +2123,7 @@ impl Rc<[T]> { } // All clear. Forget the guard so it doesn't free the new RcBox. - forget(guard); + mem::forget(guard); Self::from_ptr(ptr) } @@ -2588,7 +2584,7 @@ impl From<[T; N]> for Rc<[T]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From<&[T]> for Rc<[T]> { - /// Allocate a reference-counted slice and fill it by cloning `v`'s items. + /// Allocates a reference-counted slice and fills it by cloning `v`'s items. /// /// # Example /// @@ -2607,7 +2603,7 @@ impl From<&[T]> for Rc<[T]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From<&str> for Rc { - /// Allocate a reference-counted string slice and copy `v` into it. + /// Allocates a reference-counted string slice and copies `v` into it. /// /// # Example /// @@ -2626,7 +2622,7 @@ impl From<&str> for Rc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From for Rc { - /// Allocate a reference-counted string slice and copy `v` into it. + /// Allocates a reference-counted string slice and copies `v` into it. /// /// # Example /// @@ -2664,7 +2660,7 @@ impl From> for Rc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From> for Rc<[T], A> { - /// Allocate a reference-counted slice and move `v`'s items into it. + /// Allocates a reference-counted slice and moves `v`'s items into it. /// /// # Example /// @@ -2697,8 +2693,8 @@ where B: ToOwned + ?Sized, Rc: From<&'a B> + From, { - /// Create a reference-counted pointer from - /// a clone-on-write pointer by copying its content. + /// Creates a reference-counted pointer from a clone-on-write pointer by + /// copying its content. /// /// # Example /// @@ -3080,9 +3076,7 @@ impl Weak { #[must_use = "losing the pointer will leak memory"] #[stable(feature = "weak_into_raw", since = "1.45.0")] pub fn into_raw(self) -> *const T { - let result = self.as_ptr(); - mem::forget(self); - result + mem::ManuallyDrop::new(self).as_ptr() } /// Consumes the `Weak`, returning the wrapped pointer and allocator. @@ -3114,6 +3108,7 @@ impl Weak { /// /// [`from_raw_in`]: Weak::from_raw_in /// [`as_ptr`]: Weak::as_ptr + #[must_use = "losing the pointer will leak memory"] #[inline] #[unstable(feature = "allocator_api", issue = "32838")] pub fn into_raw_with_allocator(self) -> (*const T, A) { @@ -3530,7 +3525,7 @@ impl AsRef for Rc { #[stable(feature = "pin", since = "1.33.0")] impl Unpin for Rc {} -/// Get the offset within an `RcBox` for the payload behind a pointer. +/// Gets the offset within an `RcBox` for the payload behind a pointer. /// /// # Safety /// @@ -3738,7 +3733,7 @@ struct UniqueRcUninit { #[cfg(not(no_global_oom_handling))] impl UniqueRcUninit { - /// Allocate a RcBox with layout suitable to contain `for_value` or a clone of it. + /// Allocates a RcBox with layout suitable to contain `for_value` or a clone of it. fn new(for_value: &T, alloc: A) -> UniqueRcUninit { let layout = Layout::for_value(for_value); let ptr = unsafe { @@ -3762,10 +3757,11 @@ impl UniqueRcUninit { /// # Safety /// /// The data must have been initialized (by writing to [`Self::data_ptr()`]). - unsafe fn into_rc(mut self) -> Rc { - let ptr = self.ptr; - let alloc = self.alloc.take().unwrap(); - mem::forget(self); + unsafe fn into_rc(self) -> Rc { + let mut this = ManuallyDrop::new(self); + let ptr = this.ptr; + let alloc = this.alloc.take().unwrap(); + // SAFETY: The pointer is valid as per `UniqueRcUninit::new`, and the caller is responsible // for having initialized the data. unsafe { Rc::from_ptr_in(ptr.as_ptr(), alloc) } diff --git a/alloc/src/rc/tests.rs b/alloc/src/rc/tests.rs index 5e2e4beb94a2b..84e8b325f71fc 100644 --- a/alloc/src/rc/tests.rs +++ b/alloc/src/rc/tests.rs @@ -1,8 +1,8 @@ -use super::*; - use std::cell::RefCell; use std::clone::Clone; +use super::*; + #[test] fn test_clone() { let x = Rc::new(RefCell::new(5)); diff --git a/alloc/src/slice.rs b/alloc/src/slice.rs index c7960b3fb49c3..7dcf344cdc5e0 100644 --- a/alloc/src/slice.rs +++ b/alloc/src/slice.rs @@ -78,7 +78,6 @@ pub use core::slice::{SplitInclusive, SplitInclusiveMut}; // N.B., see the `hack` module in this file for more details. #[cfg(test)] pub use hack::into_vec; - // HACK(japaric) needed for the implementation of `Vec::clone` during testing // N.B., see the `hack` module in this file for more details. #[cfg(test)] diff --git a/alloc/src/slice/tests.rs b/alloc/src/slice/tests.rs index 0b972a13898eb..786704caeb0ad 100644 --- a/alloc/src/slice/tests.rs +++ b/alloc/src/slice/tests.rs @@ -1,18 +1,21 @@ +use core::cell::Cell; +use core::cmp::Ordering::{self, Equal, Greater, Less}; +use core::convert::identity; +use core::sync::atomic::AtomicUsize; +use core::sync::atomic::Ordering::Relaxed; +use core::{fmt, mem}; +use std::panic; + +use rand::distributions::Standard; +use rand::prelude::*; +use rand::{Rng, RngCore}; + use crate::borrow::ToOwned; use crate::rc::Rc; use crate::string::ToString; use crate::test_helpers::test_rng; use crate::vec::Vec; -use core::cell::Cell; -use core::cmp::Ordering::{self, Equal, Greater, Less}; -use core::convert::identity; -use core::fmt; -use core::mem; -use core::sync::atomic::{AtomicUsize, Ordering::Relaxed}; -use rand::{distributions::Standard, prelude::*, Rng, RngCore}; -use std::panic; - macro_rules! do_test { ($input:ident, $func:ident) => { let len = $input.len(); diff --git a/alloc/src/str.rs b/alloc/src/str.rs index 3bb808a6c73ab..d7fba3ae159c6 100644 --- a/alloc/src/str.rs +++ b/alloc/src/str.rs @@ -9,19 +9,9 @@ use core::borrow::{Borrow, BorrowMut}; use core::iter::FusedIterator; -use core::mem; -use core::ptr; -use core::str::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher}; -use core::unicode::conversions; - -use crate::borrow::ToOwned; -use crate::boxed::Box; -use crate::slice::{Concat, Join, SliceIndex}; -use crate::string::String; -use crate::vec::Vec; - #[stable(feature = "rust1", since = "1.0.0")] pub use core::str::pattern; +use core::str::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher}; #[stable(feature = "encode_utf16", since = "1.8.0")] pub use core::str::EncodeUtf16; #[stable(feature = "split_ascii_whitespace", since = "1.34.0")] @@ -55,6 +45,14 @@ pub use core::str::{RSplitN, SplitN}; pub use core::str::{RSplitTerminator, SplitTerminator}; #[stable(feature = "utf8_chunks", since = "1.79.0")] pub use core::str::{Utf8Chunk, Utf8Chunks}; +use core::unicode::conversions; +use core::{mem, ptr}; + +use crate::borrow::ToOwned; +use crate::boxed::Box; +use crate::slice::{Concat, Join, SliceIndex}; +use crate::string::String; +use crate::vec::Vec; /// Note: `str` in `Concat` is not meaningful here. /// This type parameter of the trait only exists to enable another impl. @@ -269,7 +267,7 @@ impl str { without modifying the original"] #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String { + pub fn replace(&self, from: P, to: &str) -> String { let mut result = String::new(); let mut last_end = 0; for (start, part) in self.match_indices(from) { @@ -309,7 +307,7 @@ impl str { #[must_use = "this returns the replaced string as a new allocation, \ without modifying the original"] #[stable(feature = "str_replacen", since = "1.16.0")] - pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String { + pub fn replacen(&self, pat: P, to: &str, count: usize) -> String { // Hope to reduce the times of re-allocation let mut result = String::with_capacity(32); let mut last_end = 0; diff --git a/alloc/src/string.rs b/alloc/src/string.rs index 07ffd3e151914..124230812df56 100644 --- a/alloc/src/string.rs +++ b/alloc/src/string.rs @@ -43,8 +43,6 @@ #![stable(feature = "rust1", since = "1.0.0")] use core::error::Error; -use core::fmt; -use core::hash; #[cfg(not(no_global_oom_handling))] use core::iter::from_fn; use core::iter::FusedIterator; @@ -55,9 +53,8 @@ use core::ops::AddAssign; #[cfg(not(no_global_oom_handling))] use core::ops::Bound::{Excluded, Included, Unbounded}; use core::ops::{self, Range, RangeBounds}; -use core::ptr; -use core::slice; use core::str::pattern::Pattern; +use core::{fmt, hash, ptr, slice}; #[cfg(not(no_global_oom_handling))] use crate::alloc::Allocator; @@ -903,7 +900,7 @@ impl String { /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) }; /// assert_eq!(rebuilt, "hello"); /// ``` - #[must_use = "`self` will be dropped if the result is not used"] + #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")] pub fn into_raw_parts(self) -> (*mut u8, usize, usize) { self.vec.into_raw_parts() @@ -1497,10 +1494,7 @@ impl String { /// ``` #[cfg(not(no_global_oom_handling))] #[unstable(feature = "string_remove_matches", reason = "new API", issue = "72826")] - pub fn remove_matches<'a, P>(&'a mut self, pat: P) - where - P: for<'x> Pattern<'x>, - { + pub fn remove_matches(&mut self, pat: P) { use core::str::pattern::Searcher; let rejections = { @@ -2288,35 +2282,41 @@ impl<'a> Extend> for String { reason = "API not fully fleshed out and ready to be stabilized", issue = "27721" )] -impl<'a, 'b> Pattern<'a> for &'b String { - type Searcher = <&'b str as Pattern<'a>>::Searcher; +impl<'b> Pattern for &'b String { + type Searcher<'a> = <&'b str as Pattern>::Searcher<'a>; - fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher { + fn into_searcher(self, haystack: &str) -> <&'b str as Pattern>::Searcher<'_> { self[..].into_searcher(haystack) } #[inline] - fn is_contained_in(self, haystack: &'a str) -> bool { + fn is_contained_in(self, haystack: &str) -> bool { self[..].is_contained_in(haystack) } #[inline] - fn is_prefix_of(self, haystack: &'a str) -> bool { + fn is_prefix_of(self, haystack: &str) -> bool { self[..].is_prefix_of(haystack) } #[inline] - fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> { + fn strip_prefix_of(self, haystack: &str) -> Option<&str> { self[..].strip_prefix_of(haystack) } #[inline] - fn is_suffix_of(self, haystack: &'a str) -> bool { + fn is_suffix_of<'a>(self, haystack: &'a str) -> bool + where + Self::Searcher<'a>: core::str::pattern::ReverseSearcher<'a>, + { self[..].is_suffix_of(haystack) } #[inline] - fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> { + fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&str> + where + Self::Searcher<'a>: core::str::pattern::ReverseSearcher<'a>, + { self[..].strip_suffix_of(haystack) } } diff --git a/alloc/src/sync.rs b/alloc/src/sync.rs index a905a1e6b7e62..3ad0dae77dbde 100644 --- a/alloc/src/sync.rs +++ b/alloc/src/sync.rs @@ -9,18 +9,15 @@ //! `#[cfg(target_has_atomic = "ptr")]`. use core::any::Any; -use core::borrow; #[cfg(not(no_global_oom_handling))] use core::clone::CloneToUninit; use core::cmp::Ordering; -use core::fmt; use core::hash::{Hash, Hasher}; -use core::hint; use core::intrinsics::abort; #[cfg(not(no_global_oom_handling))] use core::iter; use core::marker::{PhantomData, Unsize}; -use core::mem::{self, align_of_val_raw}; +use core::mem::{self, align_of_val_raw, ManuallyDrop}; use core::ops::{CoerceUnsized, Deref, DerefPure, DispatchFromDyn, Receiver}; use core::panic::{RefUnwindSafe, UnwindSafe}; use core::pin::Pin; @@ -29,6 +26,7 @@ use core::ptr::{self, NonNull}; use core::slice::from_raw_parts_mut; use core::sync::atomic; use core::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use core::{borrow, fmt, hint}; #[cfg(not(no_global_oom_handling))] use crate::alloc::handle_alloc_error; @@ -428,7 +426,7 @@ impl Arc { /// } /// /// impl Gadget { - /// /// Construct a reference counted Gadget. + /// /// Constructs a reference counted Gadget. /// fn new() -> Arc { /// // `me` is a `Weak` pointing at the new allocation of the /// // `Arc` we're constructing. @@ -438,7 +436,7 @@ impl Arc { /// }) /// } /// - /// /// Return a reference counted pointer to Self. + /// /// Returns a reference counted pointer to Self. /// fn me(&self) -> Arc { /// self.me.upgrade().unwrap() /// } @@ -960,16 +958,14 @@ impl Arc { acquire!(this.inner().strong); - unsafe { - let elem = ptr::read(&this.ptr.as_ref().data); - let alloc = ptr::read(&this.alloc); // copy the allocator + let this = ManuallyDrop::new(this); + let elem: T = unsafe { ptr::read(&this.ptr.as_ref().data) }; + let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator - // Make a weak pointer to clean up the implicit strong-weak reference - let _weak = Weak { ptr: this.ptr, alloc }; - mem::forget(this); + // Make a weak pointer to clean up the implicit strong-weak reference + let _weak = Weak { ptr: this.ptr, alloc }; - Ok(elem) - } + Ok(elem) } /// Returns the inner value, if the `Arc` has exactly one strong reference. @@ -1493,9 +1489,8 @@ impl Arc { #[stable(feature = "rc_raw", since = "1.17.0")] #[rustc_never_returns_null_ptr] pub fn into_raw(this: Self) -> *const T { - let ptr = Self::as_ptr(&this); - mem::forget(this); - ptr + let this = ManuallyDrop::new(this); + Self::as_ptr(&*this) } /// Consumes the `Arc`, returning the wrapped pointer and allocator. @@ -2534,7 +2529,7 @@ unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Arc { } impl Arc { - /// Attempt to downcast the `Arc` to a concrete type. + /// Attempts to downcast the `Arc` to a concrete type. /// /// # Examples /// @@ -2801,9 +2796,7 @@ impl Weak { #[must_use = "losing the pointer will leak memory"] #[stable(feature = "weak_into_raw", since = "1.45.0")] pub fn into_raw(self) -> *const T { - let result = self.as_ptr(); - mem::forget(self); - result + ManuallyDrop::new(self).as_ptr() } /// Consumes the `Weak`, returning the wrapped pointer and allocator. @@ -3550,7 +3543,7 @@ impl From<[T; N]> for Arc<[T]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From<&[T]> for Arc<[T]> { - /// Allocate a reference-counted slice and fill it by cloning `v`'s items. + /// Allocates a reference-counted slice and fills it by cloning `v`'s items. /// /// # Example /// @@ -3569,7 +3562,7 @@ impl From<&[T]> for Arc<[T]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From<&str> for Arc { - /// Allocate a reference-counted `str` and copy `v` into it. + /// Allocates a reference-counted `str` and copies `v` into it. /// /// # Example /// @@ -3588,7 +3581,7 @@ impl From<&str> for Arc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From for Arc { - /// Allocate a reference-counted `str` and copy `v` into it. + /// Allocates a reference-counted `str` and copies `v` into it. /// /// # Example /// @@ -3626,7 +3619,7 @@ impl From> for Arc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From> for Arc<[T], A> { - /// Allocate a reference-counted slice and move `v`'s items into it. + /// Allocates a reference-counted slice and moves `v`'s items into it. /// /// # Example /// @@ -3659,8 +3652,8 @@ where B: ToOwned + ?Sized, Arc: From<&'a B> + From, { - /// Create an atomically reference-counted pointer from - /// a clone-on-write pointer by copying its content. + /// Creates an atomically reference-counted pointer from a clone-on-write + /// pointer by copying its content. /// /// # Example /// @@ -3816,7 +3809,7 @@ impl AsRef for Arc { #[stable(feature = "pin", since = "1.33.0")] impl Unpin for Arc {} -/// Get the offset within an `ArcInner` for the payload behind a pointer. +/// Gets the offset within an `ArcInner` for the payload behind a pointer. /// /// # Safety /// @@ -3838,7 +3831,7 @@ fn data_offset_align(align: usize) -> usize { layout.size() + layout.padding_needed_for(align) } -/// A unique owning pointer to a [`ArcInner`] **that does not imply the contents are initialized,** +/// A unique owning pointer to an [`ArcInner`] **that does not imply the contents are initialized,** /// but will deallocate it (without dropping the value) when dropped. /// /// This is a helper for [`Arc::make_mut()`] to ensure correct cleanup on panic. @@ -3851,7 +3844,7 @@ struct UniqueArcUninit { #[cfg(not(no_global_oom_handling))] impl UniqueArcUninit { - /// Allocate a ArcInner with layout suitable to contain `for_value` or a clone of it. + /// Allocates an ArcInner with layout suitable to contain `for_value` or a clone of it. fn new(for_value: &T, alloc: A) -> UniqueArcUninit { let layout = Layout::for_value(for_value); let ptr = unsafe { @@ -3875,13 +3868,14 @@ impl UniqueArcUninit { /// # Safety /// /// The data must have been initialized (by writing to [`Self::data_ptr()`]). - unsafe fn into_arc(mut self) -> Arc { - let ptr = self.ptr; - let alloc = self.alloc.take().unwrap(); - mem::forget(self); + unsafe fn into_arc(self) -> Arc { + let mut this = ManuallyDrop::new(self); + let ptr = this.ptr.as_ptr(); + let alloc = this.alloc.take().unwrap(); + // SAFETY: The pointer is valid as per `UniqueArcUninit::new`, and the caller is responsible // for having initialized the data. - unsafe { Arc::from_ptr_in(ptr.as_ptr(), alloc) } + unsafe { Arc::from_ptr_in(ptr, alloc) } } } diff --git a/alloc/src/sync/tests.rs b/alloc/src/sync/tests.rs index 1b123aa58f205..d6b3de875771e 100644 --- a/alloc/src/sync/tests.rs +++ b/alloc/src/sync/tests.rs @@ -1,5 +1,3 @@ -use super::*; - use std::clone::Clone; use std::mem::MaybeUninit; use std::option::Option::None; @@ -9,6 +7,8 @@ use std::sync::mpsc::channel; use std::sync::Mutex; use std::thread; +use super::*; + struct Canary(*mut AtomicUsize); impl Drop for Canary { diff --git a/alloc/src/task.rs b/alloc/src/task.rs index a3fa6585a37f8..27589aed2f97c 100644 --- a/alloc/src/task.rs +++ b/alloc/src/task.rs @@ -7,14 +7,14 @@ //! This may be detected at compile time using //! `#[cfg(target_has_atomic = "ptr")]`. -use crate::rc::Rc; use core::mem::ManuallyDrop; +#[cfg(target_has_atomic = "ptr")] +use core::task::Waker; use core::task::{LocalWaker, RawWaker, RawWakerVTable}; +use crate::rc::Rc; #[cfg(target_has_atomic = "ptr")] use crate::sync::Arc; -#[cfg(target_has_atomic = "ptr")] -use core::task::Waker; /// The implementation of waking a task on an executor. /// diff --git a/alloc/src/testing/crash_test.rs b/alloc/src/testing/crash_test.rs index ff72f99b2cbed..684bac60d9a86 100644 --- a/alloc/src/testing/crash_test.rs +++ b/alloc/src/testing/crash_test.rs @@ -1,6 +1,8 @@ -use crate::fmt::Debug; // the `Debug` trait is the only thing we use from `crate::fmt` use std::cmp::Ordering; -use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering::SeqCst; + +use crate::fmt::Debug; // the `Debug` trait is the only thing we use from `crate::fmt` /// A blueprint for crash test dummy instances that monitor particular events. /// Some instances may be configured to panic at some point. diff --git a/alloc/src/tests.rs b/alloc/src/tests.rs index ab256ceaec353..b95d11cb07ec8 100644 --- a/alloc/src/tests.rs +++ b/alloc/src/tests.rs @@ -2,7 +2,6 @@ use core::any::Any; use core::ops::Deref; - use std::boxed::Box; #[test] diff --git a/alloc/src/vec/cow.rs b/alloc/src/vec/cow.rs index 3fe83242a30ad..c18091705a636 100644 --- a/alloc/src/vec/cow.rs +++ b/alloc/src/vec/cow.rs @@ -1,6 +1,5 @@ -use crate::borrow::Cow; - use super::Vec; +use crate::borrow::Cow; #[stable(feature = "cow_from_vec", since = "1.8.0")] impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> { diff --git a/alloc/src/vec/drain.rs b/alloc/src/vec/drain.rs index f0b63759ac70f..9362cef2a1b00 100644 --- a/alloc/src/vec/drain.rs +++ b/alloc/src/vec/drain.rs @@ -1,4 +1,3 @@ -use crate::alloc::{Allocator, Global}; use core::fmt; use core::iter::{FusedIterator, TrustedLen}; use core::mem::{self, ManuallyDrop, SizedTypeProperties}; @@ -6,6 +5,7 @@ use core::ptr::{self, NonNull}; use core::slice::{self}; use super::Vec; +use crate::alloc::{Allocator, Global}; /// A draining iterator for `Vec`. /// diff --git a/alloc/src/vec/extract_if.rs b/alloc/src/vec/extract_if.rs index 118cfdb36b9c2..72d51e8904488 100644 --- a/alloc/src/vec/extract_if.rs +++ b/alloc/src/vec/extract_if.rs @@ -1,8 +1,7 @@ -use crate::alloc::{Allocator, Global}; -use core::ptr; -use core::slice; +use core::{ptr, slice}; use super::Vec; +use crate::alloc::{Allocator, Global}; /// An iterator which uses a closure to determine if an element should be removed. /// diff --git a/alloc/src/vec/in_place_collect.rs b/alloc/src/vec/in_place_collect.rs index 0dc193d82c535..d119e6ca397c5 100644 --- a/alloc/src/vec/in_place_collect.rs +++ b/alloc/src/vec/in_place_collect.rs @@ -155,9 +155,7 @@ //! vec.truncate(write_idx); //! ``` -use crate::alloc::{handle_alloc_error, Global}; -use core::alloc::Allocator; -use core::alloc::Layout; +use core::alloc::{Allocator, Layout}; use core::iter::{InPlaceIterable, SourceIter, TrustedRandomAccessNoCoerce}; use core::marker::PhantomData; use core::mem::{self, ManuallyDrop, SizedTypeProperties}; @@ -165,6 +163,7 @@ use core::num::NonZero; use core::ptr; use super::{InPlaceDrop, InPlaceDstDataSrcBufDrop, SpecFromIter, SpecFromIterNested, Vec}; +use crate::alloc::{handle_alloc_error, Global}; const fn in_place_collectible( step_merge: Option>, diff --git a/alloc/src/vec/in_place_drop.rs b/alloc/src/vec/in_place_drop.rs index 4050c250130bb..27f7597931045 100644 --- a/alloc/src/vec/in_place_drop.rs +++ b/alloc/src/vec/in_place_drop.rs @@ -1,6 +1,5 @@ use core::marker::PhantomData; -use core::ptr::NonNull; -use core::ptr::{self, drop_in_place}; +use core::ptr::{self, drop_in_place, NonNull}; use core::slice::{self}; use crate::alloc::Global; diff --git a/alloc/src/vec/into_iter.rs b/alloc/src/vec/into_iter.rs index 10f62e4bb62d8..fad8abad49353 100644 --- a/alloc/src/vec/into_iter.rs +++ b/alloc/src/vec/into_iter.rs @@ -1,11 +1,3 @@ -#[cfg(not(no_global_oom_handling))] -use super::AsVecIntoIter; -use crate::alloc::{Allocator, Global}; -#[cfg(not(no_global_oom_handling))] -use crate::collections::VecDeque; -use crate::raw_vec::RawVec; -use core::array; -use core::fmt; use core::iter::{ FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen, TrustedRandomAccessNoCoerce, @@ -17,6 +9,14 @@ use core::num::NonZero; use core::ops::Deref; use core::ptr::{self, NonNull}; use core::slice::{self}; +use core::{array, fmt}; + +#[cfg(not(no_global_oom_handling))] +use super::AsVecIntoIter; +use crate::alloc::{Allocator, Global}; +#[cfg(not(no_global_oom_handling))] +use crate::collections::VecDeque; +use crate::raw_vec::RawVec; macro non_null { (mut $place:expr, $t:ident) => {{ @@ -114,8 +114,9 @@ impl IntoIter { } /// Drops remaining elements and relinquishes the backing allocation. - /// This method guarantees it won't panic before relinquishing - /// the backing allocation. + /// + /// This method guarantees it won't panic before relinquishing the backing + /// allocation. /// /// This is roughly equivalent to the following, but more efficient /// diff --git a/alloc/src/vec/mod.rs b/alloc/src/vec/mod.rs index 729d5dd4fe4d2..b4e0bc5fcbe41 100644 --- a/alloc/src/vec/mod.rs +++ b/alloc/src/vec/mod.rs @@ -66,15 +66,14 @@ use core::ops::{self, Index, IndexMut, Range, RangeBounds}; use core::ptr::{self, NonNull}; use core::slice::{self, SliceIndex}; +#[unstable(feature = "extract_if", reason = "recently added", issue = "43244")] +pub use self::extract_if::ExtractIf; use crate::alloc::{Allocator, Global}; use crate::borrow::{Cow, ToOwned}; use crate::boxed::Box; use crate::collections::TryReserveError; use crate::raw_vec::RawVec; -#[unstable(feature = "extract_if", reason = "recently added", issue = "43244")] -pub use self::extract_if::ExtractIf; - mod extract_if; #[cfg(not(no_global_oom_handling))] @@ -879,6 +878,7 @@ impl Vec { /// }; /// assert_eq!(rebuilt, [4294967295, 0, 1]); /// ``` + #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")] pub fn into_raw_parts(self) -> (*mut T, usize, usize) { let mut me = ManuallyDrop::new(self); @@ -922,6 +922,7 @@ impl Vec { /// }; /// assert_eq!(rebuilt, [4294967295, 0, 1]); /// ``` + #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "allocator_api", issue = "32838")] // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")] pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) { @@ -1277,7 +1278,7 @@ impl Vec { /// valid for zero sized reads if the vector didn't allocate. /// /// The caller must ensure that the vector outlives the pointer this - /// function returns, or else it will end up pointing to garbage. + /// function returns, or else it will end up dangling. /// Modifying the vector may cause its buffer to be reallocated, /// which would also make any pointers to it invalid. /// @@ -1337,7 +1338,7 @@ impl Vec { /// raw pointer valid for zero sized reads if the vector didn't allocate. /// /// The caller must ensure that the vector outlives the pointer this - /// function returns, or else it will end up pointing to garbage. + /// function returns, or else it will end up dangling. /// Modifying the vector may cause its buffer to be reallocated, /// which would also make any pointers to it invalid. /// @@ -1711,6 +1712,12 @@ impl Vec { F: FnMut(&mut T) -> bool, { let original_len = self.len(); + + if original_len == 0 { + // Empty case: explicit return allows better optimization, vs letting compiler infer it + return; + } + // Avoid double drop if the drop guard is not executed, // since we may make some holes during the process. unsafe { self.set_len(0) }; @@ -2373,9 +2380,11 @@ impl Vec { } /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, - /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime - /// `'a`. If the type has only static references, or none at all, then this - /// may be chosen to be `'static`. + /// `&'a mut [T]`. + /// + /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type + /// has only static references, or none at all, then this may be chosen to be + /// `'static`. /// /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, /// so the leaked allocation may include unused capacity that is not part @@ -3359,7 +3368,7 @@ impl AsMut<[T]> for Vec { #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl From<&[T]> for Vec { - /// Allocate a `Vec` and fill it by cloning `s`'s items. + /// Allocates a `Vec` and fills it by cloning `s`'s items. /// /// # Examples /// @@ -3379,7 +3388,7 @@ impl From<&[T]> for Vec { #[cfg(not(no_global_oom_handling))] #[stable(feature = "vec_from_mut", since = "1.19.0")] impl From<&mut [T]> for Vec { - /// Allocate a `Vec` and fill it by cloning `s`'s items. + /// Allocates a `Vec` and fills it by cloning `s`'s items. /// /// # Examples /// @@ -3399,7 +3408,7 @@ impl From<&mut [T]> for Vec { #[cfg(not(no_global_oom_handling))] #[stable(feature = "vec_from_array_ref", since = "1.74.0")] impl From<&[T; N]> for Vec { - /// Allocate a `Vec` and fill it by cloning `s`'s items. + /// Allocates a `Vec` and fills it by cloning `s`'s items. /// /// # Examples /// @@ -3414,7 +3423,7 @@ impl From<&[T; N]> for Vec { #[cfg(not(no_global_oom_handling))] #[stable(feature = "vec_from_array_ref", since = "1.74.0")] impl From<&mut [T; N]> for Vec { - /// Allocate a `Vec` and fill it by cloning `s`'s items. + /// Allocates a `Vec` and fills it by cloning `s`'s items. /// /// # Examples /// @@ -3429,7 +3438,7 @@ impl From<&mut [T; N]> for Vec { #[cfg(not(no_global_oom_handling))] #[stable(feature = "vec_from_array", since = "1.44.0")] impl From<[T; N]> for Vec { - /// Allocate a `Vec` and move `s`'s items into it. + /// Allocates a `Vec` and moves `s`'s items into it. /// /// # Examples /// @@ -3452,7 +3461,7 @@ impl<'a, T> From> for Vec where [T]: ToOwned>, { - /// Convert a clone-on-write slice into a vector. + /// Converts a clone-on-write slice into a vector. /// /// If `s` already owns a `Vec`, it will be returned directly. /// If `s` is borrowing a slice, a new `Vec` will be allocated and @@ -3475,7 +3484,7 @@ where #[cfg(not(test))] #[stable(feature = "vec_from_box", since = "1.18.0")] impl From> for Vec { - /// Convert a boxed slice into a vector by transferring ownership of + /// Converts a boxed slice into a vector by transferring ownership of /// the existing heap allocation. /// /// # Examples @@ -3494,7 +3503,7 @@ impl From> for Vec { #[cfg(not(test))] #[stable(feature = "box_from_vec", since = "1.20.0")] impl From> for Box<[T], A> { - /// Convert a vector into a boxed slice. + /// Converts a vector into a boxed slice. /// /// Before doing the conversion, this method discards excess capacity like [`Vec::shrink_to_fit`]. /// @@ -3522,7 +3531,7 @@ impl From> for Box<[T], A> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl From<&str> for Vec { - /// Allocate a `Vec` and fill it with a UTF-8 string. + /// Allocates a `Vec` and fills it with a UTF-8 string. /// /// # Examples /// diff --git a/alloc/src/vec/partial_eq.rs b/alloc/src/vec/partial_eq.rs index b0cf72577a1be..5e620c4b2efe7 100644 --- a/alloc/src/vec/partial_eq.rs +++ b/alloc/src/vec/partial_eq.rs @@ -1,9 +1,8 @@ +use super::Vec; use crate::alloc::Allocator; #[cfg(not(no_global_oom_handling))] use crate::borrow::Cow; -use super::Vec; - macro_rules! __impl_slice_eq1 { ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => { #[$stability] diff --git a/alloc/src/vec/spec_extend.rs b/alloc/src/vec/spec_extend.rs index e2f865d0f7167..7085bceef5baa 100644 --- a/alloc/src/vec/spec_extend.rs +++ b/alloc/src/vec/spec_extend.rs @@ -1,8 +1,8 @@ -use crate::alloc::Allocator; use core::iter::TrustedLen; use core::slice::{self}; use super::{IntoIter, Vec}; +use crate::alloc::Allocator; // Specialization trait used for Vec::extend pub(super) trait SpecExtend { diff --git a/alloc/src/vec/spec_from_elem.rs b/alloc/src/vec/spec_from_elem.rs index 01a6db14474bb..96d701e15d487 100644 --- a/alloc/src/vec/spec_from_elem.rs +++ b/alloc/src/vec/spec_from_elem.rs @@ -1,10 +1,9 @@ use core::ptr; +use super::{IsZero, Vec}; use crate::alloc::Allocator; use crate::raw_vec::RawVec; -use super::{IsZero, Vec}; - // Specialization trait used for Vec::from_elem pub(super) trait SpecFromElem: Sized { fn from_elem(elem: Self, n: usize, alloc: A) -> Vec; diff --git a/alloc/src/vec/spec_from_iter_nested.rs b/alloc/src/vec/spec_from_iter_nested.rs index f915ebb86e5a5..77f7761d22f95 100644 --- a/alloc/src/vec/spec_from_iter_nested.rs +++ b/alloc/src/vec/spec_from_iter_nested.rs @@ -1,10 +1,8 @@ -use core::cmp; use core::iter::TrustedLen; -use core::ptr; - -use crate::raw_vec::RawVec; +use core::{cmp, ptr}; use super::{SpecExtend, Vec}; +use crate::raw_vec::RawVec; /// Another specialization trait for Vec::from_iter /// necessary to manually prioritize overlapping specializations diff --git a/alloc/src/vec/splice.rs b/alloc/src/vec/splice.rs index 852fdcc3f5ce7..9e36377c148d2 100644 --- a/alloc/src/vec/splice.rs +++ b/alloc/src/vec/splice.rs @@ -1,8 +1,8 @@ -use crate::alloc::{Allocator, Global}; use core::ptr::{self}; use core::slice::{self}; use super::{Drain, Vec}; +use crate::alloc::{Allocator, Global}; /// A splicing iterator for `Vec`. /// diff --git a/alloc/tests/btree_set_hash.rs b/alloc/tests/btree_set_hash.rs index ab275ac4353ac..71a3a143209ff 100644 --- a/alloc/tests/btree_set_hash.rs +++ b/alloc/tests/btree_set_hash.rs @@ -1,6 +1,7 @@ -use crate::hash; use std::collections::BTreeSet; +use crate::hash; + #[test] fn test_hash() { let mut x = BTreeSet::new(); diff --git a/alloc/tests/slice.rs b/alloc/tests/slice.rs index c0f7a11a93e12..df5a8af16fd70 100644 --- a/alloc/tests/slice.rs +++ b/alloc/tests/slice.rs @@ -1,9 +1,7 @@ use std::cmp::Ordering::{Equal, Greater, Less}; use std::convert::identity; -use std::fmt; -use std::mem; -use std::panic; use std::rc::Rc; +use std::{fmt, mem, panic}; fn square(n: usize) -> usize { n * n @@ -911,8 +909,7 @@ fn test_split_iterators_size_hint() { // become maximally long, so the size_hint upper bounds are tight ((|_| true) as fn(&_) -> _, Bounds::Upper), ] { - use assert_tight_size_hints as a; - use format_args as f; + use {assert_tight_size_hints as a, format_args as f}; a(v.split(p), b, "split"); a(v.split_mut(p), b, "split_mut"); diff --git a/alloc/tests/str.rs b/alloc/tests/str.rs index 0078f5eaa3d2b..a6b1fe5b97945 100644 --- a/alloc/tests/str.rs +++ b/alloc/tests/str.rs @@ -165,7 +165,8 @@ fn test_join_for_different_lengths_with_long_separator() { #[test] fn test_join_issue_80335() { - use core::{borrow::Borrow, cell::Cell}; + use core::borrow::Borrow; + use core::cell::Cell; struct WeirdBorrow { state: Cell, @@ -1927,12 +1928,10 @@ mod pattern { } } - fn cmp_search_to_vec<'a>( - rev: bool, - pat: impl Pattern<'a, Searcher: ReverseSearcher<'a>>, - haystack: &'a str, - right: Vec, - ) { + fn cmp_search_to_vec

(rev: bool, pat: P, haystack: &str, right: Vec) + where + P: for<'a> Pattern: ReverseSearcher<'a>>, + { let mut searcher = pat.into_searcher(haystack); let mut v = vec![]; loop { @@ -2191,9 +2190,9 @@ generate_iterator_test! { fn different_str_pattern_forwarding_lifetimes() { use std::str::pattern::Pattern; - fn foo<'a, P>(p: P) + fn foo

(p: P) where - for<'b> &'b P: Pattern<'a>, + for<'b> &'b P: Pattern, { for _ in 0..3 { "asdf".find(&p); diff --git a/alloc/tests/string.rs b/alloc/tests/string.rs index e20ceae87b0d5..c5bc4185a3670 100644 --- a/alloc/tests/string.rs +++ b/alloc/tests/string.rs @@ -2,11 +2,9 @@ use std::assert_matches::assert_matches; use std::borrow::Cow; use std::cell::Cell; use std::collections::TryReserveErrorKind::*; -use std::ops::Bound; use std::ops::Bound::*; -use std::ops::RangeBounds; -use std::panic; -use std::str; +use std::ops::{Bound, RangeBounds}; +use std::{panic, str}; pub trait IntoCow<'a, B: ?Sized> where diff --git a/alloc/tests/vec.rs b/alloc/tests/vec.rs index 71d79893e01d7..fd2ddbf59e42d 100644 --- a/alloc/tests/vec.rs +++ b/alloc/tests/vec.rs @@ -8,15 +8,14 @@ use std::borrow::Cow; use std::cell::Cell; use std::collections::TryReserveErrorKind::*; use std::fmt::Debug; -use std::hint; use std::iter::InPlaceIterable; -use std::mem; use std::mem::{size_of, swap}; use std::ops::Bound::*; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::rc::Rc; use std::sync::atomic::{AtomicU32, Ordering}; use std::vec::{Drain, IntoIter}; +use std::{hint, mem}; struct DropCounter<'a> { count: &'a mut u32, @@ -2572,7 +2571,8 @@ fn test_into_flattened_size_overflow() { #[test] fn test_box_zero_allocator() { - use core::{alloc::AllocError, cell::RefCell}; + use core::alloc::AllocError; + use core::cell::RefCell; use std::collections::HashSet; // Track ZST allocations and ensure that they all have a matching free. diff --git a/alloc/tests/vec_deque.rs b/alloc/tests/vec_deque.rs index cea5de4dd5984..db972122fef2a 100644 --- a/alloc/tests/vec_deque.rs +++ b/alloc/tests/vec_deque.rs @@ -1,16 +1,17 @@ use core::num::NonZero; use std::assert_matches::assert_matches; +use std::collections::vec_deque::Drain; use std::collections::TryReserveErrorKind::*; -use std::collections::{vec_deque::Drain, VecDeque}; +use std::collections::VecDeque; use std::fmt::Debug; use std::ops::Bound::*; use std::panic::{catch_unwind, AssertUnwindSafe}; -use crate::hash; - use Taggy::*; use Taggypar::*; +use crate::hash; + #[test] fn test_simple() { let mut d = VecDeque::new(); diff --git a/alloc/tests/vec_deque_alloc_error.rs b/alloc/tests/vec_deque_alloc_error.rs index 8b516ddbc5c55..c41d8266eb457 100644 --- a/alloc/tests/vec_deque_alloc_error.rs +++ b/alloc/tests/vec_deque_alloc_error.rs @@ -1,11 +1,9 @@ #![feature(alloc_error_hook, allocator_api)] -use std::{ - alloc::{set_alloc_error_hook, AllocError, Allocator, Layout, System}, - collections::VecDeque, - panic::{catch_unwind, AssertUnwindSafe}, - ptr::NonNull, -}; +use std::alloc::{set_alloc_error_hook, AllocError, Allocator, Layout, System}; +use std::collections::VecDeque; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::ptr::NonNull; #[test] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] diff --git a/core/benches/any.rs b/core/benches/any.rs index 53099b78266f8..f6be41bcdbfa7 100644 --- a/core/benches/any.rs +++ b/core/benches/any.rs @@ -1,4 +1,5 @@ use core::any::*; + use test::{black_box, Bencher}; #[bench] diff --git a/core/benches/array.rs b/core/benches/array.rs index d8cc44d05c4ba..b1a41a088c493 100644 --- a/core/benches/array.rs +++ b/core/benches/array.rs @@ -1,5 +1,4 @@ -use test::black_box; -use test::Bencher; +use test::{black_box, Bencher}; macro_rules! map_array { ($func_name:ident, $start_item: expr, $map_item: expr, $arr_size: expr) => { diff --git a/core/benches/ascii.rs b/core/benches/ascii.rs index 71ec9fed2fe75..61bf8bbf411d5 100644 --- a/core/benches/ascii.rs +++ b/core/benches/ascii.rs @@ -64,8 +64,8 @@ macro_rules! benches { } use std::fmt::Write; -use test::black_box; -use test::Bencher; + +use test::{black_box, Bencher}; const ASCII_CASE_MASK: u8 = 0b0010_0000; diff --git a/core/benches/ascii/is_ascii.rs b/core/benches/ascii/is_ascii.rs index a42a1dcfe3988..05f60a46f8be2 100644 --- a/core/benches/ascii/is_ascii.rs +++ b/core/benches/ascii/is_ascii.rs @@ -1,6 +1,6 @@ +use test::{black_box, Bencher}; + use super::{LONG, MEDIUM, SHORT}; -use test::black_box; -use test::Bencher; macro_rules! benches { ($( fn $name: ident($arg: ident: &[u8]) $body: block )+) => { diff --git a/core/benches/fmt.rs b/core/benches/fmt.rs index d1cdb12e50f8c..906d7ac3eef28 100644 --- a/core/benches/fmt.rs +++ b/core/benches/fmt.rs @@ -1,5 +1,6 @@ use std::fmt::{self, Write as FmtWrite}; use std::io::{self, Write as IoWrite}; + use test::{black_box, Bencher}; #[bench] diff --git a/core/benches/hash/sip.rs b/core/benches/hash/sip.rs index 725c864dce9f1..8e8c07b6ee4c3 100644 --- a/core/benches/hash/sip.rs +++ b/core/benches/hash/sip.rs @@ -1,6 +1,7 @@ #![allow(deprecated)] use core::hash::*; + use test::{black_box, Bencher}; fn hash_bytes(mut s: H, x: &[u8]) -> u64 { diff --git a/core/benches/iter.rs b/core/benches/iter.rs index c1cec5e6d3c8c..24469ba0c4262 100644 --- a/core/benches/iter.rs +++ b/core/benches/iter.rs @@ -3,6 +3,7 @@ use core::iter::*; use core::mem; use core::num::Wrapping; use core::ops::Range; + use test::{black_box, Bencher}; #[bench] diff --git a/core/benches/num/flt2dec/mod.rs b/core/benches/num/flt2dec/mod.rs index b1a9fc56bae54..6c7de5dcd2286 100644 --- a/core/benches/num/flt2dec/mod.rs +++ b/core/benches/num/flt2dec/mod.rs @@ -3,9 +3,9 @@ mod strategy { mod grisu; } -use core::num::flt2dec::MAX_SIG_DIGITS; -use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded}; +use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded, MAX_SIG_DIGITS}; use std::io::Write; + use test::{black_box, Bencher}; pub fn decode_finite(v: T) -> Decoded { diff --git a/core/benches/num/flt2dec/strategy/dragon.rs b/core/benches/num/flt2dec/strategy/dragon.rs index babedc6c0ec80..4526697140365 100644 --- a/core/benches/num/flt2dec/strategy/dragon.rs +++ b/core/benches/num/flt2dec/strategy/dragon.rs @@ -1,7 +1,8 @@ -use super::super::*; use core::num::flt2dec::strategy::dragon::*; use std::mem::MaybeUninit; +use super::super::*; + #[bench] fn bench_small_shortest(b: &mut Bencher) { let decoded = decode_finite(3.141592f64); diff --git a/core/benches/num/flt2dec/strategy/grisu.rs b/core/benches/num/flt2dec/strategy/grisu.rs index b5bddb2c7c746..d20f9b02f7e74 100644 --- a/core/benches/num/flt2dec/strategy/grisu.rs +++ b/core/benches/num/flt2dec/strategy/grisu.rs @@ -1,7 +1,8 @@ -use super::super::*; use core::num::flt2dec::strategy::grisu::*; use std::mem::MaybeUninit; +use super::super::*; + pub fn decode_finite(v: T) -> Decoded { match decode(v).1 { FullDecoded::Finite(decoded) => decoded, diff --git a/core/benches/num/mod.rs b/core/benches/num/mod.rs index 4922ee150d95f..c1dc3a3062256 100644 --- a/core/benches/num/mod.rs +++ b/core/benches/num/mod.rs @@ -4,6 +4,7 @@ mod int_log; mod int_pow; use std::str::FromStr; + use test::{black_box, Bencher}; const ASCII_NUMBERS: [&str; 19] = [ diff --git a/core/benches/ops.rs b/core/benches/ops.rs index 0a2be8a28819f..3d0b3302957bf 100644 --- a/core/benches/ops.rs +++ b/core/benches/ops.rs @@ -1,4 +1,5 @@ use core::ops::*; + use test::Bencher; // Overhead of dtors diff --git a/core/benches/pattern.rs b/core/benches/pattern.rs index 480ac6f36d202..0d60b005feb32 100644 --- a/core/benches/pattern.rs +++ b/core/benches/pattern.rs @@ -1,5 +1,4 @@ -use test::black_box; -use test::Bencher; +use test::{black_box, Bencher}; #[bench] fn starts_with_char(b: &mut Bencher) { diff --git a/core/benches/slice.rs b/core/benches/slice.rs index 8f87a211449c0..2741dbd53f14c 100644 --- a/core/benches/slice.rs +++ b/core/benches/slice.rs @@ -1,6 +1,6 @@ use core::ptr::NonNull; -use test::black_box; -use test::Bencher; + +use test::{black_box, Bencher}; enum Cache { L1, diff --git a/core/benches/str.rs b/core/benches/str.rs index 0f14809444bc5..a8178f9c18752 100644 --- a/core/benches/str.rs +++ b/core/benches/str.rs @@ -1,4 +1,5 @@ use std::str; + use test::{black_box, Bencher}; mod char_count; diff --git a/core/benches/str/char_count.rs b/core/benches/str/char_count.rs index 25d9b2e299223..b87ad0f6adf24 100644 --- a/core/benches/str/char_count.rs +++ b/core/benches/str/char_count.rs @@ -1,6 +1,7 @@ -use super::corpora::*; use test::{black_box, Bencher}; +use super::corpora::*; + macro_rules! define_benches { ($( fn $name: ident($arg: ident: &str) $body: block )+) => { define_benches!(mod en_tiny, en::TINY, $($name $arg $body)+); diff --git a/core/benches/str/debug.rs b/core/benches/str/debug.rs index cb91169eed8eb..6dbf4e92c084b 100644 --- a/core/benches/str/debug.rs +++ b/core/benches/str/debug.rs @@ -4,6 +4,7 @@ //! we should still try to minimize those calls over time rather than regress them. use std::fmt::{self, Write}; + use test::{black_box, Bencher}; #[derive(Default)] diff --git a/core/benches/str/iter.rs b/core/benches/str/iter.rs index 58ae71fc10f12..f6e73e48d8e7d 100644 --- a/core/benches/str/iter.rs +++ b/core/benches/str/iter.rs @@ -1,6 +1,7 @@ -use super::corpora; use test::{black_box, Bencher}; +use super::corpora; + #[bench] fn chars_advance_by_1000(b: &mut Bencher) { b.iter(|| black_box(corpora::ru::LARGE).chars().advance_by(1000)); diff --git a/core/src/alloc/global.rs b/core/src/alloc/global.rs index 8df3ace54ffe1..a6f799c4a7deb 100644 --- a/core/src/alloc/global.rs +++ b/core/src/alloc/global.rs @@ -1,6 +1,5 @@ use crate::alloc::Layout; -use crate::cmp; -use crate::ptr; +use crate::{cmp, ptr}; /// A memory allocator that can be registered as the standard library’s default /// through the `#[global_allocator]` attribute. @@ -118,7 +117,7 @@ use crate::ptr; /// having side effects. #[stable(feature = "global_alloc", since = "1.28.0")] pub unsafe trait GlobalAlloc { - /// Allocate memory as described by the given `layout`. + /// Allocates memory as described by the given `layout`. /// /// Returns a pointer to newly-allocated memory, /// or null to indicate allocation failure. @@ -153,7 +152,7 @@ pub unsafe trait GlobalAlloc { #[stable(feature = "global_alloc", since = "1.28.0")] unsafe fn alloc(&self, layout: Layout) -> *mut u8; - /// Deallocate the block of memory at the given `ptr` pointer with the given `layout`. + /// Deallocates the block of memory at the given `ptr` pointer with the given `layout`. /// /// # Safety /// @@ -200,7 +199,7 @@ pub unsafe trait GlobalAlloc { ptr } - /// Shrink or grow a block of memory to the given `new_size` in bytes. + /// Shrinks or grows a block of memory to the given `new_size` in bytes. /// The block is described by the given `ptr` pointer and `layout`. /// /// If this returns a non-null pointer, then ownership of the memory block @@ -232,7 +231,7 @@ pub unsafe trait GlobalAlloc { /// * `new_size` must be greater than zero. /// /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`, - /// must not overflow isize (i.e., the rounded value must be less than or + /// must not overflow `isize` (i.e., the rounded value must be less than or /// equal to `isize::MAX`). /// /// (Extension subtraits might provide more specific bounds on diff --git a/core/src/alloc/layout.rs b/core/src/alloc/layout.rs index 0b92767c93205..549a4bc6727fc 100644 --- a/core/src/alloc/layout.rs +++ b/core/src/alloc/layout.rs @@ -4,11 +4,9 @@ // collections, resulting in having to optimize down excess IR multiple times. // Your performance intuition is useless. Run perf. -use crate::cmp; use crate::error::Error; -use crate::fmt; -use crate::mem; use crate::ptr::{Alignment, NonNull}; +use crate::{cmp, fmt, mem}; // While this function is used in one place and its implementation // could be inlined, the previous attempts to do so made rustc @@ -26,7 +24,7 @@ const fn size_align() -> (usize, usize) { /// You build a `Layout` up as an input to give to an allocator. /// /// All layouts have an associated size and a power-of-two alignment. The size, when rounded up to -/// the nearest multiple of `align`, does not overflow isize (i.e., the rounded value will always be +/// the nearest multiple of `align`, does not overflow `isize` (i.e., the rounded value will always be /// less than or equal to `isize::MAX`). /// /// (Note that layouts are *not* required to have non-zero size, @@ -61,7 +59,7 @@ impl Layout { /// * `align` must be a power of two, /// /// * `size`, when rounded up to the nearest multiple of `align`, - /// must not overflow isize (i.e., the rounded value must be + /// must not overflow `isize` (i.e., the rounded value must be /// less than or equal to `isize::MAX`). #[stable(feature = "alloc_layout", since = "1.28.0")] #[rustc_const_stable(feature = "const_alloc_layout_size_align", since = "1.50.0")] @@ -183,6 +181,8 @@ impl Layout { /// - a [slice], then the length of the slice tail must be an initialized /// integer, and the size of the *entire value* /// (dynamic tail length + statically sized prefix) must fit in `isize`. + /// For the special case where the dynamic tail length is 0, this function + /// is safe to call. /// - a [trait object], then the vtable part of the pointer must point /// to a valid vtable for the type `T` acquired by an unsizing coercion, /// and the size of the *entire value* diff --git a/core/src/alloc/mod.rs b/core/src/alloc/mod.rs index 1c8e667654469..aa841db045ce7 100644 --- a/core/src/alloc/mod.rs +++ b/core/src/alloc/mod.rs @@ -17,10 +17,8 @@ pub use self::layout::Layout; )] #[allow(deprecated, deprecated_in_future)] pub use self::layout::LayoutErr; - #[stable(feature = "alloc_layout_error", since = "1.50.0")] pub use self::layout::LayoutError; - use crate::error::Error; use crate::fmt; use crate::ptr::{self, NonNull}; diff --git a/core/src/any.rs b/core/src/any.rs index 59f3b6841d531..58107b1e7d074 100644 --- a/core/src/any.rs +++ b/core/src/any.rs @@ -86,9 +86,7 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::fmt; -use crate::hash; -use crate::intrinsics; +use crate::{fmt, hash, intrinsics}; /////////////////////////////////////////////////////////////////////////////// // Any trait diff --git a/core/src/arch.rs b/core/src/arch.rs index 31d6bc36fc8b9..d681bd124fe13 100644 --- a/core/src/arch.rs +++ b/core/src/arch.rs @@ -4,6 +4,15 @@ #[stable(feature = "simd_arch", since = "1.27.0")] pub use crate::core_arch::arch::*; +#[cfg(bootstrap)] +#[allow(dead_code)] +#[unstable(feature = "sha512_sm_x86", issue = "126624")] +fn dummy() { + // AArch64 also has a target feature named `sm4`, so we need `#![feature(sha512_sm_x86)]` in lib.rs + // But as the bootstrap compiler doesn't know about this feature yet, we need to convert it to a + // library feature until bootstrap gets bumped +} + /// Inline assembly. /// /// Refer to [Rust By Example] for a usage guide and the [reference] for diff --git a/core/src/array/ascii.rs b/core/src/array/ascii.rs index 3fea9a44049fb..05797b042ee4a 100644 --- a/core/src/array/ascii.rs +++ b/core/src/array/ascii.rs @@ -2,7 +2,7 @@ use crate::ascii; #[cfg(not(test))] impl [u8; N] { - /// Converts this array of bytes into a array of ASCII characters, + /// Converts this array of bytes into an array of ASCII characters, /// or returns `None` if any of the characters is non-ASCII. /// /// # Examples @@ -29,7 +29,7 @@ impl [u8; N] { } } - /// Converts this array of bytes into a array of ASCII characters, + /// Converts this array of bytes into an array of ASCII characters, /// without checking whether they're valid. /// /// # Safety diff --git a/core/src/array/iter.rs b/core/src/array/iter.rs index 3585bf07b597c..2d19e4876f680 100644 --- a/core/src/array/iter.rs +++ b/core/src/array/iter.rs @@ -1,14 +1,11 @@ //! Defines the `IntoIter` owned iterator for arrays. +use crate::intrinsics::transmute_unchecked; +use crate::iter::{self, FusedIterator, TrustedLen, TrustedRandomAccessNoCoerce}; +use crate::mem::MaybeUninit; use crate::num::NonZero; -use crate::{ - fmt, - intrinsics::transmute_unchecked, - iter::{self, FusedIterator, TrustedLen, TrustedRandomAccessNoCoerce}, - mem::MaybeUninit, - ops::{IndexRange, Range}, - ptr, -}; +use crate::ops::{IndexRange, Range}; +use crate::{fmt, ptr}; /// A by-value [array] iterator. #[stable(feature = "array_value_iter", since = "1.51.0")] @@ -47,8 +44,10 @@ impl IntoIterator for [T; N] { type IntoIter = IntoIter; /// Creates a consuming iterator, that is, one that moves each value out of - /// the array (from start to end). The array cannot be used after calling - /// this unless `T` implements `Copy`, so the whole array is copied. + /// the array (from start to end). + /// + /// The array cannot be used after calling this unless `T` implements + /// `Copy`, so the whole array is copied. /// /// Arrays have special behavior when calling `.into_iter()` prior to the /// 2021 edition -- see the [array] Editions section for more information. diff --git a/core/src/array/mod.rs b/core/src/array/mod.rs index 8285c64ed2966..5c826b9993f86 100644 --- a/core/src/array/mod.rs +++ b/core/src/array/mod.rs @@ -23,7 +23,6 @@ mod equality; mod iter; pub(crate) use drain::drain_array_with; - #[stable(feature = "array_value_iter", since = "1.51.0")] pub use iter::IntoIter; diff --git a/core/src/ascii.rs b/core/src/ascii.rs index e9f4d0f93ed49..5b3711b4071ab 100644 --- a/core/src/ascii.rs +++ b/core/src/ascii.rs @@ -9,10 +9,9 @@ #![stable(feature = "core_ascii", since = "1.26.0")] -use crate::escape; -use crate::fmt; use crate::iter::FusedIterator; use crate::num::NonZero; +use crate::{escape, fmt}; mod ascii_char; #[unstable(feature = "ascii_char", issue = "110998")] diff --git a/core/src/asserting.rs b/core/src/asserting.rs index 212b637d34365..3015aa562e6c0 100644 --- a/core/src/asserting.rs +++ b/core/src/asserting.rs @@ -9,10 +9,8 @@ #![doc(hidden)] #![unstable(feature = "generic_assert_internals", issue = "44838")] -use crate::{ - fmt::{Debug, Formatter}, - marker::PhantomData, -}; +use crate::fmt::{Debug, Formatter}; +use crate::marker::PhantomData; // ***** TryCapture - Generic ***** diff --git a/core/src/async_iter/async_iter.rs b/core/src/async_iter/async_iter.rs index a0ffb6d47507b..069c50c2531b0 100644 --- a/core/src/async_iter/async_iter.rs +++ b/core/src/async_iter/async_iter.rs @@ -18,7 +18,7 @@ pub trait AsyncIterator { /// The type of items yielded by the async iterator. type Item; - /// Attempt to pull out the next value of this async iterator, registering the + /// Attempts to pull out the next value of this async iterator, registering the /// current task for wakeup if the value is not yet available, and returning /// `None` if the async iterator is exhausted. /// @@ -139,7 +139,7 @@ impl Poll> { pub const FINISHED: Self = Poll::Ready(None); } -/// Convert something into an async iterator +/// Converts something into an async iterator #[unstable(feature = "async_iterator", issue = "79024")] pub trait IntoAsyncIterator { /// The type of the item yielded by the iterator diff --git a/core/src/async_iter/from_iter.rs b/core/src/async_iter/from_iter.rs index 3180187afc8c9..f4e10bdffea2f 100644 --- a/core/src/async_iter/from_iter.rs +++ b/core/src/async_iter/from_iter.rs @@ -1,6 +1,5 @@ -use crate::pin::Pin; - use crate::async_iter::AsyncIterator; +use crate::pin::Pin; use crate::task::{Context, Poll}; /// An async iterator that was created from iterator. diff --git a/core/src/cell.rs b/core/src/cell.rs index b3189f14f9e47..0d66c2b52c84e 100644 --- a/core/src/cell.rs +++ b/core/src/cell.rs @@ -427,7 +427,9 @@ impl Cell { } /// Swaps the values of two `Cell`s. - /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference. + /// + /// The difference with `std::mem::swap` is that this function doesn't + /// require a `&mut` reference. /// /// # Panics /// @@ -1579,7 +1581,7 @@ impl<'b, T: ?Sized> Ref<'b, T> { ) } - /// Convert into a reference to the underlying data. + /// Converts into a reference to the underlying data. /// /// The underlying `RefCell` can never be mutably borrowed from again and will always appear /// already immutably borrowed. It is not a good idea to leak more than a constant number of @@ -1747,7 +1749,7 @@ impl<'b, T: ?Sized> RefMut<'b, T> { ) } - /// Convert into a mutable reference to the underlying data. + /// Converts into a mutable reference to the underlying data. /// /// The underlying `RefCell` can not be borrowed from again and will always appear already /// mutably borrowed, making the returned reference the only to the interior. @@ -1879,7 +1881,7 @@ impl fmt::Display for RefMut<'_, T> { /// /// If you have a reference `&T`, then normally in Rust the compiler performs optimizations based on /// the knowledge that `&T` points to immutable data. Mutating that data, for example through an -/// alias or by transmuting an `&T` into an `&mut T`, is considered undefined behavior. +/// alias or by transmuting a `&T` into a `&mut T`, is considered undefined behavior. /// `UnsafeCell` opts-out of the immutability guarantee for `&T`: a shared reference /// `&UnsafeCell` may point to data that is being mutated. This is called "interior mutability". /// @@ -1936,7 +1938,7 @@ impl fmt::Display for RefMut<'_, T> { /// to have multiple `&mut UnsafeCell` aliases. That is, `UnsafeCell` is a wrapper /// designed to have a special interaction with _shared_ accesses (_i.e._, through an /// `&UnsafeCell<_>` reference); there is no magic whatsoever when dealing with _exclusive_ -/// accesses (_e.g._, through an `&mut UnsafeCell<_>`): neither the cell nor the wrapped value +/// accesses (_e.g._, through a `&mut UnsafeCell<_>`): neither the cell nor the wrapped value /// may be aliased for the duration of that `&mut` borrow. /// This is showcased by the [`.get_mut()`] accessor, which is a _safe_ getter that yields /// a `&mut T`. diff --git a/core/src/cell/lazy.rs b/core/src/cell/lazy.rs index 21452d40f9ded..6ec1d2a33bef5 100644 --- a/core/src/cell/lazy.rs +++ b/core/src/cell/lazy.rs @@ -1,8 +1,7 @@ +use super::UnsafeCell; use crate::ops::Deref; use crate::{fmt, mem}; -use super::UnsafeCell; - enum State { Uninit(F), Init(T), diff --git a/core/src/cell/once.rs b/core/src/cell/once.rs index 872b4da4dbfda..097fa86c93814 100644 --- a/core/src/cell/once.rs +++ b/core/src/cell/once.rs @@ -1,6 +1,5 @@ use crate::cell::UnsafeCell; -use crate::fmt; -use crate::mem; +use crate::{fmt, mem}; /// A cell which can nominally be written to only once. /// diff --git a/core/src/char/methods.rs b/core/src/char/methods.rs index 4186565c131ed..41a19665779b6 100644 --- a/core/src/char/methods.rs +++ b/core/src/char/methods.rs @@ -1,12 +1,11 @@ //! impl char {} +use super::*; use crate::slice; use crate::str::from_utf8_unchecked_mut; use crate::unicode::printable::is_printable; use crate::unicode::{self, conversions}; -use super::*; - impl char { /// The lowest valid code point a `char` can have, `'\0'`. /// @@ -223,10 +222,7 @@ impl char { /// assert_eq!('❤', c); /// ``` #[stable(feature = "assoc_char_funcs", since = "1.52.0")] - #[rustc_const_stable( - feature = "const_char_from_u32_unchecked", - since = "CURRENT_RUSTC_VERSION" - )] + #[rustc_const_stable(feature = "const_char_from_u32_unchecked", since = "1.81.0")] #[must_use] #[inline] pub const unsafe fn from_u32_unchecked(i: u32) -> char { diff --git a/core/src/char/mod.rs b/core/src/char/mod.rs index 3c641a2e01c93..e6574ac3c7278 100644 --- a/core/src/char/mod.rs +++ b/core/src/char/mod.rs @@ -24,6 +24,8 @@ mod convert; mod decode; mod methods; +// stable re-exports +#[rustfmt::skip] #[stable(feature = "try_from", since = "1.34.0")] pub use self::convert::CharTryFromError; #[stable(feature = "char_from_str", since = "1.20.0")] @@ -31,20 +33,22 @@ pub use self::convert::ParseCharError; #[stable(feature = "decode_utf16", since = "1.9.0")] pub use self::decode::{DecodeUtf16, DecodeUtf16Error}; +// perma-unstable re-exports +#[rustfmt::skip] #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] pub use self::methods::encode_utf16_raw; // perma-unstable #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] pub use self::methods::encode_utf8_raw; // perma-unstable +#[rustfmt::skip] use crate::ascii; +pub(crate) use self::methods::EscapeDebugExtArgs; use crate::error::Error; use crate::escape; use crate::fmt::{self, Write}; use crate::iter::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use crate::num::NonZero; -pub(crate) use self::methods::EscapeDebugExtArgs; - // UTF-8 ranges and tags for encoding characters const TAG_CONT: u8 = 0b1000_0000; const TAG_TWO_B: u8 = 0b1100_0000; @@ -121,7 +125,7 @@ pub const fn from_u32(i: u32) -> Option { /// Converts a `u32` to a `char`, ignoring validity. Use [`char::from_u32_unchecked`]. /// instead. #[stable(feature = "char_from_unchecked", since = "1.5.0")] -#[rustc_const_stable(feature = "const_char_from_u32_unchecked", since = "CURRENT_RUSTC_VERSION")] +#[rustc_const_stable(feature = "const_char_from_u32_unchecked", since = "1.81.0")] #[must_use] #[inline] pub const unsafe fn from_u32_unchecked(i: u32) -> char { diff --git a/core/src/clone.rs b/core/src/clone.rs index 939b2be6dfaf1..76a89eaaff86e 100644 --- a/core/src/clone.rs +++ b/core/src/clone.rs @@ -160,6 +160,9 @@ pub trait Clone: Sized { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use = "cloning is often expensive and is not expected to have side effects"] + // Clone::clone is special because the compiler generates MIR to implement it for some types. + // See InstanceKind::CloneShim. + #[cfg_attr(not(bootstrap), lang = "clone_fn")] fn clone(&self) -> Self; /// Performs copy-assignment from `source`. diff --git a/core/src/cmp.rs b/core/src/cmp.rs index cff75870790c5..a1ed993b7d9bf 100644 --- a/core/src/cmp.rs +++ b/core/src/cmp.rs @@ -246,15 +246,14 @@ use self::Ordering::*; )] #[rustc_diagnostic_item = "PartialEq"] pub trait PartialEq { - /// This method tests for `self` and `other` values to be equal, and is used - /// by `==`. + /// Tests for `self` and `other` values to be equal, and is used by `==`. #[must_use] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_diagnostic_item = "cmp_partialeq_eq"] fn eq(&self, other: &Rhs) -> bool; - /// This method tests for `!=`. The default implementation is almost always - /// sufficient, and should not be overridden without very good reason. + /// Tests for `!=`. The default implementation is almost always sufficient, + /// and should not be overridden without very good reason. #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] @@ -1163,7 +1162,7 @@ pub trait PartialOrd: PartialEq { #[rustc_diagnostic_item = "cmp_partialord_cmp"] fn partial_cmp(&self, other: &Rhs) -> Option; - /// This method tests less than (for `self` and `other`) and is used by the `<` operator. + /// Tests less than (for `self` and `other`) and is used by the `<` operator. /// /// # Examples /// @@ -1180,8 +1179,8 @@ pub trait PartialOrd: PartialEq { matches!(self.partial_cmp(other), Some(Less)) } - /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=` - /// operator. + /// Tests less than or equal to (for `self` and `other`) and is used by the + /// `<=` operator. /// /// # Examples /// @@ -1198,7 +1197,8 @@ pub trait PartialOrd: PartialEq { matches!(self.partial_cmp(other), Some(Less | Equal)) } - /// This method tests greater than (for `self` and `other`) and is used by the `>` operator. + /// Tests greater than (for `self` and `other`) and is used by the `>` + /// operator. /// /// # Examples /// @@ -1215,8 +1215,8 @@ pub trait PartialOrd: PartialEq { matches!(self.partial_cmp(other), Some(Greater)) } - /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` - /// operator. + /// Tests greater than or equal to (for `self` and `other`) and is used by + /// the `>=` operator. /// /// # Examples /// diff --git a/core/src/convert/num.rs b/core/src/convert/num.rs index 86c4ea9fab088..0246d0627cafe 100644 --- a/core/src/convert/num.rs +++ b/core/src/convert/num.rs @@ -208,7 +208,7 @@ macro_rules! impl_try_from_unbounded { impl TryFrom<$source> for $target { type Error = TryFromIntError; - /// Try to create the target number type from a source + /// Tries to create the target number type from a source /// number type. This returns an error if the source value /// is outside of the range of the target type. #[inline] @@ -226,7 +226,7 @@ macro_rules! impl_try_from_lower_bounded { impl TryFrom<$source> for $target { type Error = TryFromIntError; - /// Try to create the target number type from a source + /// Tries to create the target number type from a source /// number type. This returns an error if the source value /// is outside of the range of the target type. #[inline] @@ -248,7 +248,7 @@ macro_rules! impl_try_from_upper_bounded { impl TryFrom<$source> for $target { type Error = TryFromIntError; - /// Try to create the target number type from a source + /// Tries to create the target number type from a source /// number type. This returns an error if the source value /// is outside of the range of the target type. #[inline] @@ -270,7 +270,7 @@ macro_rules! impl_try_from_both_bounded { impl TryFrom<$source> for $target { type Error = TryFromIntError; - /// Try to create the target number type from a source + /// Tries to create the target number type from a source /// number type. This returns an error if the source value /// is outside of the range of the target type. #[inline] diff --git a/core/src/default.rs b/core/src/default.rs index 4524b352ec817..5cacedcb241a5 100644 --- a/core/src/default.rs +++ b/core/src/default.rs @@ -103,6 +103,7 @@ use crate::ascii::Char as AsciiChar; /// ``` #[cfg_attr(not(test), rustc_diagnostic_item = "Default")] #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(bootstrap), rustc_trivial_field_reads)] pub trait Default: Sized { /// Returns the "default value" for a type. /// diff --git a/core/src/error.rs b/core/src/error.rs index ca8983d4cbcfe..6cc91849e1dc9 100644 --- a/core/src/error.rs +++ b/core/src/error.rs @@ -1,5 +1,5 @@ #![doc = include_str!("error.md")] -#![stable(feature = "error_in_core", since = "CURRENT_RUSTC_VERSION")] +#![stable(feature = "error_in_core", since = "1.81.0")] #[cfg(test)] mod tests; @@ -30,7 +30,7 @@ use crate::fmt::{Debug, Display, Formatter, Result}; #[rustc_has_incoherent_inherent_impls] #[allow(multiple_supertrait_upcastable)] pub trait Error: Debug + Display { - /// The lower-level source of this error, if any. + /// Returns the lower-level source of this error, if any. /// /// # Examples /// @@ -121,7 +121,7 @@ pub trait Error: Debug + Display { self.source() } - /// Provides type based access to context intended for error reports. + /// Provides type-based access to context intended for error reports. /// /// Used in conjunction with [`Request::provide_value`] and [`Request::provide_ref`] to extract /// references to member variables from `dyn Error` trait objects. @@ -353,7 +353,7 @@ impl dyn Error { } } -/// Request a value of type `T` from the given `impl Error`. +/// Requests a value of type `T` from the given `impl Error`. /// /// # Examples /// @@ -376,7 +376,7 @@ where request_by_type_tag::<'a, tags::Value>(err) } -/// Request a reference of type `T` from the given `impl Error`. +/// Requests a reference of type `T` from the given `impl Error`. /// /// # Examples /// @@ -506,11 +506,11 @@ where /// ``` /// #[unstable(feature = "error_generic_member_access", issue = "99301")] -#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/90435 +#[repr(transparent)] pub struct Request<'a>(Tagged + 'a>); impl<'a> Request<'a> { - /// Provide a value or other type with only static lifetimes. + /// Provides a value or other type with only static lifetimes. /// /// # Examples /// @@ -544,7 +544,7 @@ impl<'a> Request<'a> { self.provide::>(value) } - /// Provide a value or other type with only static lifetimes computed using a closure. + /// Provides a value or other type with only static lifetimes computed using a closure. /// /// # Examples /// @@ -578,7 +578,7 @@ impl<'a> Request<'a> { self.provide_with::>(fulfil) } - /// Provide a reference. The referee type must be bounded by `'static`, + /// Provides a reference. The referee type must be bounded by `'static`, /// but may be unsized. /// /// # Examples @@ -610,7 +610,7 @@ impl<'a> Request<'a> { self.provide::>>(value) } - /// Provide a reference computed using a closure. The referee type + /// Provides a reference computed using a closure. The referee type /// must be bounded by `'static`, but may be unsized. /// /// # Examples @@ -652,7 +652,7 @@ impl<'a> Request<'a> { self.provide_with::>>(fulfil) } - /// Provide a value with the given `Type` tag. + /// Provides a value with the given `Type` tag. fn provide(&mut self, value: I::Reified) -> &mut Self where I: tags::Type<'a>, @@ -663,7 +663,7 @@ impl<'a> Request<'a> { self } - /// Provide a value with the given `Type` tag, using a closure to prevent unnecessary work. + /// Provides a value with the given `Type` tag, using a closure to prevent unnecessary work. fn provide_with(&mut self, fulfil: impl FnOnce() -> I::Reified) -> &mut Self where I: tags::Type<'a>, @@ -674,13 +674,13 @@ impl<'a> Request<'a> { self } - /// Check if the `Request` would be satisfied if provided with a + /// Checks if the `Request` would be satisfied if provided with a /// value of the specified type. If the type does not match or has /// already been provided, returns false. /// /// # Examples /// - /// Check if an `u8` still needs to be provided and then provides + /// Checks if a `u8` still needs to be provided and then provides /// it. /// /// ```rust @@ -761,13 +761,14 @@ impl<'a> Request<'a> { self.would_be_satisfied_by::>() } - /// Check if the `Request` would be satisfied if provided with a - /// reference to a value of the specified type. If the type does - /// not match or has already been provided, returns false. + /// Checks if the `Request` would be satisfied if provided with a + /// reference to a value of the specified type. + /// + /// If the type does not match or has already been provided, returns false. /// /// # Examples /// - /// Check if a `&str` still needs to be provided and then provides + /// Checks if a `&str` still needs to be provided and then provides /// it. /// /// ```rust diff --git a/core/src/ffi/c_str.rs b/core/src/ffi/c_str.rs index 563f0a324e3f1..22084dcff8f88 100644 --- a/core/src/ffi/c_str.rs +++ b/core/src/ffi/c_str.rs @@ -3,16 +3,11 @@ use crate::cmp::Ordering; use crate::error::Error; use crate::ffi::c_char; -use crate::fmt; -use crate::intrinsics; use crate::iter::FusedIterator; use crate::marker::PhantomData; -use crate::ops; -use crate::ptr::addr_of; -use crate::ptr::NonNull; -use crate::slice; +use crate::ptr::{addr_of, NonNull}; use crate::slice::memchr; -use crate::str; +use crate::{fmt, intrinsics, ops, slice, str}; // FIXME: because this is doc(inline)d, we *have* to use intra-doc links because the actual link // depends on where the item is being documented. however, since this is libcore, we can't @@ -94,7 +89,7 @@ use crate::str; /// ``` /// /// [str]: prim@str "str" -#[derive(Hash)] +#[derive(PartialEq, Eq, Hash)] #[stable(feature = "core_c_str", since = "1.64.0")] #[rustc_has_incoherent_inherent_impls] #[lang = "CStr"] @@ -103,8 +98,7 @@ use crate::str; // However, `CStr` layout is considered an implementation detail and must not be relied upon. We // want `repr(transparent)` but we don't want it to show up in rustdoc, so we hide it under // `cfg(doc)`. This is an ad-hoc implementation of attribute privacy. -#[cfg_attr(not(doc), repr(transparent))] -#[allow(clippy::derived_hash_with_manual_eq)] +#[repr(transparent)] pub struct CStr { // FIXME: this should not be represented with a DST slice but rather with // just a raw `c_char` along with some form of marker to make @@ -278,7 +272,7 @@ impl CStr { #[inline] // inline is necessary for codegen to see strlen. #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")] pub const unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr { // SAFETY: The caller has provided a pointer that points to a valid C // string with a NUL terminator less than `isize::MAX` from `ptr`. @@ -540,7 +534,7 @@ impl CStr { #[must_use] #[doc(alias("len", "strlen"))] #[stable(feature = "cstr_count_bytes", since = "1.79.0")] - #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")] pub const fn count_bytes(&self) -> usize { self.inner.len() - 1 } @@ -678,15 +672,9 @@ impl CStr { } } -#[stable(feature = "rust1", since = "1.0.0")] -impl PartialEq for CStr { - #[inline] - fn eq(&self, other: &CStr) -> bool { - self.to_bytes().eq(other.to_bytes()) - } -} -#[stable(feature = "rust1", since = "1.0.0")] -impl Eq for CStr {} +// `.to_bytes()` representations are compared instead of the inner `[c_char]`s, +// because `c_char` is `i8` (not `u8`) on some platforms. +// That is why this is implemented manually and not derived. #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for CStr { #[inline] @@ -741,7 +729,7 @@ impl AsRef for CStr { /// located within `isize::MAX` from `ptr`. #[inline] #[unstable(feature = "cstr_internals", issue = "none")] -#[rustc_const_stable(feature = "const_cstr_from_ptr", since = "CURRENT_RUSTC_VERSION")] +#[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")] #[rustc_allow_const_fn_unstable(const_eval_select)] const unsafe fn strlen(ptr: *const c_char) -> usize { const fn strlen_ct(s: *const c_char) -> usize { diff --git a/core/src/ffi/mod.rs b/core/src/ffi/mod.rs index 88adc378477fd..ec1f9052a1564 100644 --- a/core/src/ffi/mod.rs +++ b/core/src/ffi/mod.rs @@ -9,19 +9,16 @@ #![stable(feature = "core_ffi", since = "1.30.0")] #![allow(non_camel_case_types)] -use crate::fmt; - -#[doc(no_inline)] +#[doc(inline)] #[stable(feature = "core_c_str", since = "1.64.0")] -pub use self::c_str::FromBytesWithNulError; - +pub use self::c_str::CStr; #[doc(no_inline)] #[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")] pub use self::c_str::FromBytesUntilNulError; - -#[doc(inline)] +#[doc(no_inline)] #[stable(feature = "core_c_str", since = "1.64.0")] -pub use self::c_str::CStr; +pub use self::c_str::FromBytesWithNulError; +use crate::fmt; #[unstable(feature = "c_str_module", issue = "112134")] pub mod c_str; @@ -191,7 +188,7 @@ mod c_long_definition { // be UB. #[doc = include_str!("c_void.md")] #[lang = "c_void"] -#[cfg_attr(not(doc), repr(u8))] // work around https://github.com/rust-lang/rust/issues/90435 +#[cfg_attr(not(doc), repr(u8))] // An implementation detail we don't want to show up in rustdoc #[stable(feature = "core_c_void", since = "1.30.0")] pub enum c_void { #[unstable( diff --git a/core/src/ffi/va_list.rs b/core/src/ffi/va_list.rs index 6a2e8b67d0c2a..3a224e4d8fe5f 100644 --- a/core/src/ffi/va_list.rs +++ b/core/src/ffi/va_list.rs @@ -3,7 +3,6 @@ //! Better known as "varargs". use crate::ffi::c_void; - #[allow(unused_imports)] use crate::fmt; use crate::marker::PhantomData; @@ -23,7 +22,7 @@ use crate::ops::{Deref, DerefMut}; target_os = "uefi", windows, ))] -#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/90435 +#[repr(transparent)] #[lang = "va_list"] pub struct VaListImpl<'f> { ptr: *mut c_void, @@ -115,7 +114,7 @@ pub struct VaListImpl<'f> { } /// A wrapper for a `va_list` -#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/90435 +#[repr(transparent)] #[derive(Debug)] pub struct VaList<'a, 'f: 'a> { #[cfg(any( @@ -162,7 +161,7 @@ pub struct VaList<'a, 'f: 'a> { windows, ))] impl<'f> VaListImpl<'f> { - /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`. + /// Converts a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`. #[inline] pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> { VaList { inner: VaListImpl { ..*self }, _marker: PhantomData } @@ -182,7 +181,7 @@ impl<'f> VaListImpl<'f> { not(windows), ))] impl<'f> VaListImpl<'f> { - /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`. + /// Converts a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`. #[inline] pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> { VaList { inner: self, _marker: PhantomData } diff --git a/core/src/fmt/builders.rs b/core/src/fmt/builders.rs index 4ccb585862cdf..794ca1851b13d 100644 --- a/core/src/fmt/builders.rs +++ b/core/src/fmt/builders.rs @@ -402,6 +402,7 @@ impl<'a, 'b: 'a> DebugTuple<'a, 'b> { } } +/// A helper used to print list-like items with no special formatting. struct DebugInner<'a, 'b: 'a> { fmt: &'a mut fmt::Formatter<'b>, result: fmt::Result, @@ -578,7 +579,8 @@ impl<'a, 'b: 'a> DebugSet<'a, 'b> { /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn finish(&mut self) -> fmt::Result { - self.inner.result.and_then(|_| self.inner.fmt.write_str("}")) + self.inner.result = self.inner.result.and_then(|_| self.inner.fmt.write_str("}")); + self.inner.result } } @@ -721,7 +723,8 @@ impl<'a, 'b: 'a> DebugList<'a, 'b> { /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn finish(&mut self) -> fmt::Result { - self.inner.result.and_then(|_| self.inner.fmt.write_str("]")) + self.inner.result = self.inner.result.and_then(|_| self.inner.fmt.write_str("]")); + self.inner.result } } @@ -1002,11 +1005,12 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn finish(&mut self) -> fmt::Result { - self.result.and_then(|_| { + self.result = self.result.and_then(|_| { assert!(!self.has_key, "attempted to finish a map with a partial entry"); self.fmt.write_str("}") - }) + }); + self.result } fn is_pretty(&self) -> bool { @@ -1026,7 +1030,7 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// assert_eq!(format!("{}", value), "a"); /// assert_eq!(format!("{:?}", value), "'a'"); /// -/// let wrapped = fmt::FormatterFn(|f| write!(f, "{:?}", &value)); +/// let wrapped = fmt::FormatterFn(|f| write!(f, "{value:?}")); /// assert_eq!(format!("{}", wrapped), "'a'"); /// assert_eq!(format!("{:?}", wrapped), "'a'"); /// ``` diff --git a/core/src/fmt/float.rs b/core/src/fmt/float.rs index 80c45fce2f0a0..20ea0352c2dce 100644 --- a/core/src/fmt/float.rs +++ b/core/src/fmt/float.rs @@ -1,7 +1,6 @@ use crate::fmt::{Debug, Display, Formatter, LowerExp, Result, UpperExp}; use crate::mem::MaybeUninit; -use crate::num::flt2dec; -use crate::num::fmt as numfmt; +use crate::num::{flt2dec, fmt as numfmt}; #[doc(hidden)] trait GeneralFormat: PartialOrd { diff --git a/core/src/fmt/mod.rs b/core/src/fmt/mod.rs index 25ab5b2db9641..60c0dc7685253 100644 --- a/core/src/fmt/mod.rs +++ b/core/src/fmt/mod.rs @@ -4,13 +4,10 @@ use crate::cell::{Cell, Ref, RefCell, RefMut, SyncUnsafeCell, UnsafeCell}; use crate::char::EscapeDebugExtArgs; -use crate::iter; use crate::marker::PhantomData; -use crate::mem; use crate::num::fmt as numfmt; use crate::ops::Deref; -use crate::result; -use crate::str; +use crate::{iter, mem, result, str}; mod builders; #[cfg(not(no_fp_fmt_parse))] @@ -36,11 +33,10 @@ pub enum Alignment { Center, } -#[stable(feature = "debug_builders", since = "1.2.0")] -pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; - #[unstable(feature = "debug_closure_helpers", issue = "117729")] pub use self::builders::FormatterFn; +#[stable(feature = "debug_builders", since = "1.2.0")] +pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; /// The type returned by formatter methods. /// @@ -354,7 +350,7 @@ impl<'a> Arguments<'a> { Arguments { pieces, fmt: None, args } } - /// This function is used to specify nonstandard formatting parameters. + /// Specifies nonstandard formatting parameters. /// /// An `rt::UnsafeArg` is required because the following invariants must be held /// in order for this function to be safe: @@ -396,7 +392,7 @@ impl<'a> Arguments<'a> { } impl<'a> Arguments<'a> { - /// Get the formatted string, if it has no arguments to be formatted at runtime. + /// Gets the formatted string, if it has no arguments to be formatted at runtime. /// /// This can be used to avoid allocations in some cases. /// @@ -1129,8 +1125,8 @@ pub trait UpperExp { fn fmt(&self, f: &mut Formatter<'_>) -> Result; } -/// The `write` function takes an output stream, and an `Arguments` struct -/// that can be precompiled with the `format_args!` macro. +/// Takes an output stream and an `Arguments` struct that can be precompiled with +/// the `format_args!` macro. /// /// The arguments will be formatted according to the specified format string /// into the output stream provided. @@ -1257,7 +1253,7 @@ impl PostPadding { PostPadding { fill, padding } } - /// Write this post padding. + /// Writes this post padding. pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result { for _ in 0..self.padding { f.buf.write_char(self.fill)?; @@ -1398,9 +1394,10 @@ impl<'a> Formatter<'a> { } } - /// This function takes a string slice and emits it to the internal buffer - /// after applying the relevant formatting flags specified. The flags - /// recognized for generic strings are: + /// Takes a string slice and emits it to the internal buffer after applying + /// the relevant formatting flags specified. + /// + /// The flags recognized for generic strings are: /// /// * width - the minimum width of what to emit /// * fill/align - what to emit and where to emit it if the string @@ -1474,9 +1471,10 @@ impl<'a> Formatter<'a> { } } - /// Write the pre-padding and return the unwritten post-padding. Callers are - /// responsible for ensuring post-padding is written after the thing that is - /// being padded. + /// Writes the pre-padding and returns the unwritten post-padding. + /// + /// Callers are responsible for ensuring post-padding is written after the + /// thing that is being padded. pub(crate) fn padding( &mut self, padding: usize, @@ -1503,6 +1501,7 @@ impl<'a> Formatter<'a> { } /// Takes the formatted parts and applies the padding. + /// /// Assumes that the caller already has rendered the parts with required precision, /// so that `self.precision` can be ignored. /// @@ -1655,7 +1654,7 @@ impl<'a> Formatter<'a> { } } - /// Flags for formatting + /// Returns flags for formatting. #[must_use] #[stable(feature = "rust1", since = "1.0.0")] #[deprecated( @@ -1667,7 +1666,7 @@ impl<'a> Formatter<'a> { self.flags } - /// Character used as 'fill' whenever there is alignment. + /// Returns the character used as 'fill' whenever there is alignment. /// /// # Examples /// @@ -1700,7 +1699,7 @@ impl<'a> Formatter<'a> { self.fill } - /// Flag indicating what form of alignment was requested. + /// Returns a flag indicating what form of alignment was requested. /// /// # Examples /// @@ -1740,7 +1739,7 @@ impl<'a> Formatter<'a> { } } - /// Optionally specified integer width that the output should be. + /// Returns the optionally specified integer width that the output should be. /// /// # Examples /// @@ -1770,8 +1769,8 @@ impl<'a> Formatter<'a> { self.width } - /// Optionally specified precision for numeric types. Alternatively, the - /// maximum width for string types. + /// Returns the optionally specified precision for numeric types. + /// Alternatively, the maximum width for string types. /// /// # Examples /// @@ -1967,8 +1966,9 @@ impl<'a> Formatter<'a> { builders::debug_struct_new(self, name) } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_struct_fields_finish` is more general, but this is faster for 1 field. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_struct_fields_finish` is more general, but this is + /// faster for 1 field. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_struct_field1_finish<'b>( @@ -1982,8 +1982,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_struct_fields_finish` is more general, but this is faster for 2 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_struct_fields_finish` is more general, but this is + /// faster for 2 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_struct_field2_finish<'b>( @@ -2000,8 +2001,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_struct_fields_finish` is more general, but this is faster for 3 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_struct_fields_finish` is more general, but this is + /// faster for 3 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_struct_field3_finish<'b>( @@ -2021,8 +2023,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_struct_fields_finish` is more general, but this is faster for 4 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_struct_fields_finish` is more general, but this is + /// faster for 4 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_struct_field4_finish<'b>( @@ -2045,8 +2048,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_struct_fields_finish` is more general, but this is faster for 5 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_struct_fields_finish` is more general, but this is + /// faster for 5 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_struct_field5_finish<'b>( @@ -2072,7 +2076,7 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller binaries. /// For the cases not covered by `debug_struct_field[12345]_finish`. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] @@ -2121,8 +2125,9 @@ impl<'a> Formatter<'a> { builders::debug_tuple_new(self, name) } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_tuple_fields_finish` is more general, but this is faster for 1 field. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_tuple_fields_finish` is more general, but this is faster + /// for 1 field. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result { @@ -2131,8 +2136,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_tuple_fields_finish` is more general, but this is faster for 2 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_tuple_fields_finish` is more general, but this is faster + /// for 2 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_field2_finish<'b>( @@ -2147,8 +2153,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_tuple_fields_finish` is more general, but this is faster for 3 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_tuple_fields_finish` is more general, but this is faster + /// for 3 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_field3_finish<'b>( @@ -2165,8 +2172,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_tuple_fields_finish` is more general, but this is faster for 4 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_tuple_fields_finish` is more general, but this is faster + /// for 4 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_field4_finish<'b>( @@ -2185,8 +2193,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_tuple_fields_finish` is more general, but this is faster for 5 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_tuple_fields_finish` is more general, but this is faster + /// for 5 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_field5_finish<'b>( @@ -2207,8 +2216,8 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// For the cases not covered by `debug_tuple_field[12345]_finish`. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. For the cases not covered by `debug_tuple_field[12345]_finish`. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_fields_finish<'b>( @@ -2496,8 +2505,9 @@ impl Pointer for *const T { } } -/// Since the formatting will be identical for all pointer types, use a non-monomorphized -/// implementation for the actual formatting to reduce the amount of codegen work needed. +/// Since the formatting will be identical for all pointer types, uses a +/// non-monomorphized implementation for the actual formatting to reduce the +/// amount of codegen work needed. /// /// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for /// `fn(...) -> ...` without using [problematic] "Oxford Casts". diff --git a/core/src/fmt/num.rs b/core/src/fmt/num.rs index 3a5a5af8bf5d3..e7726da8d91f2 100644 --- a/core/src/fmt/num.rs +++ b/core/src/fmt/num.rs @@ -1,12 +1,9 @@ //! Integer and floating-point number formatting -use crate::fmt; use crate::mem::MaybeUninit; use crate::num::fmt as numfmt; use crate::ops::{Div, Rem, Sub}; -use crate::ptr; -use crate::slice; -use crate::str; +use crate::{fmt, ptr, slice, str}; #[doc(hidden)] trait DisplayInt: diff --git a/core/src/future/async_drop.rs b/core/src/future/async_drop.rs index 63193bbfb35e8..8971a2c0aafd1 100644 --- a/core/src/future/async_drop.rs +++ b/core/src/future/async_drop.rs @@ -205,7 +205,7 @@ async unsafe fn slice(s: *mut [T]) { } } -/// Construct a chain of two futures, which awaits them sequentially as +/// Constructs a chain of two futures, which awaits them sequentially as /// a future. #[lang = "async_drop_chain"] async fn chain(first: F, last: G) @@ -235,8 +235,8 @@ async unsafe fn defer(to_drop: *mut T) { /// /// # Safety /// -/// User should carefully manage returned future, since it would -/// try creating an immutable referece from `this` and get pointee's +/// Users should carefully manage the returned future, since it would +/// try creating an immutable reference from `this` and get pointee's /// discriminant. // FIXME(zetanumbers): Send and Sync impls #[lang = "async_drop_either"] diff --git a/core/src/future/future.rs b/core/src/future/future.rs index c80cfdcebf70d..ca1c2d1ca1f2e 100644 --- a/core/src/future/future.rs +++ b/core/src/future/future.rs @@ -38,7 +38,7 @@ pub trait Future { #[lang = "future_output"] type Output; - /// Attempt to resolve the future to a final value, registering + /// Attempts to resolve the future to a final value, registering /// the current task for wakeup if the value is not yet available. /// /// # Return value diff --git a/core/src/future/into_future.rs b/core/src/future/into_future.rs index eb5a9b72dd0f2..aa546b940b23a 100644 --- a/core/src/future/into_future.rs +++ b/core/src/future/into_future.rs @@ -40,7 +40,7 @@ use crate::future::Future; /// } /// /// impl Multiply { -/// /// Construct a new instance of `Multiply`. +/// /// Constructs a new instance of `Multiply`. /// pub fn new(num: u16, factor: u16) -> Self { /// Self { num, factor } /// } @@ -89,7 +89,7 @@ use crate::future::Future; /// ```rust /// use std::future::IntoFuture; /// -/// /// Convert the output of a future to a string. +/// /// Converts the output of a future to a string. /// async fn fut_to_string(fut: Fut) -> String /// where /// Fut: IntoFuture, diff --git a/core/src/future/mod.rs b/core/src/future/mod.rs index 3a1451abfa40b..d188f1c713079 100644 --- a/core/src/future/mod.rs +++ b/core/src/future/mod.rs @@ -20,25 +20,21 @@ mod pending; mod poll_fn; mod ready; -#[stable(feature = "futures_api", since = "1.36.0")] -pub use self::future::Future; - -#[unstable(feature = "future_join", issue = "91642")] -pub use self::join::join; - +#[unstable(feature = "async_drop", issue = "126482")] +pub use async_drop::{async_drop, async_drop_in_place, AsyncDrop, AsyncDropInPlace}; #[stable(feature = "into_future", since = "1.64.0")] pub use into_future::IntoFuture; - #[stable(feature = "future_readiness_fns", since = "1.48.0")] pub use pending::{pending, Pending}; -#[stable(feature = "future_readiness_fns", since = "1.48.0")] -pub use ready::{ready, Ready}; - #[stable(feature = "future_poll_fn", since = "1.64.0")] pub use poll_fn::{poll_fn, PollFn}; +#[stable(feature = "future_readiness_fns", since = "1.48.0")] +pub use ready::{ready, Ready}; -#[unstable(feature = "async_drop", issue = "126482")] -pub use async_drop::{async_drop, async_drop_in_place, AsyncDrop, AsyncDropInPlace}; +#[stable(feature = "futures_api", since = "1.36.0")] +pub use self::future::Future; +#[unstable(feature = "future_join", issue = "91642")] +pub use self::join::join; /// This type is needed because: /// diff --git a/core/src/hash/mod.rs b/core/src/hash/mod.rs index da734466263ab..061690e88ddf8 100644 --- a/core/src/hash/mod.rs +++ b/core/src/hash/mod.rs @@ -83,17 +83,14 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::fmt; -use crate::marker; - #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] pub use self::sip::SipHasher; - #[unstable(feature = "hashmap_internals", issue = "none")] #[allow(deprecated)] #[doc(hidden)] pub use self::sip::SipHasher13; +use crate::{fmt, marker}; mod sip; @@ -806,10 +803,8 @@ impl PartialEq for BuildHasherDefault { impl Eq for BuildHasherDefault {} mod impls { - use crate::mem; - use crate::slice; - use super::*; + use crate::{mem, slice}; macro_rules! impl_write { ($(($ty:ident, $meth:ident),)*) => {$( diff --git a/core/src/hash/sip.rs b/core/src/hash/sip.rs index 0d1ac64aa56cf..17f2caaa0c083 100644 --- a/core/src/hash/sip.rs +++ b/core/src/hash/sip.rs @@ -2,10 +2,8 @@ #![allow(deprecated)] // the types in this module are deprecated -use crate::cmp; use crate::marker::PhantomData; -use crate::mem; -use crate::ptr; +use crate::{cmp, mem, ptr}; /// An implementation of SipHash 1-3. /// diff --git a/core/src/hint.rs b/core/src/hint.rs index b3e36e6fbc4ac..6ca5e53df3b01 100644 --- a/core/src/hint.rs +++ b/core/src/hint.rs @@ -3,8 +3,7 @@ //! Hints to compiler that affects how code should be emitted or optimized. //! Hints may be compile time or runtime. -use crate::intrinsics; -use crate::ub_checks; +use crate::{intrinsics, ub_checks}; /// Informs the compiler that the site which is calling this function is not /// reachable, possibly enabling further optimizations. @@ -195,8 +194,8 @@ pub const unsafe fn unreachable_unchecked() -> ! { #[track_caller] #[inline(always)] #[doc(alias = "assume")] -#[stable(feature = "hint_assert_unchecked", since = "CURRENT_RUSTC_VERSION")] -#[rustc_const_stable(feature = "hint_assert_unchecked", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "hint_assert_unchecked", since = "1.81.0")] +#[rustc_const_stable(feature = "hint_assert_unchecked", since = "1.81.0")] pub const unsafe fn assert_unchecked(cond: bool) { // SAFETY: The caller promised `cond` is true. unsafe { diff --git a/core/src/internal_macros.rs b/core/src/internal_macros.rs index bf53b2245ac59..fe4fa80263c28 100644 --- a/core/src/internal_macros.rs +++ b/core/src/internal_macros.rs @@ -80,7 +80,7 @@ macro_rules! forward_ref_op_assign { } } -/// Create a zero-size type similar to a closure type, but named. +/// Creates a zero-size type similar to a closure type, but named. macro_rules! impl_fn_for_zst { ($( $( #[$attr: meta] )* diff --git a/core/src/intrinsics.rs b/core/src/intrinsics.rs index 720da0feecee6..e9eacbcd25a0a 100644 --- a/core/src/intrinsics.rs +++ b/core/src/intrinsics.rs @@ -63,10 +63,8 @@ )] #![allow(missing_docs)] -use crate::marker::DiscriminantKind; -use crate::marker::Tuple; -use crate::ptr; -use crate::ub_checks; +use crate::marker::{DiscriminantKind, Tuple}; +use crate::{ptr, ub_checks}; pub mod mir; pub mod simd; @@ -947,7 +945,6 @@ extern "rust-intrinsic" { #[rustc_const_stable(feature = "const_unreachable_unchecked", since = "1.57.0")] #[rustc_nounwind] pub fn unreachable() -> !; - } /// Informs the optimizer that a condition is always true. @@ -1011,6 +1008,34 @@ pub const fn unlikely(b: bool) -> bool { b } +/// Returns either `true_val` or `false_val` depending on condition `b` with a +/// hint to the compiler that this condition is unlikely to be correctly +/// predicted by a CPU's branch predictor (e.g. a binary search). +/// +/// This is otherwise functionally equivalent to `if b { true_val } else { false_val }`. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// This intrinsic does not have a stable counterpart. +#[cfg(not(bootstrap))] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_intrinsic] +#[rustc_nounwind] +#[miri::intrinsic_fallback_is_spec] +#[inline] +pub fn select_unpredictable(b: bool, true_val: T, false_val: T) -> T { + if b { true_val } else { false_val } +} + +#[cfg(bootstrap)] +#[inline] +pub fn select_unpredictable(b: bool, true_val: T, false_val: T) -> T { + if b { true_val } else { false_val } +} + extern "rust-intrinsic" { /// Executes a breakpoint trap, for inspection by a debugger. /// @@ -1018,83 +1043,6 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn breakpoint(); - /// The size of a type in bytes. - /// - /// Note that, unlike most intrinsics, this is safe to call; - /// it does not require an `unsafe` block. - /// Therefore, implementations must not require the user to uphold - /// any safety invariants. - /// - /// More specifically, this is the offset in bytes between successive - /// items of the same type, including alignment padding. - /// - /// The stabilized version of this intrinsic is [`core::mem::size_of`]. - #[rustc_const_stable(feature = "const_size_of", since = "1.40.0")] - #[rustc_safe_intrinsic] - #[rustc_nounwind] - pub fn size_of() -> usize; - - /// The minimum alignment of a type. - /// - /// Note that, unlike most intrinsics, this is safe to call; - /// it does not require an `unsafe` block. - /// Therefore, implementations must not require the user to uphold - /// any safety invariants. - /// - /// The stabilized version of this intrinsic is [`core::mem::align_of`]. - #[rustc_const_stable(feature = "const_min_align_of", since = "1.40.0")] - #[rustc_safe_intrinsic] - #[rustc_nounwind] - pub fn min_align_of() -> usize; - /// The preferred alignment of a type. - /// - /// This intrinsic does not have a stable counterpart. - /// It's "tracking issue" is [#91971](https://github.com/rust-lang/rust/issues/91971). - #[rustc_const_unstable(feature = "const_pref_align_of", issue = "91971")] - #[rustc_nounwind] - pub fn pref_align_of() -> usize; - - /// The size of the referenced value in bytes. - /// - /// The stabilized version of this intrinsic is [`crate::mem::size_of_val`]. - #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")] - #[rustc_nounwind] - pub fn size_of_val(_: *const T) -> usize; - /// The required alignment of the referenced value. - /// - /// The stabilized version of this intrinsic is [`core::mem::align_of_val`]. - #[rustc_const_unstable(feature = "const_align_of_val", issue = "46571")] - #[rustc_nounwind] - pub fn min_align_of_val(_: *const T) -> usize; - - /// Gets a static string slice containing the name of a type. - /// - /// Note that, unlike most intrinsics, this is safe to call; - /// it does not require an `unsafe` block. - /// Therefore, implementations must not require the user to uphold - /// any safety invariants. - /// - /// The stabilized version of this intrinsic is [`core::any::type_name`]. - #[rustc_const_unstable(feature = "const_type_name", issue = "63084")] - #[rustc_safe_intrinsic] - #[rustc_nounwind] - pub fn type_name() -> &'static str; - - /// Gets an identifier which is globally unique to the specified type. This - /// function will return the same value for a type regardless of whichever - /// crate it is invoked in. - /// - /// Note that, unlike most intrinsics, this is safe to call; - /// it does not require an `unsafe` block. - /// Therefore, implementations must not require the user to uphold - /// any safety invariants. - /// - /// The stabilized version of this intrinsic is [`core::any::TypeId::of`]. - #[rustc_const_unstable(feature = "const_type_id", issue = "77125")] - #[rustc_safe_intrinsic] - #[rustc_nounwind] - pub fn type_id() -> u128; - /// A guard for unsafe functions that cannot ever be executed if `T` is uninhabited: /// This will statically either panic, or do nothing. /// @@ -1291,7 +1239,7 @@ extern "rust-intrinsic" { /// - If the code actually wants to work on the address the pointer points to, it can use `as` /// casts or [`ptr.addr()`][pointer::addr]. /// - /// Turning a `*mut T` into an `&mut T`: + /// Turning a `*mut T` into a `&mut T`: /// /// ``` /// let ptr: *mut i32 = &mut 0; @@ -1303,7 +1251,7 @@ extern "rust-intrinsic" { /// let ref_casted = unsafe { &mut *ptr }; /// ``` /// - /// Turning an `&mut T` into an `&mut U`: + /// Turning a `&mut T` into a `&mut U`: /// /// ``` /// let ptr = &mut 0; @@ -1316,7 +1264,7 @@ extern "rust-intrinsic" { /// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) }; /// ``` /// - /// Turning an `&str` into a `&[u8]`: + /// Turning a `&str` into a `&[u8]`: /// /// ``` /// // this is not a good way to do this. @@ -1402,7 +1350,7 @@ extern "rust-intrinsic" { /// } /// /// // This gets rid of the type safety problems; `&mut *` will *only* give - /// // you an `&mut T` from an `&mut T` or `*mut T`. + /// // you a `&mut T` from a `&mut T` or `*mut T`. /// fn split_at_mut_casts(slice: &mut [T], mid: usize) /// -> (&mut [T], &mut [T]) { /// let len = slice.len(); @@ -1983,7 +1931,7 @@ extern "rust-intrinsic" { #[rustc_safe_intrinsic] pub fn frem_algebraic(a: T, b: T) -> T; - /// Convert with LLVM’s fptoui/fptosi, which may return undef for values out of range + /// Converts with LLVM’s fptoui/fptosi, which may return undef for values out of range /// () /// /// Stabilized as [`f32::to_int_unchecked`] and [`f64::to_int_unchecked`]. @@ -2424,20 +2372,6 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn discriminant_value(v: &T) -> ::Discriminant; - /// Returns the number of variants of the type `T` cast to a `usize`; - /// if `T` has no variants, returns `0`. Uninhabited variants will be counted. - /// - /// Note that, unlike most intrinsics, this is safe to call; - /// it does not require an `unsafe` block. - /// Therefore, implementations must not require the user to uphold - /// any safety invariants. - /// - /// The to-be-stabilized version of this intrinsic is [`crate::mem::variant_count`]. - #[rustc_const_unstable(feature = "variant_count", issue = "73662")] - #[rustc_safe_intrinsic] - #[rustc_nounwind] - pub fn variant_count() -> usize; - /// Rust's "try catch" construct for unwinding. Invokes the function pointer `try_fn` with the /// data pointer `data`, and calls `catch_fn` if unwinding occurs while `try_fn` runs. /// @@ -2502,11 +2436,13 @@ extern "rust-intrinsic" { /// /// # Safety /// - /// It's UB to call this if any of the *bytes* in `*a` or `*b` are uninitialized or carry a - /// pointer value. + /// It's UB to call this if any of the *bytes* in `*a` or `*b` are uninitialized. /// Note that this is a stricter criterion than just the *values* being /// fully-initialized: if `T` has padding, it's UB to call this intrinsic. /// + /// At compile-time, it is furthermore UB to call this if any of the bytes + /// in `*a` or `*b` have provenance. + /// /// (The implementation is allowed to branch on the results of comparisons, /// which is UB if any of their inputs are `undef`.) #[rustc_const_unstable(feature = "const_intrinsic_raw_eq", issue = "none")] @@ -2773,8 +2709,11 @@ pub const unsafe fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) // Runtime NOP } -/// `ptr` must point to a vtable. /// The intrinsic will return the size stored in that vtable. +/// +/// # Safety +/// +/// `ptr` must point to a vtable. #[rustc_nounwind] #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] @@ -2783,8 +2722,11 @@ pub unsafe fn vtable_size(_ptr: *const ()) -> usize { unreachable!() } -/// `ptr` must point to a vtable. /// The intrinsic will return the alignment stored in that vtable. +/// +/// # Safety +/// +/// `ptr` must point to a vtable. #[rustc_nounwind] #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] @@ -2793,6 +2735,142 @@ pub unsafe fn vtable_align(_ptr: *const ()) -> usize { unreachable!() } +/// The size of a type in bytes. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// More specifically, this is the offset in bytes between successive +/// items of the same type, including alignment padding. +/// +/// The stabilized version of this intrinsic is [`core::mem::size_of`]. +#[rustc_nounwind] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_const_stable(feature = "const_size_of", since = "1.40.0")] +#[rustc_intrinsic] +#[rustc_intrinsic_must_be_overridden] +pub const fn size_of() -> usize { + unreachable!() +} + +/// The minimum alignment of a type. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized version of this intrinsic is [`core::mem::align_of`]. +#[rustc_nounwind] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_const_stable(feature = "const_min_align_of", since = "1.40.0")] +#[rustc_intrinsic] +#[rustc_intrinsic_must_be_overridden] +pub const fn min_align_of() -> usize { + unreachable!() +} + +/// The preferred alignment of a type. +/// +/// This intrinsic does not have a stable counterpart. +/// It's "tracking issue" is [#91971](https://github.com/rust-lang/rust/issues/91971). +#[rustc_nounwind] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_const_unstable(feature = "const_pref_align_of", issue = "91971")] +#[rustc_intrinsic] +#[rustc_intrinsic_must_be_overridden] +pub const unsafe fn pref_align_of() -> usize { + unreachable!() +} + +/// Returns the number of variants of the type `T` cast to a `usize`; +/// if `T` has no variants, returns `0`. Uninhabited variants will be counted. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The to-be-stabilized version of this intrinsic is [`crate::mem::variant_count`]. +#[rustc_nounwind] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_const_unstable(feature = "variant_count", issue = "73662")] +#[rustc_intrinsic] +#[rustc_intrinsic_must_be_overridden] +pub const fn variant_count() -> usize { + unreachable!() +} + +/// The size of the referenced value in bytes. +/// +/// The stabilized version of this intrinsic is [`crate::mem::size_of_val`]. +/// +/// # Safety +/// +/// See [`crate::mem::size_of_val_raw`] for safety conditions. +#[rustc_nounwind] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")] +#[rustc_intrinsic] +#[rustc_intrinsic_must_be_overridden] +pub const unsafe fn size_of_val(_ptr: *const T) -> usize { + unreachable!() +} + +/// The required alignment of the referenced value. +/// +/// The stabilized version of this intrinsic is [`core::mem::align_of_val`]. +/// +/// # Safety +/// +/// See [`crate::mem::align_of_val_raw`] for safety conditions. +#[rustc_nounwind] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_const_unstable(feature = "const_align_of_val", issue = "46571")] +#[rustc_intrinsic] +#[rustc_intrinsic_must_be_overridden] +pub const unsafe fn min_align_of_val(_ptr: *const T) -> usize { + unreachable!() +} + +/// Gets a static string slice containing the name of a type. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized version of this intrinsic is [`core::any::type_name`]. +#[rustc_nounwind] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_const_unstable(feature = "const_type_name", issue = "63084")] +#[rustc_intrinsic] +#[rustc_intrinsic_must_be_overridden] +pub const fn type_name() -> &'static str { + unreachable!() +} + +/// Gets an identifier which is globally unique to the specified type. This +/// function will return the same value for a type regardless of whichever +/// crate it is invoked in. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized version of this intrinsic is [`core::any::TypeId::of`]. +#[rustc_nounwind] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_const_unstable(feature = "const_type_id", issue = "77125")] +#[rustc_intrinsic] +#[rustc_intrinsic_must_be_overridden] +pub const fn type_id() -> u128 { + unreachable!() +} + /// Lowers in MIR to `Rvalue::Aggregate` with `AggregateKind::RawPtr`. /// /// This is used to implement functions like `slice::from_raw_parts_mut` and diff --git a/core/src/intrinsics/mir.rs b/core/src/intrinsics/mir.rs index 1daf1d723fb95..c7cec396e1f2e 100644 --- a/core/src/intrinsics/mir.rs +++ b/core/src/intrinsics/mir.rs @@ -247,6 +247,8 @@ //! otherwise branch. //! - [`Call`] has an associated function as well, with special syntax: //! `Call(ret_val = function(arg1, arg2, ...), ReturnTo(next_block), UnwindContinue())`. +//! - [`TailCall`] does not have a return destination or next block, so its syntax is just +//! `TailCall(function(arg1, arg2, ...))`. #![unstable( feature = "custom_mir", @@ -276,8 +278,7 @@ pub enum UnwindTerminateReason { InCleanup, } -pub use UnwindTerminateReason::Abi as ReasonAbi; -pub use UnwindTerminateReason::InCleanup as ReasonInCleanup; +pub use UnwindTerminateReason::{Abi as ReasonAbi, InCleanup as ReasonInCleanup}; macro_rules! define { ($name:literal, $( #[ $meta:meta ] )* fn $($sig:tt)*) => { @@ -351,6 +352,12 @@ define!("mir_call", /// - [`UnwindCleanup`] fn Call(call: (), goto: ReturnToArg, unwind_action: UnwindActionArg) ); +define!("mir_tail_call", + /// Call a function. + /// + /// The argument must be of the form `fun(arg1, arg2, ...)`. + fn TailCall(call: T) +); define!("mir_unwind_resume", /// A terminator that resumes the unwinding. fn UnwindResume() diff --git a/core/src/intrinsics/simd.rs b/core/src/intrinsics/simd.rs index 30734c020b39b..221724d7b4ae9 100644 --- a/core/src/intrinsics/simd.rs +++ b/core/src/intrinsics/simd.rs @@ -3,7 +3,7 @@ //! In this module, a "vector" is any `repr(simd)` type. extern "rust-intrinsic" { - /// Insert an element into a vector, returning the updated vector. + /// Inserts an element into a vector, returning the updated vector. /// /// `T` must be a vector with element type `U`. /// @@ -13,7 +13,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_insert(x: T, idx: u32, val: U) -> T; - /// Extract an element from a vector. + /// Extracts an element from a vector. /// /// `T` must be a vector with element type `U`. /// @@ -23,25 +23,25 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_extract(x: T, idx: u32) -> U; - /// Add two simd vectors elementwise. + /// Adds two simd vectors elementwise. /// /// `T` must be a vector of integer or floating point primitive types. #[rustc_nounwind] pub fn simd_add(x: T, y: T) -> T; - /// Subtract `rhs` from `lhs` elementwise. + /// Subtracts `rhs` from `lhs` elementwise. /// /// `T` must be a vector of integer or floating point primitive types. #[rustc_nounwind] pub fn simd_sub(lhs: T, rhs: T) -> T; - /// Multiply two simd vectors elementwise. + /// Multiplies two simd vectors elementwise. /// /// `T` must be a vector of integer or floating point primitive types. #[rustc_nounwind] pub fn simd_mul(x: T, y: T) -> T; - /// Divide `lhs` by `rhs` elementwise. + /// Divides `lhs` by `rhs` elementwise. /// /// `T` must be a vector of integer or floating point primitive types. /// @@ -51,7 +51,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_div(lhs: T, rhs: T) -> T; - /// Remainder of two vectors elementwise + /// Returns remainder of two vectors elementwise. /// /// `T` must be a vector of integer or floating point primitive types. /// @@ -61,9 +61,9 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_rem(lhs: T, rhs: T) -> T; - /// Elementwise vector left shift, with UB on overflow. + /// Shifts vector left elementwise, with UB on overflow. /// - /// Shift `lhs` left by `rhs`, shifting in sign bits for signed types. + /// Shifts `lhs` left by `rhs`, shifting in sign bits for signed types. /// /// `T` must be a vector of integer primitive types. /// @@ -73,11 +73,11 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_shl(lhs: T, rhs: T) -> T; - /// Elementwise vector right shift, with UB on overflow. + /// Shifts vector right elementwise, with UB on overflow. /// /// `T` must be a vector of integer primitive types. /// - /// Shift `lhs` right by `rhs`, shifting in sign bits for signed types. + /// Shifts `lhs` right by `rhs`, shifting in sign bits for signed types. /// /// # Safety /// @@ -85,25 +85,25 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_shr(lhs: T, rhs: T) -> T; - /// Elementwise vector "and". + /// "Ands" vectors elementwise. /// /// `T` must be a vector of integer primitive types. #[rustc_nounwind] pub fn simd_and(x: T, y: T) -> T; - /// Elementwise vector "or". + /// "Ors" vectors elementwise. /// /// `T` must be a vector of integer primitive types. #[rustc_nounwind] pub fn simd_or(x: T, y: T) -> T; - /// Elementwise vector "exclusive or". + /// "Exclusive ors" vectors elementwise. /// /// `T` must be a vector of integer primitive types. #[rustc_nounwind] pub fn simd_xor(x: T, y: T) -> T; - /// Numerically cast a vector, elementwise. + /// Numerically casts a vector, elementwise. /// /// `T` and `U` must be vectors of integer or floating point primitive types, and must have the /// same length. @@ -124,7 +124,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_cast(x: T) -> U; - /// Numerically cast a vector, elementwise. + /// Numerically casts a vector, elementwise. /// /// `T` and `U` be a vectors of integer or floating point primitive types, and must have the /// same length. @@ -138,7 +138,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_as(x: T) -> U; - /// Elementwise negation of a vector. + /// Negates a vector elementwise. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -146,13 +146,13 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_neg(x: T) -> T; - /// Elementwise absolute value of a vector. + /// Returns absolute value of a vector, elementwise. /// /// `T` must be a vector of floating-point primitive types. #[rustc_nounwind] pub fn simd_fabs(x: T) -> T; - /// Elementwise minimum of two vectors. + /// Returns the minimum of two vectors, elementwise. /// /// `T` must be a vector of floating-point primitive types. /// @@ -160,7 +160,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_fmin(x: T, y: T) -> T; - /// Elementwise maximum of two vectors. + /// Returns the maximum of two vectors, elementwise. /// /// `T` must be a vector of floating-point primitive types. /// @@ -228,7 +228,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_ge(x: T, y: T) -> U; - /// Shuffle two vectors by const indices. + /// Shuffles two vectors by const indices. /// /// `T` must be a vector. /// @@ -243,19 +243,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_shuffle(x: T, y: T, idx: U) -> V; - /// Shuffle two vectors by const indices. - /// - /// `T` must be a vector. - /// - /// `U` must be a vector with the same element type as `T` and the same length as `IDX`. - /// - /// Returns a new vector such that element `i` is selected from `xy[IDX[i]]`, where `xy` - /// is the concatenation of `x` and `y`. It is a compile-time error if `IDX[i]` is out-of-bounds - /// of `xy`. - #[rustc_nounwind] - pub fn simd_shuffle_generic(x: T, y: T) -> U; - - /// Read a vector of pointers. + /// Reads a vector of pointers. /// /// `T` must be a vector. /// @@ -275,7 +263,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_gather(val: T, ptr: U, mask: V) -> T; - /// Write to a vector of pointers. + /// Writes to a vector of pointers. /// /// `T` must be a vector. /// @@ -298,7 +286,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_scatter(val: T, ptr: U, mask: V); - /// Read a vector of pointers. + /// Reads a vector of pointers. /// /// `T` must be a vector. /// @@ -320,7 +308,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_masked_load(mask: V, ptr: U, val: T) -> T; - /// Write to a vector of pointers. + /// Writes to a vector of pointers. /// /// `T` must be a vector. /// @@ -341,13 +329,13 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_masked_store(mask: V, ptr: U, val: T); - /// Add two simd vectors elementwise, with saturation. + /// Adds two simd vectors elementwise, with saturation. /// /// `T` must be a vector of integer primitive types. #[rustc_nounwind] pub fn simd_saturating_add(x: T, y: T) -> T; - /// Subtract two simd vectors elementwise, with saturation. + /// Subtracts two simd vectors elementwise, with saturation. /// /// `T` must be a vector of integer primitive types. /// @@ -355,7 +343,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_saturating_sub(lhs: T, rhs: T) -> T; - /// Add elements within a vector from left to right. + /// Adds elements within a vector from left to right. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -365,7 +353,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_add_ordered(x: T, y: U) -> U; - /// Add elements within a vector in arbitrary order. May also be re-associated with + /// Adds elements within a vector in arbitrary order. May also be re-associated with /// unordered additions on the inputs/outputs. /// /// `T` must be a vector of integer or floating-point primitive types. @@ -374,7 +362,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_add_unordered(x: T) -> U; - /// Multiply elements within a vector from left to right. + /// Multiplies elements within a vector from left to right. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -384,7 +372,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_mul_ordered(x: T, y: U) -> U; - /// Multiply elements within a vector in arbitrary order. May also be re-associated with + /// Multiplies elements within a vector in arbitrary order. May also be re-associated with /// unordered additions on the inputs/outputs. /// /// `T` must be a vector of integer or floating-point primitive types. @@ -393,7 +381,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_mul_unordered(x: T) -> U; - /// Check if all mask values are true. + /// Checks if all mask values are true. /// /// `T` must be a vector of integer primitive types. /// @@ -402,7 +390,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_all(x: T) -> bool; - /// Check if any mask value is true. + /// Checks if any mask value is true. /// /// `T` must be a vector of integer primitive types. /// @@ -411,7 +399,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_any(x: T) -> bool; - /// Return the maximum element of a vector. + /// Returns the maximum element of a vector. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -421,7 +409,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_max(x: T) -> U; - /// Return the minimum element of a vector. + /// Returns the minimum element of a vector. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -431,7 +419,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_min(x: T) -> U; - /// Logical "and" all elements together. + /// Logical "ands" all elements together. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -439,7 +427,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_and(x: T) -> U; - /// Logical "or" all elements together. + /// Logical "ors" all elements together. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -447,7 +435,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_or(x: T) -> U; - /// Logical "exclusive or" all elements together. + /// Logical "exclusive ors" all elements together. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -455,7 +443,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_xor(x: T) -> U; - /// Truncate an integer vector to a bitmask. + /// Truncates an integer vector to a bitmask. /// /// `T` must be an integer vector. /// @@ -491,7 +479,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_bitmask(x: T) -> U; - /// Select elements from a mask. + /// Selects elements from a mask. /// /// `M` must be an integer vector. /// @@ -506,7 +494,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_select(mask: M, if_true: T, if_false: T) -> T; - /// Select elements from a bitmask. + /// Selects elements from a bitmask. /// /// `M` must be an unsigned integer or array of `u8`, matching `simd_bitmask`. /// @@ -523,7 +511,8 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_select_bitmask(m: M, yes: T, no: T) -> T; - /// Elementwise calculates the offset from a pointer vector, potentially wrapping. + /// Calculates the offset from a pointer vector elementwise, potentially + /// wrapping. /// /// `T` must be a vector of pointers. /// @@ -533,13 +522,13 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_arith_offset(ptr: T, offset: U) -> T; - /// Cast a vector of pointers. + /// Casts a vector of pointers. /// /// `T` and `U` must be vectors of pointers with the same number of elements. #[rustc_nounwind] pub fn simd_cast_ptr(ptr: T) -> U; - /// Expose a vector of pointers as a vector of addresses. + /// Exposes a vector of pointers as a vector of addresses. /// /// `T` must be a vector of pointers. /// @@ -547,7 +536,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_expose_provenance(ptr: T) -> U; - /// Create a vector of pointers from a vector of addresses. + /// Creates a vector of pointers from a vector of addresses. /// /// `T` must be a vector of `usize`. /// @@ -555,56 +544,56 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_with_exposed_provenance(addr: T) -> U; - /// Swap bytes of each element. + /// Swaps bytes of each element. /// /// `T` must be a vector of integers. #[rustc_nounwind] pub fn simd_bswap(x: T) -> T; - /// Reverse bits of each element. + /// Reverses bits of each element. /// /// `T` must be a vector of integers. #[rustc_nounwind] pub fn simd_bitreverse(x: T) -> T; - /// Count the leading zeros of each element. + /// Counts the leading zeros of each element. /// /// `T` must be a vector of integers. #[rustc_nounwind] pub fn simd_ctlz(x: T) -> T; - /// Count the number of ones in each element. + /// Counts the number of ones in each element. /// /// `T` must be a vector of integers. #[rustc_nounwind] pub fn simd_ctpop(x: T) -> T; - /// Count the trailing zeros of each element. + /// Counts the trailing zeros of each element. /// /// `T` must be a vector of integers. #[rustc_nounwind] pub fn simd_cttz(x: T) -> T; - /// Round up each element to the next highest integer-valued float. + /// Rounds up each element to the next highest integer-valued float. /// /// `T` must be a vector of floats. #[rustc_nounwind] pub fn simd_ceil(x: T) -> T; - /// Round down each element to the next lowest integer-valued float. + /// Rounds down each element to the next lowest integer-valued float. /// /// `T` must be a vector of floats. #[rustc_nounwind] pub fn simd_floor(x: T) -> T; - /// Round each element to the closest integer-valued float. + /// Rounds each element to the closest integer-valued float. /// Ties are resolved by rounding away from 0. /// /// `T` must be a vector of floats. #[rustc_nounwind] pub fn simd_round(x: T) -> T; - /// Return the integer part of each element as an integer-valued float. + /// Returns the integer part of each element as an integer-valued float. /// In other words, non-integer values are truncated towards zero. /// /// `T` must be a vector of floats. diff --git a/core/src/io/borrowed_buf.rs b/core/src/io/borrowed_buf.rs index d497da33dd923..dbc60aa8154c6 100644 --- a/core/src/io/borrowed_buf.rs +++ b/core/src/io/borrowed_buf.rs @@ -44,7 +44,7 @@ impl Debug for BorrowedBuf<'_> { } } -/// Create a new `BorrowedBuf` from a fully initialized slice. +/// Creates a new `BorrowedBuf` from a fully initialized slice. impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data> { #[inline] fn from(slice: &'data mut [u8]) -> BorrowedBuf<'data> { @@ -59,7 +59,7 @@ impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data> { } } -/// Create a new `BorrowedBuf` from an uninitialized buffer. +/// Creates a new `BorrowedBuf` from an uninitialized buffer. /// /// Use `set_init` if part of the buffer is known to be already initialized. impl<'data> From<&'data mut [MaybeUninit]> for BorrowedBuf<'data> { @@ -174,7 +174,7 @@ pub struct BorrowedCursor<'a> { } impl<'a> BorrowedCursor<'a> { - /// Reborrow this cursor by cloning it with a smaller lifetime. + /// Reborrows this cursor by cloning it with a smaller lifetime. /// /// Since a cursor maintains unique access to its underlying buffer, the borrowed cursor is /// not accessible while the new cursor exists. @@ -247,7 +247,7 @@ impl<'a> BorrowedCursor<'a> { unsafe { self.buf.buf.get_unchecked_mut(self.buf.filled..) } } - /// Advance the cursor by asserting that `n` bytes have been filled. + /// Advances the cursor by asserting that `n` bytes have been filled. /// /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements @@ -268,7 +268,7 @@ impl<'a> BorrowedCursor<'a> { self } - /// Advance the cursor by asserting that `n` bytes have been filled. + /// Advances the cursor by asserting that `n` bytes have been filled. /// /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements diff --git a/core/src/iter/adapters/cloned.rs b/core/src/iter/adapters/cloned.rs index 1a106ef97942b..aea6d64281aec 100644 --- a/core/src/iter/adapters/cloned.rs +++ b/core/src/iter/adapters/cloned.rs @@ -1,9 +1,9 @@ -use crate::iter::adapters::{ - zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce, -}; +use core::num::NonZero; + +use crate::iter::adapters::zip::try_get_unchecked; +use crate::iter::adapters::{SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen, UncheckedIterator}; use crate::ops::Try; -use core::num::NonZero; /// An iterator that clones the elements of an underlying iterator. /// diff --git a/core/src/iter/adapters/copied.rs b/core/src/iter/adapters/copied.rs index d772e7b36e09e..23e4e25ab5388 100644 --- a/core/src/iter/adapters/copied.rs +++ b/core/src/iter/adapters/copied.rs @@ -1,9 +1,7 @@ -use crate::iter::adapters::{ - zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce, -}; +use crate::iter::adapters::zip::try_get_unchecked; +use crate::iter::adapters::{SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen}; -use crate::mem::MaybeUninit; -use crate::mem::SizedTypeProperties; +use crate::mem::{MaybeUninit, SizedTypeProperties}; use crate::num::NonZero; use crate::ops::Try; use crate::{array, ptr}; diff --git a/core/src/iter/adapters/cycle.rs b/core/src/iter/adapters/cycle.rs index b35ed8442032d..6cb1a3a46763e 100644 --- a/core/src/iter/adapters/cycle.rs +++ b/core/src/iter/adapters/cycle.rs @@ -1,5 +1,6 @@ +use crate::iter::FusedIterator; use crate::num::NonZero; -use crate::{iter::FusedIterator, ops::Try}; +use crate::ops::Try; /// An iterator that repeats endlessly. /// diff --git a/core/src/iter/adapters/enumerate.rs b/core/src/iter/adapters/enumerate.rs index 7adbabf69e490..ac15e3767fc09 100644 --- a/core/src/iter/adapters/enumerate.rs +++ b/core/src/iter/adapters/enumerate.rs @@ -1,6 +1,5 @@ -use crate::iter::adapters::{ - zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce, -}; +use crate::iter::adapters::zip::try_get_unchecked; +use crate::iter::adapters::{SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused, TrustedLen}; use crate::num::NonZero; use crate::ops::Try; diff --git a/core/src/iter/adapters/filter.rs b/core/src/iter/adapters/filter.rs index ba49070329c22..dd08cd6f61c4c 100644 --- a/core/src/iter/adapters/filter.rs +++ b/core/src/iter/adapters/filter.rs @@ -1,11 +1,13 @@ -use crate::fmt; -use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; -use crate::num::NonZero; -use crate::ops::Try; use core::array; use core::mem::MaybeUninit; use core::ops::ControlFlow; +use crate::fmt; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused}; +use crate::num::NonZero; +use crate::ops::Try; + /// An iterator that filters the elements of `iter` with `predicate`. /// /// This `struct` is created by the [`filter`] method on [`Iterator`]. See its diff --git a/core/src/iter/adapters/filter_map.rs b/core/src/iter/adapters/filter_map.rs index 2126619a58a87..914ef6131771f 100644 --- a/core/src/iter/adapters/filter_map.rs +++ b/core/src/iter/adapters/filter_map.rs @@ -1,4 +1,5 @@ -use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused}; use crate::mem::{ManuallyDrop, MaybeUninit}; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/core/src/iter/adapters/flatten.rs b/core/src/iter/adapters/flatten.rs index 145c9d3dacc84..0023b46031f12 100644 --- a/core/src/iter/adapters/flatten.rs +++ b/core/src/iter/adapters/flatten.rs @@ -1,13 +1,11 @@ use crate::iter::adapters::SourceIter; use crate::iter::{ - Cloned, Copied, Filter, FilterMap, Fuse, FusedIterator, InPlaceIterable, Map, TrustedFused, - TrustedLen, + Cloned, Copied, Empty, Filter, FilterMap, Fuse, FusedIterator, InPlaceIterable, Map, Once, + OnceWith, TrustedFused, TrustedLen, }; -use crate::iter::{Empty, Once, OnceWith}; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; -use crate::result; -use crate::{array, fmt, option}; +use crate::{array, fmt, option, result}; /// An iterator that maps each element to an iterator, and yields the elements /// of the produced iterators. diff --git a/core/src/iter/adapters/inspect.rs b/core/src/iter/adapters/inspect.rs index 1c4656a649a37..0e2a68a503e44 100644 --- a/core/src/iter/adapters/inspect.rs +++ b/core/src/iter/adapters/inspect.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused}; use crate::num::NonZero; use crate::ops::Try; diff --git a/core/src/iter/adapters/map.rs b/core/src/iter/adapters/map.rs index 6e163e20d8ec4..007c2d5acc2d0 100644 --- a/core/src/iter/adapters/map.rs +++ b/core/src/iter/adapters/map.rs @@ -1,7 +1,6 @@ use crate::fmt; -use crate::iter::adapters::{ - zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce, -}; +use crate::iter::adapters::zip::try_get_unchecked; +use crate::iter::adapters::{SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, UncheckedIterator}; use crate::num::NonZero; use crate::ops::Try; diff --git a/core/src/iter/adapters/map_while.rs b/core/src/iter/adapters/map_while.rs index 9ad50048c25ea..4e7327938d72a 100644 --- a/core/src/iter/adapters/map_while.rs +++ b/core/src/iter/adapters/map_while.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::iter::{adapters::SourceIter, InPlaceIterable}; +use crate::iter::adapters::SourceIter; +use crate::iter::InPlaceIterable; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/core/src/iter/adapters/map_windows.rs b/core/src/iter/adapters/map_windows.rs index 182775121369e..cb13023c85c41 100644 --- a/core/src/iter/adapters/map_windows.rs +++ b/core/src/iter/adapters/map_windows.rs @@ -1,9 +1,6 @@ -use crate::{ - fmt, - iter::FusedIterator, - mem::{self, MaybeUninit}, - ptr, -}; +use crate::iter::FusedIterator; +use crate::mem::{self, MaybeUninit}; +use crate::{fmt, ptr}; /// An iterator over the mapped windows of another iterator. /// diff --git a/core/src/iter/adapters/mod.rs b/core/src/iter/adapters/mod.rs index 1bde4488cc9de..96158c43318ea 100644 --- a/core/src/iter/adapters/mod.rs +++ b/core/src/iter/adapters/mod.rs @@ -28,51 +28,38 @@ mod take; mod take_while; mod zip; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::{ - chain::Chain, cycle::Cycle, enumerate::Enumerate, filter::Filter, filter_map::FilterMap, - flatten::FlatMap, fuse::Fuse, inspect::Inspect, map::Map, peekable::Peekable, rev::Rev, - scan::Scan, skip::Skip, skip_while::SkipWhile, take::Take, take_while::TakeWhile, zip::Zip, -}; - #[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] pub use self::array_chunks::ArrayChunks; - #[unstable(feature = "std_internals", issue = "none")] pub use self::by_ref_sized::ByRefSized; - #[unstable(feature = "iter_chain", reason = "recently added", issue = "125964")] pub use self::chain::chain; - #[stable(feature = "iter_cloned", since = "1.1.0")] pub use self::cloned::Cloned; - -#[stable(feature = "iterator_step_by", since = "1.28.0")] -pub use self::step_by::StepBy; - -#[stable(feature = "iterator_flatten", since = "1.29.0")] -pub use self::flatten::Flatten; - #[stable(feature = "iter_copied", since = "1.36.0")] pub use self::copied::Copied; - +#[stable(feature = "iterator_flatten", since = "1.29.0")] +pub use self::flatten::Flatten; #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] pub use self::intersperse::{Intersperse, IntersperseWith}; - #[stable(feature = "iter_map_while", since = "1.57.0")] pub use self::map_while::MapWhile; - #[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] pub use self::map_windows::MapWindows; - +#[stable(feature = "iterator_step_by", since = "1.28.0")] +pub use self::step_by::StepBy; +#[stable(feature = "iter_zip", since = "1.59.0")] +pub use self::zip::zip; #[unstable(feature = "trusted_random_access", issue = "none")] pub use self::zip::TrustedRandomAccess; - #[unstable(feature = "trusted_random_access", issue = "none")] pub use self::zip::TrustedRandomAccessNoCoerce; - -#[stable(feature = "iter_zip", since = "1.59.0")] -pub use self::zip::zip; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::{ + chain::Chain, cycle::Cycle, enumerate::Enumerate, filter::Filter, filter_map::FilterMap, + flatten::FlatMap, fuse::Fuse, inspect::Inspect, map::Map, peekable::Peekable, rev::Rev, + scan::Scan, skip::Skip, skip_while::SkipWhile, take::Take, take_while::TakeWhile, zip::Zip, +}; /// This trait provides transitive access to source-stage in an iterator-adapter pipeline /// under the conditions that diff --git a/core/src/iter/adapters/peekable.rs b/core/src/iter/adapters/peekable.rs index 65ba42920c93d..a11b73cbe8e2d 100644 --- a/core/src/iter/adapters/peekable.rs +++ b/core/src/iter/adapters/peekable.rs @@ -1,4 +1,5 @@ -use crate::iter::{adapters::SourceIter, FusedIterator, TrustedLen}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, TrustedLen}; use crate::ops::{ControlFlow, Try}; /// An iterator with a `peek()` that returns an optional reference to the next diff --git a/core/src/iter/adapters/scan.rs b/core/src/iter/adapters/scan.rs index d261a535b183a..7ba7ed2fdd0d5 100644 --- a/core/src/iter/adapters/scan.rs +++ b/core/src/iter/adapters/scan.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::iter::{adapters::SourceIter, InPlaceIterable}; +use crate::iter::adapters::SourceIter; +use crate::iter::InPlaceIterable; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/core/src/iter/adapters/skip.rs b/core/src/iter/adapters/skip.rs index f51a2c39b8e28..8ba2e2a8f2dd7 100644 --- a/core/src/iter/adapters/skip.rs +++ b/core/src/iter/adapters/skip.rs @@ -1,8 +1,8 @@ use crate::intrinsics::unlikely; use crate::iter::adapters::zip::try_get_unchecked; -use crate::iter::TrustedFused; +use crate::iter::adapters::SourceIter; use crate::iter::{ - adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedLen, TrustedRandomAccess, + FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, }; use crate::num::NonZero; diff --git a/core/src/iter/adapters/skip_while.rs b/core/src/iter/adapters/skip_while.rs index 8001e6e64713a..8ae453e76fa0d 100644 --- a/core/src/iter/adapters/skip_while.rs +++ b/core/src/iter/adapters/skip_while.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused}; use crate::num::NonZero; use crate::ops::Try; diff --git a/core/src/iter/adapters/step_by.rs b/core/src/iter/adapters/step_by.rs index abdf2f415fe55..72eb72a76c66c 100644 --- a/core/src/iter/adapters/step_by.rs +++ b/core/src/iter/adapters/step_by.rs @@ -1,9 +1,7 @@ -use crate::{ - intrinsics, - iter::{from_fn, TrustedLen, TrustedRandomAccess}, - num::NonZero, - ops::{Range, Try}, -}; +use crate::intrinsics; +use crate::iter::{from_fn, TrustedLen, TrustedRandomAccess}; +use crate::num::NonZero; +use crate::ops::{Range, Try}; /// An iterator for stepping iterators by a custom amount. /// @@ -414,9 +412,9 @@ unsafe impl StepByBackImpl for St /// These only work for unsigned types, and will need to be reworked /// if you want to use it to specialize on signed types. /// -/// Currently these are only implemented for integers up to usize due to -/// correctness issues around ExactSizeIterator impls on 16bit platforms. -/// And since ExactSizeIterator is a prerequisite for backwards iteration +/// Currently these are only implemented for integers up to `usize` due to +/// correctness issues around `ExactSizeIterator` impls on 16bit platforms. +/// And since `ExactSizeIterator` is a prerequisite for backwards iteration /// and we must consistently specialize backwards and forwards iteration /// that makes the situation complicated enough that it's not covered /// for now. diff --git a/core/src/iter/adapters/take.rs b/core/src/iter/adapters/take.rs index 6870c677b1e07..297dd0acaddc1 100644 --- a/core/src/iter/adapters/take.rs +++ b/core/src/iter/adapters/take.rs @@ -1,8 +1,6 @@ use crate::cmp; -use crate::iter::{ - adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, - TrustedRandomAccess, -}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, TrustedRandomAccess}; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/core/src/iter/adapters/take_while.rs b/core/src/iter/adapters/take_while.rs index d3f09ab356ad8..06028ea98e7fd 100644 --- a/core/src/iter/adapters/take_while.rs +++ b/core/src/iter/adapters/take_while.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused}; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/core/src/iter/adapters/zip.rs b/core/src/iter/adapters/zip.rs index 2e885f06b5272..0c38811590877 100644 --- a/core/src/iter/adapters/zip.rs +++ b/core/src/iter/adapters/zip.rs @@ -1,7 +1,8 @@ use crate::cmp; use crate::fmt::{self, Debug}; -use crate::iter::{FusedIterator, TrustedFused}; -use crate::iter::{InPlaceIterable, SourceIter, TrustedLen, UncheckedIterator}; +use crate::iter::{ + FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen, UncheckedIterator, +}; use crate::num::NonZero; /// An iterator that iterates two other iterators simultaneously. diff --git a/core/src/iter/mod.rs b/core/src/iter/mod.rs index 921c75c85f161..1f2bf49d2b729 100644 --- a/core/src/iter/mod.rs +++ b/core/src/iter/mod.rs @@ -380,16 +380,46 @@ macro_rules! impl_fold_via_try_fold { }; } +#[unstable(feature = "iter_chain", reason = "recently added", issue = "125964")] +pub use self::adapters::chain; +pub(crate) use self::adapters::try_process; +#[stable(feature = "iter_zip", since = "1.59.0")] +pub use self::adapters::zip; +#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] +pub use self::adapters::ArrayChunks; +#[unstable(feature = "std_internals", issue = "none")] +pub use self::adapters::ByRefSized; +#[stable(feature = "iter_cloned", since = "1.1.0")] +pub use self::adapters::Cloned; +#[stable(feature = "iter_copied", since = "1.36.0")] +pub use self::adapters::Copied; +#[stable(feature = "iterator_flatten", since = "1.29.0")] +pub use self::adapters::Flatten; +#[stable(feature = "iter_map_while", since = "1.57.0")] +pub use self::adapters::MapWhile; +#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] +pub use self::adapters::MapWindows; +#[unstable(feature = "inplace_iteration", issue = "none")] +pub use self::adapters::SourceIter; +#[stable(feature = "iterator_step_by", since = "1.28.0")] +pub use self::adapters::StepBy; +#[unstable(feature = "trusted_random_access", issue = "none")] +pub use self::adapters::TrustedRandomAccess; +#[unstable(feature = "trusted_random_access", issue = "none")] +pub use self::adapters::TrustedRandomAccessNoCoerce; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::traits::Iterator; - +pub use self::adapters::{ + Chain, Cycle, Enumerate, Filter, FilterMap, FlatMap, Fuse, Inspect, Map, Peekable, Rev, Scan, + Skip, SkipWhile, Take, TakeWhile, Zip, +}; +#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +pub use self::adapters::{Intersperse, IntersperseWith}; #[unstable( feature = "step_trait", reason = "likely to be replaced by finer-grained traits", issue = "42168" )] pub use self::range::Step; - #[unstable( feature = "iter_from_coroutine", issue = "43122", @@ -412,59 +442,24 @@ pub use self::sources::{repeat_n, RepeatN}; pub use self::sources::{repeat_with, RepeatWith}; #[stable(feature = "iter_successors", since = "1.34.0")] pub use self::sources::{successors, Successors}; - #[stable(feature = "fused", since = "1.26.0")] pub use self::traits::FusedIterator; #[unstable(issue = "none", feature = "inplace_iteration")] pub use self::traits::InPlaceIterable; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::traits::Iterator; #[unstable(issue = "none", feature = "trusted_fused")] pub use self::traits::TrustedFused; #[unstable(feature = "trusted_len", issue = "37572")] pub use self::traits::TrustedLen; #[unstable(feature = "trusted_step", issue = "85731")] pub use self::traits::TrustedStep; +pub(crate) use self::traits::UncheckedIterator; #[stable(feature = "rust1", since = "1.0.0")] pub use self::traits::{ DoubleEndedIterator, ExactSizeIterator, Extend, FromIterator, IntoIterator, Product, Sum, }; -#[unstable(feature = "iter_chain", reason = "recently added", issue = "125964")] -pub use self::adapters::chain; -#[stable(feature = "iter_zip", since = "1.59.0")] -pub use self::adapters::zip; -#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] -pub use self::adapters::ArrayChunks; -#[unstable(feature = "std_internals", issue = "none")] -pub use self::adapters::ByRefSized; -#[stable(feature = "iter_cloned", since = "1.1.0")] -pub use self::adapters::Cloned; -#[stable(feature = "iter_copied", since = "1.36.0")] -pub use self::adapters::Copied; -#[stable(feature = "iterator_flatten", since = "1.29.0")] -pub use self::adapters::Flatten; -#[stable(feature = "iter_map_while", since = "1.57.0")] -pub use self::adapters::MapWhile; -#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] -pub use self::adapters::MapWindows; -#[unstable(feature = "inplace_iteration", issue = "none")] -pub use self::adapters::SourceIter; -#[stable(feature = "iterator_step_by", since = "1.28.0")] -pub use self::adapters::StepBy; -#[unstable(feature = "trusted_random_access", issue = "none")] -pub use self::adapters::TrustedRandomAccess; -#[unstable(feature = "trusted_random_access", issue = "none")] -pub use self::adapters::TrustedRandomAccessNoCoerce; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::adapters::{ - Chain, Cycle, Enumerate, Filter, FilterMap, FlatMap, Fuse, Inspect, Map, Peekable, Rev, Scan, - Skip, SkipWhile, Take, TakeWhile, Zip, -}; -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] -pub use self::adapters::{Intersperse, IntersperseWith}; - -pub(crate) use self::adapters::try_process; -pub(crate) use self::traits::UncheckedIterator; - mod adapters; mod range; mod sources; diff --git a/core/src/iter/range.rs b/core/src/iter/range.rs index 644a169294396..da4f68a0de4fb 100644 --- a/core/src/iter/range.rs +++ b/core/src/iter/range.rs @@ -1,13 +1,12 @@ +use super::{ + FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, TrustedStep, +}; use crate::ascii::Char as AsciiChar; use crate::mem; use crate::net::{Ipv4Addr, Ipv6Addr}; use crate::num::NonZero; use crate::ops::{self, Try}; -use super::{ - FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, TrustedStep, -}; - // Safety: All invariants are upheld. macro_rules! unsafe_impl_trusted_step { ($($type:ty)*) => {$( diff --git a/core/src/iter/sources.rs b/core/src/iter/sources.rs index 56c1f86079a3a..6a94051b7c7b8 100644 --- a/core/src/iter/sources.rs +++ b/core/src/iter/sources.rs @@ -8,33 +8,25 @@ mod repeat_n; mod repeat_with; mod successors; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::repeat::{repeat, Repeat}; - #[stable(feature = "iter_empty", since = "1.2.0")] pub use self::empty::{empty, Empty}; - -#[stable(feature = "iter_once", since = "1.2.0")] -pub use self::once::{once, Once}; - -#[unstable(feature = "iter_repeat_n", issue = "104434")] -pub use self::repeat_n::{repeat_n, RepeatN}; - -#[stable(feature = "iterator_repeat_with", since = "1.28.0")] -pub use self::repeat_with::{repeat_with, RepeatWith}; - -#[stable(feature = "iter_from_fn", since = "1.34.0")] -pub use self::from_fn::{from_fn, FromFn}; - #[unstable( feature = "iter_from_coroutine", issue = "43122", reason = "coroutines are unstable" )] pub use self::from_coroutine::from_coroutine; - -#[stable(feature = "iter_successors", since = "1.34.0")] -pub use self::successors::{successors, Successors}; - +#[stable(feature = "iter_from_fn", since = "1.34.0")] +pub use self::from_fn::{from_fn, FromFn}; +#[stable(feature = "iter_once", since = "1.2.0")] +pub use self::once::{once, Once}; #[stable(feature = "iter_once_with", since = "1.43.0")] pub use self::once_with::{once_with, OnceWith}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::repeat::{repeat, Repeat}; +#[unstable(feature = "iter_repeat_n", issue = "104434")] +pub use self::repeat_n::{repeat_n, RepeatN}; +#[stable(feature = "iterator_repeat_with", since = "1.28.0")] +pub use self::repeat_with::{repeat_with, RepeatWith}; +#[stable(feature = "iter_successors", since = "1.34.0")] +pub use self::successors::{successors, Successors}; diff --git a/core/src/iter/sources/empty.rs b/core/src/iter/sources/empty.rs index 438e046a4dfdc..3c3acceded889 100644 --- a/core/src/iter/sources/empty.rs +++ b/core/src/iter/sources/empty.rs @@ -1,6 +1,5 @@ -use crate::fmt; use crate::iter::{FusedIterator, TrustedLen}; -use crate::marker; +use crate::{fmt, marker}; /// Creates an iterator that yields nothing. /// diff --git a/core/src/iter/sources/repeat_n.rs b/core/src/iter/sources/repeat_n.rs index 8390dab8e543e..4c4ae39f836ca 100644 --- a/core/src/iter/sources/repeat_n.rs +++ b/core/src/iter/sources/repeat_n.rs @@ -114,19 +114,12 @@ impl Iterator for RepeatN { #[inline] fn next(&mut self) -> Option { - if self.count == 0 { - return None; - } - - self.count -= 1; - Some(if self.count == 0 { - // SAFETY: the check above ensured that the count used to be non-zero, - // so element hasn't been dropped yet, and we just lowered the count to - // zero so it won't be dropped later, and thus it's okay to take it here. - unsafe { ManuallyDrop::take(&mut self.element) } + if self.count > 0 { + // SAFETY: Just checked it's not empty + unsafe { Some(self.next_unchecked()) } } else { - A::clone(&self.element) - }) + None + } } #[inline] @@ -194,4 +187,18 @@ impl FusedIterator for RepeatN {} #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl TrustedLen for RepeatN {} #[unstable(feature = "trusted_len_next_unchecked", issue = "37572")] -impl UncheckedIterator for RepeatN {} +impl UncheckedIterator for RepeatN { + #[inline] + unsafe fn next_unchecked(&mut self) -> Self::Item { + // SAFETY: The caller promised the iterator isn't empty + self.count = unsafe { self.count.unchecked_sub(1) }; + if self.count == 0 { + // SAFETY: the check above ensured that the count used to be non-zero, + // so element hasn't been dropped yet, and we just lowered the count to + // zero so it won't be dropped later, and thus it's okay to take it here. + unsafe { ManuallyDrop::take(&mut self.element) } + } else { + A::clone(&self.element) + } + } +} diff --git a/core/src/iter/sources/successors.rs b/core/src/iter/sources/successors.rs index 7f7b2c7756628..36bc4035039e6 100644 --- a/core/src/iter/sources/successors.rs +++ b/core/src/iter/sources/successors.rs @@ -1,4 +1,5 @@ -use crate::{fmt, iter::FusedIterator}; +use crate::fmt; +use crate::iter::FusedIterator; /// Creates a new iterator where each successive item is computed based on the preceding one. /// diff --git a/core/src/iter/traits/accum.rs b/core/src/iter/traits/accum.rs index f9c7eb8f9383e..c97cd042ab459 100644 --- a/core/src/iter/traits/accum.rs +++ b/core/src/iter/traits/accum.rs @@ -15,8 +15,8 @@ use crate::num::Wrapping; label = "value of type `{Self}` cannot be made by summing a `std::iter::Iterator`" )] pub trait Sum: Sized { - /// Method which takes an iterator and generates `Self` from the elements by - /// "summing up" the items. + /// Takes an iterator and generates `Self` from the elements by "summing up" + /// the items. #[stable(feature = "iter_arith_traits", since = "1.12.0")] fn sum>(iter: I) -> Self; } @@ -36,8 +36,8 @@ pub trait Sum: Sized { label = "value of type `{Self}` cannot be made by multiplying all elements from a `std::iter::Iterator`" )] pub trait Product: Sized { - /// Method which takes an iterator and generates `Self` from the elements by - /// multiplying the items. + /// Takes an iterator and generates `Self` from the elements by multiplying + /// the items. #[stable(feature = "iter_arith_traits", since = "1.12.0")] fn product>(iter: I) -> Self; } diff --git a/core/src/iter/traits/iterator.rs b/core/src/iter/traits/iterator.rs index 733d414d44465..50a2d952e5b36 100644 --- a/core/src/iter/traits/iterator.rs +++ b/core/src/iter/traits/iterator.rs @@ -1,19 +1,14 @@ +use super::super::{ + try_process, ArrayChunks, ByRefSized, Chain, Cloned, Copied, Cycle, Enumerate, Filter, + FilterMap, FlatMap, Flatten, Fuse, Inspect, Intersperse, IntersperseWith, Map, MapWhile, + MapWindows, Peekable, Product, Rev, Scan, Skip, SkipWhile, StepBy, Sum, Take, TakeWhile, + TrustedRandomAccessNoCoerce, Zip, +}; use crate::array; use crate::cmp::{self, Ordering}; use crate::num::NonZero; use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try}; -use super::super::try_process; -use super::super::ByRefSized; -use super::super::TrustedRandomAccessNoCoerce; -use super::super::{ArrayChunks, Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse}; -use super::super::{FlatMap, Flatten}; -use super::super::{ - Inspect, Map, MapWhile, MapWindows, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, - TakeWhile, -}; -use super::super::{Intersperse, IntersperseWith, Product, Sum, Zip}; - fn _assert_is_object_safe(_: &dyn Iterator) {} /// A trait for dealing with iterators. @@ -823,7 +818,7 @@ pub trait Iterator { /// /// Given an element the closure must return `true` or `false`. The returned /// iterator will yield only the elements for which the closure returns - /// true. + /// `true`. /// /// # Examples /// @@ -3951,8 +3946,6 @@ pub trait Iterator { /// # Examples /// /// ``` - /// #![feature(is_sorted)] - /// /// assert!([1, 2, 2, 9].iter().is_sorted()); /// assert!(![1, 3, 2, 4].iter().is_sorted()); /// assert!([0].iter().is_sorted()); @@ -3960,7 +3953,7 @@ pub trait Iterator { /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted()); /// ``` #[inline] - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[rustc_do_not_const_check] fn is_sorted(self) -> bool where @@ -3978,8 +3971,6 @@ pub trait Iterator { /// # Examples /// /// ``` - /// #![feature(is_sorted)] - /// /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a <= b)); /// assert!(![1, 2, 2, 9].iter().is_sorted_by(|a, b| a < b)); /// @@ -3989,7 +3980,7 @@ pub trait Iterator { /// assert!(std::iter::empty::().is_sorted_by(|a, b| false)); /// assert!(std::iter::empty::().is_sorted_by(|a, b| true)); /// ``` - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[rustc_do_not_const_check] fn is_sorted_by(mut self, compare: F) -> bool where @@ -4030,13 +4021,11 @@ pub trait Iterator { /// # Examples /// /// ``` - /// #![feature(is_sorted)] - /// /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len())); /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs())); /// ``` #[inline] - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[rustc_do_not_const_check] fn is_sorted_by_key(self, f: F) -> bool where diff --git a/core/src/iter/traits/mod.rs b/core/src/iter/traits/mod.rs index d4c9cc4b16037..b330e9ffe21ac 100644 --- a/core/src/iter/traits/mod.rs +++ b/core/src/iter/traits/mod.rs @@ -6,6 +6,13 @@ mod iterator; mod marker; mod unchecked_iterator; +#[unstable(issue = "none", feature = "inplace_iteration")] +pub use self::marker::InPlaceIterable; +#[unstable(issue = "none", feature = "trusted_fused")] +pub use self::marker::TrustedFused; +#[unstable(feature = "trusted_step", issue = "85731")] +pub use self::marker::TrustedStep; +pub(crate) use self::unchecked_iterator::UncheckedIterator; #[stable(feature = "rust1", since = "1.0.0")] pub use self::{ accum::{Product, Sum}, @@ -15,12 +22,3 @@ pub use self::{ iterator::Iterator, marker::{FusedIterator, TrustedLen}, }; - -#[unstable(issue = "none", feature = "inplace_iteration")] -pub use self::marker::InPlaceIterable; -#[unstable(issue = "none", feature = "trusted_fused")] -pub use self::marker::TrustedFused; -#[unstable(feature = "trusted_step", issue = "85731")] -pub use self::marker::TrustedStep; - -pub(crate) use self::unchecked_iterator::UncheckedIterator; diff --git a/core/src/lib.rs b/core/src/lib.rs index 49f89e702558f..e74900ff7471b 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -103,9 +103,11 @@ #![deny(ffi_unwind_calls)] // Do not check link redundancy on bootstraping phase #![allow(rustdoc::redundant_explicit_links)] +#![warn(rustdoc::unescaped_backticks)] // // Library features: // tidy-alphabetical-start +#![cfg_attr(bootstrap, feature(offset_of_nested))] #![feature(array_ptr_get)] #![feature(asm_experimental_arch)] #![feature(char_indices_offset)] @@ -127,7 +129,6 @@ #![feature(const_hash)] #![feature(const_heap)] #![feature(const_index_range_slice_index)] -#![feature(const_int_from_str)] #![feature(const_intrinsic_copy)] #![feature(const_intrinsic_forget)] #![feature(const_ipv4)] @@ -163,8 +164,8 @@ #![feature(const_ub_checks)] #![feature(const_unicode_case_lookup)] #![feature(const_unsafecell_get_mut)] -#![feature(const_waker)] #![feature(coverage_attribute)] +#![feature(do_not_recommend)] #![feature(duration_consts_float)] #![feature(internal_impls_macro)] #![feature(ip)] @@ -172,7 +173,6 @@ #![feature(isqrt)] #![feature(link_cfg)] #![feature(offset_of_enum)] -#![feature(offset_of_nested)] #![feature(panic_internals)] #![feature(ptr_alignment_type)] #![feature(ptr_metadata)] @@ -192,8 +192,6 @@ // // Language features: // tidy-alphabetical-start -#![cfg_attr(bootstrap, feature(c_unwind))] -#![cfg_attr(bootstrap, feature(effects))] #![feature(abi_unadjusted)] #![feature(adt_const_params)] #![feature(allow_internal_unsafe)] @@ -262,9 +260,11 @@ #![feature(powerpc_target_feature)] #![feature(riscv_target_feature)] #![feature(rtm_target_feature)] +#![feature(sha512_sm_x86)] #![feature(sse4a_target_feature)] #![feature(tbm_target_feature)] #![feature(wasm_target_feature)] +#![feature(x86_amx_intrinsics)] // tidy-alphabetical-end // allow using `core::` in intra-doc links diff --git a/core/src/macros/mod.rs b/core/src/macros/mod.rs index 0d4ca4d5f01e4..ac51a40d9f478 100644 --- a/core/src/macros/mod.rs +++ b/core/src/macros/mod.rs @@ -14,6 +14,12 @@ macro_rules! panic { /// Asserts that two expressions are equal to each other (using [`PartialEq`]). /// +/// Assertions are always checked in both debug and release builds, and cannot +/// be disabled. See [`debug_assert_eq!`] for assertions that are disabled in +/// release builds by default. +/// +/// [`debug_assert_eq!`]: crate::debug_assert_eq +/// /// On panic, this macro will print the values of the expressions with their /// debug representations. /// @@ -64,6 +70,12 @@ macro_rules! assert_eq { /// Asserts that two expressions are not equal to each other (using [`PartialEq`]). /// +/// Assertions are always checked in both debug and release builds, and cannot +/// be disabled. See [`debug_assert_ne!`] for assertions that are disabled in +/// release builds by default. +/// +/// [`debug_assert_ne!`]: crate::debug_assert_ne +/// /// On panic, this macro will print the values of the expressions with their /// debug representations. /// @@ -122,6 +134,12 @@ macro_rules! assert_ne { /// optional if guard can be used to add additional checks that must be true for the matched value, /// otherwise this macro will panic. /// +/// Assertions are always checked in both debug and release builds, and cannot +/// be disabled. See [`debug_assert_matches!`] for assertions that are disabled in +/// release builds by default. +/// +/// [`debug_assert_matches!`]: crate::assert_matches::debug_assert_matches +/// /// On panic, this macro will print the value of the expression with its debug representation. /// /// Like [`assert!`], this macro has a second form, where a custom panic message can be provided. @@ -633,7 +651,7 @@ macro_rules! write { }; } -/// Write formatted data into a buffer, with a newline appended. +/// Writes formatted data into a buffer, with a newline appended. /// /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone /// (no additional CARRIAGE RETURN (`\r`/`U+000D`). diff --git a/core/src/marker.rs b/core/src/marker.rs index 21abd7c036ba7..6a83ec2eb1e0e 100644 --- a/core/src/marker.rs +++ b/core/src/marker.rs @@ -9,8 +9,7 @@ use crate::cell::UnsafeCell; use crate::cmp; use crate::fmt::Debug; -use crate::hash::Hash; -use crate::hash::Hasher; +use crate::hash::{Hash, Hasher}; /// Implements a given marker trait for multiple types at the same time. /// @@ -42,6 +41,8 @@ use crate::hash::Hasher; /// } /// ``` #[unstable(feature = "internal_impls_macro", issue = "none")] +// Allow implementations of `UnsizedConstParamTy` even though std cannot use that feature. +#[allow_internal_unstable(unsized_const_params)] macro marker_impls { ( $(#[$($meta:tt)*])* $Trait:ident for $({$($bounds:tt)*})? $T:ty $(, $($rest:tt)*)? ) => { $(#[$($meta)*])* impl< $($($bounds)*)? > $Trait for $T {} @@ -869,7 +870,7 @@ marker_impls! { /// /// *However*, you cannot use [`mem::replace`] on `!Unpin` data which is *pinned* by being wrapped /// inside a [`Pin`] pointing at it. This is because you cannot (safely) use a -/// [`Pin`] to get an `&mut T` to its pointee value, which you would need to call +/// [`Pin`] to get a `&mut T` to its pointee value, which you would need to call /// [`mem::replace`], and *that* is what makes this system work. /// /// So this, for example, can only be done on types implementing `Unpin`: @@ -975,31 +976,73 @@ pub trait PointerLike {} /// that all fields are also `ConstParamTy`, which implies that recursively, all fields /// are `StructuralPartialEq`. #[lang = "const_param_ty"] -#[unstable(feature = "adt_const_params", issue = "95174")] +#[unstable(feature = "unsized_const_params", issue = "95174")] #[diagnostic::on_unimplemented(message = "`{Self}` can't be used as a const parameter type")] #[allow(multiple_supertrait_upcastable)] -pub trait ConstParamTy: StructuralPartialEq + Eq {} +// We name this differently than the derive macro so that the `adt_const_params` can +// be used independently of `unsized_const_params` without requiring a full path +// to the derive macro every time it is used. This should be renamed on stabilization. +pub trait ConstParamTy_: UnsizedConstParamTy + StructuralPartialEq + Eq {} /// Derive macro generating an impl of the trait `ConstParamTy`. #[rustc_builtin_macro] +#[allow_internal_unstable(unsized_const_params)] #[unstable(feature = "adt_const_params", issue = "95174")] pub macro ConstParamTy($item:item) { /* compiler built-in */ } +#[cfg_attr(not(bootstrap), lang = "unsized_const_param_ty")] +#[unstable(feature = "unsized_const_params", issue = "95174")] +#[diagnostic::on_unimplemented(message = "`{Self}` can't be used as a const parameter type")] +/// A marker for types which can be used as types of `const` generic parameters. +/// +/// Equivalent to [`ConstParamTy_`] except that this is used by +/// the `unsized_const_params` to allow for fake unstable impls. +pub trait UnsizedConstParamTy: StructuralPartialEq + Eq {} + +/// Derive macro generating an impl of the trait `ConstParamTy`. +#[cfg(not(bootstrap))] +#[cfg_attr(not(bootstrap), rustc_builtin_macro)] +#[cfg_attr(not(bootstrap), allow_internal_unstable(unsized_const_params))] +#[cfg_attr(not(bootstrap), unstable(feature = "unsized_const_params", issue = "95174"))] +pub macro UnsizedConstParamTy($item:item) { + /* compiler built-in */ +} + // FIXME(adt_const_params): handle `ty::FnDef`/`ty::Closure` marker_impls! { #[unstable(feature = "adt_const_params", issue = "95174")] - ConstParamTy for + ConstParamTy_ for + usize, u8, u16, u32, u64, u128, + isize, i8, i16, i32, i64, i128, + bool, + char, + (), + {T: ConstParamTy_, const N: usize} [T; N], +} +#[cfg(bootstrap)] +marker_impls! { + #[unstable(feature = "adt_const_params", issue = "95174")] + ConstParamTy_ for + str, + {T: ConstParamTy_} [T], + {T: ConstParamTy_ + ?Sized} &T, +} + +marker_impls! { + #[unstable(feature = "unsized_const_params", issue = "95174")] + UnsizedConstParamTy for usize, u8, u16, u32, u64, u128, isize, i8, i16, i32, i64, i128, bool, char, - str /* Technically requires `[u8]: ConstParamTy` */, (), - {T: ConstParamTy, const N: usize} [T; N], - {T: ConstParamTy} [T], - {T: ?Sized + ConstParamTy} &T, + {T: UnsizedConstParamTy, const N: usize} [T; N], + + str, + {T: UnsizedConstParamTy} [T], + {T: UnsizedConstParamTy + ?Sized} &T, } /// A common trait implemented by all function pointers. @@ -1017,7 +1060,6 @@ pub trait FnPtr: Copy + Clone { } /// Derive macro generating impls of traits related to smart pointers. -#[cfg(not(bootstrap))] #[rustc_builtin_macro] #[allow_internal_unstable(dispatch_from_dyn, coerce_unsized, unsize)] #[unstable(feature = "derive_smart_pointer", issue = "123430")] @@ -1035,7 +1077,6 @@ pub macro SmartPointer($item:item) { reason = "internal module for implementing effects" )] #[allow(missing_debug_implementations)] // these unit structs don't need `Debug` impls. -#[cfg(not(bootstrap))] pub mod effects { #[lang = "EffectsNoRuntime"] pub struct NoRuntime; diff --git a/core/src/mem/manually_drop.rs b/core/src/mem/manually_drop.rs index 997f088c6d687..00c837041b697 100644 --- a/core/src/mem/manually_drop.rs +++ b/core/src/mem/manually_drop.rs @@ -118,10 +118,12 @@ impl ManuallyDrop { } impl ManuallyDrop { - /// Manually drops the contained value. This is exactly equivalent to calling - /// [`ptr::drop_in_place`] with a pointer to the contained value. As such, unless - /// the contained value is a packed struct, the destructor will be called in-place - /// without moving the value, and thus can be used to safely drop [pinned] data. + /// Manually drops the contained value. + /// + /// This is exactly equivalent to calling [`ptr::drop_in_place`] with a + /// pointer to the contained value. As such, unless the contained value is a + /// packed struct, the destructor will be called in-place without moving the + /// value, and thus can be used to safely drop [pinned] data. /// /// If you have ownership of the value, you can use [`ManuallyDrop::into_inner`] instead. /// diff --git a/core/src/mem/maybe_uninit.rs b/core/src/mem/maybe_uninit.rs index dd40f57dc8707..f920ab1792daf 100644 --- a/core/src/mem/maybe_uninit.rs +++ b/core/src/mem/maybe_uninit.rs @@ -1,9 +1,6 @@ use crate::any::type_name; -use crate::fmt; -use crate::intrinsics; use crate::mem::{self, ManuallyDrop}; -use crate::ptr; -use crate::slice; +use crate::{fmt, intrinsics, ptr, slice}; /// A wrapper type to construct uninitialized instances of `T`. /// @@ -310,7 +307,7 @@ impl MaybeUninit { MaybeUninit { uninit: () } } - /// Create a new array of `MaybeUninit` items, in an uninitialized state. + /// Creates a new array of `MaybeUninit` items, in an uninitialized state. /// /// Note: in a future Rust version this method may become unnecessary /// when Rust allows diff --git a/core/src/mem/mod.rs b/core/src/mem/mod.rs index dd4b6e823434e..ea2dcdce6e89e 100644 --- a/core/src/mem/mod.rs +++ b/core/src/mem/mod.rs @@ -5,13 +5,8 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::clone; -use crate::cmp; -use crate::fmt; -use crate::hash; -use crate::intrinsics; use crate::marker::DiscriminantKind; -use crate::ptr; +use crate::{clone, cmp, fmt, hash, intrinsics, ptr}; mod manually_drop; #[stable(feature = "manually_drop", since = "1.20.0")] @@ -359,6 +354,12 @@ pub const fn size_of_val(val: &T) -> usize { /// - a [slice], then the length of the slice tail must be an initialized /// integer, and the size of the *entire value* /// (dynamic tail length + statically sized prefix) must fit in `isize`. +/// For the special case where the dynamic tail length is 0, this function +/// is safe to call. +// NOTE: the reason this is safe is that if an overflow were to occur already with size 0, +// then we would stop compilation as even the "statically known" part of the type would +// already be too big (or the call may be in dead code and optimized away, but then it +// doesn't matter). /// - a [trait object], then the vtable part of the pointer must point /// to a valid vtable acquired by an unsizing coercion, and the size /// of the *entire value* (dynamic tail length + statically sized prefix) @@ -506,6 +507,8 @@ pub const fn align_of_val(val: &T) -> usize { /// - a [slice], then the length of the slice tail must be an initialized /// integer, and the size of the *entire value* /// (dynamic tail length + statically sized prefix) must fit in `isize`. +/// For the special case where the dynamic tail length is 0, this function +/// is safe to call. /// - a [trait object], then the vtable part of the pointer must point /// to a valid vtable acquired by an unsizing coercion, and the size /// of the *entire value* (dynamic tail length + statically sized prefix) @@ -1318,7 +1321,8 @@ impl SizedTypeProperties for T {} /// # Examples /// /// ``` -/// #![feature(offset_of_enum, offset_of_nested)] +/// # #![cfg_attr(bootstrap, feature(offset_of_nested))] +/// #![feature(offset_of_enum)] /// /// use std::mem; /// #[repr(C)] diff --git a/core/src/mem/transmutability.rs b/core/src/mem/transmutability.rs index 827426b235839..ea73c5b80ba44 100644 --- a/core/src/mem/transmutability.rs +++ b/core/src/mem/transmutability.rs @@ -1,4 +1,4 @@ -use crate::marker::ConstParamTy; +use crate::marker::{ConstParamTy_, UnsizedConstParamTy}; /// Are values of a type transmutable into values of another type? /// @@ -39,7 +39,9 @@ pub struct Assume { } #[unstable(feature = "transmutability", issue = "99571")] -impl ConstParamTy for Assume {} +impl ConstParamTy_ for Assume {} +#[unstable(feature = "transmutability", issue = "99571")] +impl UnsizedConstParamTy for Assume {} impl Assume { /// Do not assume that *you* have ensured any safety properties are met. diff --git a/core/src/net/display_buffer.rs b/core/src/net/display_buffer.rs index 6619c85f483ef..bab84a97308b3 100644 --- a/core/src/net/display_buffer.rs +++ b/core/src/net/display_buffer.rs @@ -1,6 +1,5 @@ -use crate::fmt; use crate::mem::MaybeUninit; -use crate::str; +use crate::{fmt, str}; /// Used for slow path in `Display` implementations when alignment is required. pub struct DisplayBuffer { diff --git a/core/src/net/ip_addr.rs b/core/src/net/ip_addr.rs index c11a508a135b3..3e036b88128c7 100644 --- a/core/src/net/ip_addr.rs +++ b/core/src/net/ip_addr.rs @@ -1,11 +1,10 @@ +use super::display_buffer::DisplayBuffer; use crate::cmp::Ordering; use crate::fmt::{self, Write}; use crate::iter; use crate::mem::transmute; use crate::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not}; -use super::display_buffer::DisplayBuffer; - /// An IP address, either IPv4 or IPv6. /// /// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their @@ -406,8 +405,8 @@ impl IpAddr { matches!(self, IpAddr::V6(_)) } - /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped IPv6 address, otherwise it - /// returns `self` as-is. + /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped IPv6 + /// address, otherwise returns `self` as-is. /// /// # Examples /// @@ -549,7 +548,7 @@ impl Ipv4Addr { #[stable(feature = "ip_constructors", since = "1.30.0")] pub const UNSPECIFIED: Self = Ipv4Addr::new(0, 0, 0, 0); - /// An IPv4 address representing the broadcast address: `255.255.255.255` + /// An IPv4 address representing the broadcast address: `255.255.255.255`. /// /// # Examples /// @@ -686,10 +685,10 @@ impl Ipv4Addr { /// Returns [`true`] if the address appears to be globally reachable /// as specified by the [IANA IPv4 Special-Purpose Address Registry]. - /// Whether or not an address is practically reachable will depend on your network configuration. /// - /// Most IPv4 addresses are globally reachable; - /// unless they are specifically defined as *not* globally reachable. + /// Whether or not an address is practically reachable will depend on your + /// network configuration. Most IPv4 addresses are globally reachable, unless + /// they are specifically defined as *not* globally reachable. /// /// Non-exhaustive list of notable addresses that are not globally reachable: /// @@ -802,8 +801,10 @@ impl Ipv4Addr { } /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for - /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0` - /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`. + /// network devices benchmarking. + /// + /// This range is defined in [IETF RFC 2544] as `192.18.0.0` through + /// `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`. /// /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544 /// [errata 423]: https://www.rfc-editor.org/errata/eid423 @@ -827,10 +828,12 @@ impl Ipv4Addr { self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18 } - /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112] - /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the - /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since - /// it is obviously not reserved for future use. + /// Returns [`true`] if this address is reserved by IANA for future use. + /// + /// [IETF RFC 1112] defines the block of reserved addresses as `240.0.0.0/4`. + /// This range normally includes the broadcast address `255.255.255.255`, but + /// this implementation explicitly excludes it, since it is obviously not + /// reserved for future use. /// /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112 /// @@ -1328,7 +1331,7 @@ impl Ipv6Addr { #[stable(feature = "ip_constructors", since = "1.30.0")] pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); - /// An IPv6 address representing the unspecified address: `::` + /// An IPv6 address representing the unspecified address: `::`. /// /// This corresponds to constant `IN6ADDR_ANY_INIT` or `in6addr_any` in other languages. /// @@ -1424,10 +1427,10 @@ impl Ipv6Addr { /// Returns [`true`] if the address appears to be globally reachable /// as specified by the [IANA IPv6 Special-Purpose Address Registry]. - /// Whether or not an address is practically reachable will depend on your network configuration. /// - /// Most IPv6 addresses are globally reachable; - /// unless they are specifically defined as *not* globally reachable. + /// Whether or not an address is practically reachable will depend on your + /// network configuration. Most IPv6 addresses are globally reachable, unless + /// they are specifically defined as *not* globally reachable. /// /// Non-exhaustive list of notable addresses that are not globally reachable: /// - The [unspecified address] ([`is_unspecified`](Ipv6Addr::is_unspecified)) @@ -1879,8 +1882,8 @@ impl Ipv6Addr { } } - /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped address, otherwise it - /// returns self wrapped in an `IpAddr::V6`. + /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped address, + /// otherwise returns self wrapped in an `IpAddr::V6`. /// /// # Examples /// @@ -1919,7 +1922,7 @@ impl Ipv6Addr { } } -/// Write an Ipv6Addr, conforming to the canonical style described by +/// Writes an Ipv6Addr, conforming to the canonical style described by /// [RFC 5952](https://tools.ietf.org/html/rfc5952). #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for Ipv6Addr { @@ -1962,7 +1965,7 @@ impl fmt::Display for Ipv6Addr { longest }; - /// Write a colon-separated part of the address + /// Writes a colon-separated part of the address. #[inline] fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result { if let Some((first, tail)) = chunk.split_first() { diff --git a/core/src/net/parser.rs b/core/src/net/parser.rs index deea821244859..a8ec71f0dd801 100644 --- a/core/src/net/parser.rs +++ b/core/src/net/parser.rs @@ -68,7 +68,7 @@ impl<'a> Parser<'a> { self.state.first().map(|&b| char::from(b)) } - /// Read the next character from the input + /// Reads the next character from the input fn read_char(&mut self) -> Option { self.state.split_first().map(|(&b, tail)| { self.state = tail; @@ -77,7 +77,7 @@ impl<'a> Parser<'a> { } #[must_use] - /// Read the next character from the input if it matches the target. + /// Reads the next character from the input if it matches the target. fn read_given_char(&mut self, target: char) -> Option<()> { self.read_atomically(|p| { p.read_char().and_then(|c| if c == target { Some(()) } else { None }) @@ -165,7 +165,7 @@ impl<'a> Parser<'a> { } } - /// Read an IPv4 address. + /// Reads an IPv4 address. fn read_ipv4_addr(&mut self) -> Option { self.read_atomically(|p| { let mut groups = [0; 4]; @@ -182,7 +182,7 @@ impl<'a> Parser<'a> { }) } - /// Read an IPv6 Address. + /// Reads an IPv6 address. fn read_ipv6_addr(&mut self) -> Option { /// Read a chunk of an IPv6 address into `groups`. Returns the number /// of groups read, along with a bool indicating if an embedded @@ -249,12 +249,12 @@ impl<'a> Parser<'a> { }) } - /// Read an IP Address, either IPv4 or IPv6. + /// Reads an IP address, either IPv4 or IPv6. fn read_ip_addr(&mut self) -> Option { self.read_ipv4_addr().map(IpAddr::V4).or_else(move || self.read_ipv6_addr().map(IpAddr::V6)) } - /// Read a `:` followed by a port in base 10. + /// Reads a `:` followed by a port in base 10. fn read_port(&mut self) -> Option { self.read_atomically(|p| { p.read_given_char(':')?; @@ -262,7 +262,7 @@ impl<'a> Parser<'a> { }) } - /// Read a `%` followed by a scope ID in base 10. + /// Reads a `%` followed by a scope ID in base 10. fn read_scope_id(&mut self) -> Option { self.read_atomically(|p| { p.read_given_char('%')?; @@ -270,7 +270,7 @@ impl<'a> Parser<'a> { }) } - /// Read an IPv4 address with a port. + /// Reads an IPv4 address with a port. fn read_socket_addr_v4(&mut self) -> Option { self.read_atomically(|p| { let ip = p.read_ipv4_addr()?; @@ -279,7 +279,7 @@ impl<'a> Parser<'a> { }) } - /// Read an IPv6 address with a port. + /// Reads an IPv6 address with a port. fn read_socket_addr_v6(&mut self) -> Option { self.read_atomically(|p| { p.read_given_char('[')?; @@ -292,7 +292,7 @@ impl<'a> Parser<'a> { }) } - /// Read an IP address with a port + /// Reads an IP address with a port. fn read_socket_addr(&mut self) -> Option { self.read_socket_addr_v4() .map(SocketAddr::V4) diff --git a/core/src/net/socket_addr.rs b/core/src/net/socket_addr.rs index c24d8f5519504..4e339172b682f 100644 --- a/core/src/net/socket_addr.rs +++ b/core/src/net/socket_addr.rs @@ -1,8 +1,7 @@ +use super::display_buffer::DisplayBuffer; use crate::fmt::{self, Write}; use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -use super::display_buffer::DisplayBuffer; - /// An internet socket address, either IPv4 or IPv6. /// /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well diff --git a/core/src/num/bignum.rs b/core/src/num/bignum.rs index d2a21b6b38260..2a47c89e2aee2 100644 --- a/core/src/num/bignum.rs +++ b/core/src/num/bignum.rs @@ -145,8 +145,7 @@ macro_rules! define_bignum { /// Adds `other` to itself and returns its own mutable reference. pub fn add<'a>(&'a mut self, other: &$name) -> &'a mut $name { - use crate::cmp; - use crate::iter; + use crate::{cmp, iter}; let mut sz = cmp::max(self.size, other.size); let mut carry = false; @@ -181,8 +180,7 @@ macro_rules! define_bignum { /// Subtracts `other` from itself and returns its own mutable reference. pub fn sub<'a>(&'a mut self, other: &$name) -> &'a mut $name { - use crate::cmp; - use crate::iter; + use crate::{cmp, iter}; let sz = cmp::max(self.size, other.size); let mut noborrow = true; diff --git a/core/src/num/dec2flt/common.rs b/core/src/num/dec2flt/common.rs index c85727b493816..4dadf406ae8c7 100644 --- a/core/src/num/dec2flt/common.rs +++ b/core/src/num/dec2flt/common.rs @@ -2,10 +2,10 @@ /// Helper methods to process immutable bytes. pub(crate) trait ByteSlice { - /// Read 8 bytes as a 64-bit integer in little-endian order. + /// Reads 8 bytes as a 64-bit integer in little-endian order. fn read_u64(&self) -> u64; - /// Write a 64-bit integer as 8 bytes in little-endian order. + /// Writes a 64-bit integer as 8 bytes in little-endian order. fn write_u64(&mut self, value: u64); /// Calculate the offset of a slice from another. diff --git a/core/src/num/dec2flt/float.rs b/core/src/num/dec2flt/float.rs index 1c9d68999d6f8..da57aa9a546af 100644 --- a/core/src/num/dec2flt/float.rs +++ b/core/src/num/dec2flt/float.rs @@ -81,7 +81,7 @@ pub trait RawFloat: // Maximum mantissa for the fast-path (`1 << 53` for f64). const MAX_MANTISSA_FAST_PATH: u64 = 2_u64 << Self::MANTISSA_EXPLICIT_BITS; - /// Convert integer into float through an as cast. + /// Converts integer into float through an as cast. /// This is only called in the fast-path algorithm, and therefore /// will not lose precision, since the value will always have /// only if the value is <= Self::MAX_MANTISSA_FAST_PATH. @@ -90,7 +90,7 @@ pub trait RawFloat: /// Performs a raw transmutation from an integer. fn from_u64_bits(v: u64) -> Self; - /// Get a small power-of-ten for fast-path multiplication. + /// Gets a small power-of-ten for fast-path multiplication. fn pow10_fast_path(exponent: usize) -> Self; /// Returns the category that this number falls into. diff --git a/core/src/num/dec2flt/mod.rs b/core/src/num/dec2flt/mod.rs index 9aac2332dce0d..87bfd0d256634 100644 --- a/core/src/num/dec2flt/mod.rs +++ b/core/src/num/dec2flt/mod.rs @@ -75,15 +75,14 @@ issue = "none" )] -use crate::error::Error; -use crate::fmt; -use crate::str::FromStr; - use self::common::BiasedFp; use self::float::RawFloat; use self::lemire::compute_float; use self::parse::{parse_inf_nan, parse_number}; use self::slow::parse_long_mantissa; +use crate::error::Error; +use crate::fmt; +use crate::str::FromStr; mod common; mod decimal; diff --git a/core/src/num/error.rs b/core/src/num/error.rs index a2d7e6f7b0754..b8e22a8aef955 100644 --- a/core/src/num/error.rs +++ b/core/src/num/error.rs @@ -113,7 +113,7 @@ pub enum IntErrorKind { impl ParseIntError { /// Outputs the detailed cause of parsing an integer failing. #[must_use] - #[rustc_const_unstable(feature = "const_int_from_str", issue = "59133")] + #[rustc_const_stable(feature = "const_int_from_str", since = "CURRENT_RUSTC_VERSION")] #[stable(feature = "int_error_matching", since = "1.55.0")] pub const fn kind(&self) -> &IntErrorKind { &self.kind diff --git a/core/src/num/f128.rs b/core/src/num/f128.rs index 05dc1e97852e0..6a24748fd9e87 100644 --- a/core/src/num/f128.rs +++ b/core/src/num/f128.rs @@ -234,24 +234,20 @@ impl f128 { /// This constant isn't guaranteed to equal to any specific NaN bitpattern, /// and the stability of its representation over Rust versions /// and target platforms isn't guaranteed. - #[cfg(not(bootstrap))] #[allow(clippy::eq_op)] #[rustc_diagnostic_item = "f128_nan"] #[unstable(feature = "f128", issue = "116909")] pub const NAN: f128 = 0.0_f128 / 0.0_f128; /// Infinity (∞). - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] pub const INFINITY: f128 = 1.0_f128 / 0.0_f128; /// Negative infinity (−∞). - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] pub const NEG_INFINITY: f128 = -1.0_f128 / 0.0_f128; /// Sign bit - #[cfg(not(bootstrap))] pub(crate) const SIGN_MASK: u128 = 0x8000_0000_0000_0000_0000_0000_0000_0000; /// Exponent mask @@ -261,11 +257,9 @@ impl f128 { pub(crate) const MAN_MASK: u128 = 0x0000_ffff_ffff_ffff_ffff_ffff_ffff_ffff; /// Minimum representable positive value (min subnormal) - #[cfg(not(bootstrap))] const TINY_BITS: u128 = 0x1; /// Minimum representable negative value (min negative subnormal) - #[cfg(not(bootstrap))] const NEG_TINY_BITS: u128 = Self::TINY_BITS | Self::SIGN_MASK; /// Returns `true` if this value is NaN. @@ -284,7 +278,6 @@ impl f128 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :) pub const fn is_nan(self) -> bool { @@ -295,7 +288,6 @@ impl f128 { // concerns about portability, so this implementation is for // private use internally. #[inline] - #[cfg(not(bootstrap))] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub(crate) const fn abs_private(self) -> f128 { // SAFETY: This transmutation is fine. Probably. For the reasons std is using it. @@ -326,7 +318,6 @@ impl f128 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_infinite(self) -> bool { @@ -354,7 +345,6 @@ impl f128 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_finite(self) -> bool { @@ -389,7 +379,6 @@ impl f128 { /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_subnormal(self) -> bool { @@ -422,7 +411,6 @@ impl f128 { /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_normal(self) -> bool { @@ -448,7 +436,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn classify(self) -> FpCategory { @@ -557,7 +544,6 @@ impl f128 { /// [`MIN`]: Self::MIN /// [`MAX`]: Self::MAX #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] // #[unstable(feature = "float_next_up_down", issue = "91399")] pub fn next_up(self) -> Self { @@ -612,7 +598,6 @@ impl f128 { /// [`MIN`]: Self::MIN /// [`MAX`]: Self::MAX #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] // #[unstable(feature = "float_next_up_down", issue = "91399")] pub fn next_down(self) -> Self { @@ -649,7 +634,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn recip(self) -> Self { @@ -670,7 +654,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn to_degrees(self) -> Self { @@ -694,7 +677,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn to_radians(self) -> f128 { @@ -898,7 +880,7 @@ impl f128 { intrinsics::const_eval_select((v,), ct_u128_to_f128, rt_u128_to_f128) } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// big-endian (network) byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -924,7 +906,7 @@ impl f128 { self.to_bits().to_be_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// little-endian byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -950,7 +932,7 @@ impl f128 { self.to_bits().to_le_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -987,7 +969,7 @@ impl f128 { self.to_bits().to_ne_bytes() } - /// Create a floating point value from its representation as a byte array in big endian. + /// Creates a floating point value from its representation as a byte array in big endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1014,7 +996,7 @@ impl f128 { Self::from_bits(u128::from_be_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in little endian. + /// Creates a floating point value from its representation as a byte array in little endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1041,7 +1023,7 @@ impl f128 { Self::from_bits(u128::from_le_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in native endian. + /// Creates a floating point value from its representation as a byte array in native endian. /// /// As the target platform's native endianness is used, portable code /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as @@ -1078,7 +1060,7 @@ impl f128 { Self::from_bits(u128::from_ne_bytes(bytes)) } - /// Return the ordering between `self` and `other`. + /// Returns the ordering between `self` and `other`. /// /// Unlike the standard partial comparison between floating point numbers, /// this comparison always produces an ordering in accordance to @@ -1141,7 +1123,6 @@ impl f128 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering { let mut left = self.to_bits() as i128; @@ -1201,7 +1182,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] pub fn clamp(mut self, min: f128, max: f128) -> f128 { diff --git a/core/src/num/f16.rs b/core/src/num/f16.rs index 2a8ede9383844..054897b3c96bc 100644 --- a/core/src/num/f16.rs +++ b/core/src/num/f16.rs @@ -229,24 +229,20 @@ impl f16 { /// This constant isn't guaranteed to equal to any specific NaN bitpattern, /// and the stability of its representation over Rust versions /// and target platforms isn't guaranteed. - #[cfg(not(bootstrap))] #[allow(clippy::eq_op)] #[rustc_diagnostic_item = "f16_nan"] #[unstable(feature = "f16", issue = "116909")] pub const NAN: f16 = 0.0_f16 / 0.0_f16; /// Infinity (∞). - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] pub const INFINITY: f16 = 1.0_f16 / 0.0_f16; /// Negative infinity (−∞). - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] pub const NEG_INFINITY: f16 = -1.0_f16 / 0.0_f16; /// Sign bit - #[cfg(not(bootstrap))] pub(crate) const SIGN_MASK: u16 = 0x8000; /// Exponent mask @@ -256,11 +252,9 @@ impl f16 { pub(crate) const MAN_MASK: u16 = 0x03ff; /// Minimum representable positive value (min subnormal) - #[cfg(not(bootstrap))] const TINY_BITS: u16 = 0x1; /// Minimum representable negative value (min negative subnormal) - #[cfg(not(bootstrap))] const NEG_TINY_BITS: u16 = Self::TINY_BITS | Self::SIGN_MASK; /// Returns `true` if this value is NaN. @@ -278,7 +272,6 @@ impl f16 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :) pub const fn is_nan(self) -> bool { @@ -289,7 +282,6 @@ impl f16 { // concerns about portability, so this implementation is for // private use internally. #[inline] - #[cfg(not(bootstrap))] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub(crate) const fn abs_private(self) -> f16 { // SAFETY: This transmutation is fine. Probably. For the reasons std is using it. @@ -317,7 +309,6 @@ impl f16 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_infinite(self) -> bool { @@ -344,7 +335,6 @@ impl f16 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_finite(self) -> bool { @@ -377,7 +367,6 @@ impl f16 { /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_subnormal(self) -> bool { @@ -408,7 +397,6 @@ impl f16 { /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_normal(self) -> bool { @@ -433,7 +421,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn classify(self) -> FpCategory { @@ -478,7 +465,6 @@ impl f16 { /// but getting floats correct is important for not accidentally leaking const eval /// runtime-deviating logic which may or may not be acceptable. #[inline] - #[cfg(not(bootstrap))] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] const unsafe fn partial_classify(self) -> FpCategory { // SAFETY: The caller is not asking questions for which this will tell lies. @@ -593,7 +579,6 @@ impl f16 { /// [`MIN`]: Self::MIN /// [`MAX`]: Self::MAX #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] // #[unstable(feature = "float_next_up_down", issue = "91399")] pub fn next_up(self) -> Self { @@ -648,7 +633,6 @@ impl f16 { /// [`MIN`]: Self::MIN /// [`MAX`]: Self::MAX #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] // #[unstable(feature = "float_next_up_down", issue = "91399")] pub fn next_down(self) -> Self { @@ -685,7 +669,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn recip(self) -> Self { @@ -706,7 +689,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn to_degrees(self) -> Self { @@ -730,7 +712,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn to_radians(self) -> f16 { @@ -933,7 +914,7 @@ impl f16 { intrinsics::const_eval_select((v,), ct_u16_to_f16, rt_u16_to_f16) } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// big-endian (network) byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -958,7 +939,7 @@ impl f16 { self.to_bits().to_be_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// little-endian byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -983,7 +964,7 @@ impl f16 { self.to_bits().to_le_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -1021,7 +1002,7 @@ impl f16 { self.to_bits().to_ne_bytes() } - /// Create a floating point value from its representation as a byte array in big endian. + /// Creates a floating point value from its representation as a byte array in big endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1044,7 +1025,7 @@ impl f16 { Self::from_bits(u16::from_be_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in little endian. + /// Creates a floating point value from its representation as a byte array in little endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1067,7 +1048,7 @@ impl f16 { Self::from_bits(u16::from_le_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in native endian. + /// Creates a floating point value from its representation as a byte array in native endian. /// /// As the target platform's native endianness is used, portable code /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as @@ -1101,7 +1082,7 @@ impl f16 { Self::from_bits(u16::from_ne_bytes(bytes)) } - /// Return the ordering between `self` and `other`. + /// Returns the ordering between `self` and `other`. /// /// Unlike the standard partial comparison between floating point numbers, /// this comparison always produces an ordering in accordance to @@ -1167,7 +1148,6 @@ impl f16 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering { let mut left = self.to_bits() as i16; @@ -1226,7 +1206,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] pub fn clamp(mut self, min: f16, max: f16) -> f16 { diff --git a/core/src/num/f32.rs b/core/src/num/f32.rs index b9c84a66ed138..08d863f17caf7 100644 --- a/core/src/num/f32.rs +++ b/core/src/num/f32.rs @@ -721,11 +721,13 @@ impl f32 { } /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with - /// positive sign bit and positive infinity. Note that IEEE 754 doesn't assign any - /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that - /// the bit pattern of NaNs are conserved over arithmetic operations, the result of - /// `is_sign_positive` on a NaN might produce an unexpected result in some cases. - /// See [explanation of NaN as a special value](f32) for more info. + /// positive sign bit and positive infinity. + /// + /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of + /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are + /// conserved over arithmetic operations, the result of `is_sign_positive` on + /// a NaN might produce an unexpected result in some cases. See [explanation + /// of NaN as a special value](f32) for more info. /// /// ``` /// let f = 7.0_f32; @@ -743,11 +745,13 @@ impl f32 { } /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with - /// negative sign bit and negative infinity. Note that IEEE 754 doesn't assign any - /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that - /// the bit pattern of NaNs are conserved over arithmetic operations, the result of - /// `is_sign_negative` on a NaN might produce an unexpected result in some cases. - /// See [explanation of NaN as a special value](f32) for more info. + /// negative sign bit and negative infinity. + /// + /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of + /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are + /// conserved over arithmetic operations, the result of `is_sign_negative` on + /// a NaN might produce an unexpected result in some cases. See [explanation + /// of NaN as a special value](f32) for more info. /// /// ``` /// let f = 7.0f32; @@ -1274,7 +1278,7 @@ impl f32 { intrinsics::const_eval_select((v,), ct_u32_to_f32, rt_u32_to_f32) } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// big-endian (network) byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -1295,7 +1299,7 @@ impl f32 { self.to_bits().to_be_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// little-endian byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -1316,7 +1320,7 @@ impl f32 { self.to_bits().to_le_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -1350,7 +1354,7 @@ impl f32 { self.to_bits().to_ne_bytes() } - /// Create a floating point value from its representation as a byte array in big endian. + /// Creates a floating point value from its representation as a byte array in big endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1369,7 +1373,7 @@ impl f32 { Self::from_bits(u32::from_be_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in little endian. + /// Creates a floating point value from its representation as a byte array in little endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1388,7 +1392,7 @@ impl f32 { Self::from_bits(u32::from_le_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in native endian. + /// Creates a floating point value from its representation as a byte array in native endian. /// /// As the target platform's native endianness is used, portable code /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as @@ -1418,7 +1422,7 @@ impl f32 { Self::from_bits(u32::from_ne_bytes(bytes)) } - /// Return the ordering between `self` and `other`. + /// Returns the ordering between `self` and `other`. /// /// Unlike the standard partial comparison between floating point numbers, /// this comparison always produces an ordering in accordance to diff --git a/core/src/num/f64.rs b/core/src/num/f64.rs index f8e4555fc44f2..5d33eea6d011f 100644 --- a/core/src/num/f64.rs +++ b/core/src/num/f64.rs @@ -711,11 +711,13 @@ impl f64 { } /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with - /// positive sign bit and positive infinity. Note that IEEE 754 doesn't assign any - /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that - /// the bit pattern of NaNs are conserved over arithmetic operations, the result of - /// `is_sign_positive` on a NaN might produce an unexpected result in some cases. - /// See [explanation of NaN as a special value](f32) for more info. + /// positive sign bit and positive infinity. + /// + /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of + /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are + /// conserved over arithmetic operations, the result of `is_sign_positive` on + /// a NaN might produce an unexpected result in some cases. See [explanation + /// of NaN as a special value](f32) for more info. /// /// ``` /// let f = 7.0_f64; @@ -742,11 +744,13 @@ impl f64 { } /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with - /// negative sign bit and negative infinity. Note that IEEE 754 doesn't assign any - /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that - /// the bit pattern of NaNs are conserved over arithmetic operations, the result of - /// `is_sign_negative` on a NaN might produce an unexpected result in some cases. - /// See [explanation of NaN as a special value](f32) for more info. + /// negative sign bit and negative infinity. + /// + /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of + /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are + /// conserved over arithmetic operations, the result of `is_sign_negative` on + /// a NaN might produce an unexpected result in some cases. See [explanation + /// of NaN as a special value](f32) for more info. /// /// ``` /// let f = 7.0_f64; @@ -1252,7 +1256,7 @@ impl f64 { intrinsics::const_eval_select((v,), ct_u64_to_f64, rt_u64_to_f64) } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// big-endian (network) byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -1273,7 +1277,7 @@ impl f64 { self.to_bits().to_be_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// little-endian byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -1294,7 +1298,7 @@ impl f64 { self.to_bits().to_le_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -1328,7 +1332,7 @@ impl f64 { self.to_bits().to_ne_bytes() } - /// Create a floating point value from its representation as a byte array in big endian. + /// Creates a floating point value from its representation as a byte array in big endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1347,7 +1351,7 @@ impl f64 { Self::from_bits(u64::from_be_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in little endian. + /// Creates a floating point value from its representation as a byte array in little endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1366,7 +1370,7 @@ impl f64 { Self::from_bits(u64::from_le_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in native endian. + /// Creates a floating point value from its representation as a byte array in native endian. /// /// As the target platform's native endianness is used, portable code /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as @@ -1396,7 +1400,7 @@ impl f64 { Self::from_bits(u64::from_ne_bytes(bytes)) } - /// Return the ordering between `self` and `other`. + /// Returns the ordering between `self` and `other`. /// /// Unlike the standard partial comparison between floating point numbers, /// this comparison always produces an ordering in accordance to diff --git a/core/src/num/flt2dec/mod.rs b/core/src/num/flt2dec/mod.rs index 1ff2e8c8228c9..7d923a2652f28 100644 --- a/core/src/num/flt2dec/mod.rs +++ b/core/src/num/flt2dec/mod.rs @@ -123,7 +123,6 @@ functions. )] pub use self::decoder::{decode, DecodableFloat, Decoded, FullDecoded}; - use super::fmt::{Formatted, Part}; use crate::mem::MaybeUninit; diff --git a/core/src/num/flt2dec/strategy/dragon.rs b/core/src/num/flt2dec/strategy/dragon.rs index 71b14d0ae3f4c..f8db6370653ab 100644 --- a/core/src/num/flt2dec/strategy/dragon.rs +++ b/core/src/num/flt2dec/strategy/dragon.rs @@ -6,56 +6,57 @@ use crate::cmp::Ordering; use crate::mem::MaybeUninit; - -use crate::num::bignum::Big32x40 as Big; -use crate::num::bignum::Digit32 as Digit; +use crate::num::bignum::{Big32x40 as Big, Digit32 as Digit}; use crate::num::flt2dec::estimator::estimate_scaling_factor; use crate::num::flt2dec::{round_up, Decoded, MAX_SIG_DIGITS}; static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; -static TWOPOW10: [Digit; 10] = - [2, 20, 200, 2000, 20000, 200000, 2000000, 20000000, 200000000, 2000000000]; - -// precalculated arrays of `Digit`s for 10^(2^n) -static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2]; -static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee]; -static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; -static POW10TO128: [Digit; 14] = [ - 0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, - 0xa6337f19, 0xe91f2603, 0x24e, +// precalculated arrays of `Digit`s for 5^(2^n). +static POW5TO16: [Digit; 2] = [0x86f26fc1, 0x23]; +static POW5TO32: [Digit; 3] = [0x85acef81, 0x2d6d415b, 0x4ee]; +static POW5TO64: [Digit; 5] = [0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; +static POW5TO128: [Digit; 10] = [ + 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19, + 0xe91f2603, 0x24e, ]; -static POW10TO256: [Digit; 27] = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, - 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, - 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7, +static POW5TO256: [Digit; 19] = [ + 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, 0xd595d80f, 0x26b2716e, + 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, + 0xf46eeddc, 0x5fdcefce, 0x553f7, ]; #[doc(hidden)] pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big { debug_assert!(n < 512); + // Save ourself the left shift for the smallest cases. + if n < 8 { + return x.mul_small(POW10[n & 7]); + } + // Multiply by the powers of 5 and shift the 2s in at the end. + // This keeps the intermediate products smaller and faster. if n & 7 != 0 { - x.mul_small(POW10[n & 7]); + x.mul_small(POW10[n & 7] >> (n & 7)); } if n & 8 != 0 { - x.mul_small(POW10[8]); + x.mul_small(POW10[8] >> 8); } if n & 16 != 0 { - x.mul_digits(&POW10TO16); + x.mul_digits(&POW5TO16); } if n & 32 != 0 { - x.mul_digits(&POW10TO32); + x.mul_digits(&POW5TO32); } if n & 64 != 0 { - x.mul_digits(&POW10TO64); + x.mul_digits(&POW5TO64); } if n & 128 != 0 { - x.mul_digits(&POW10TO128); + x.mul_digits(&POW5TO128); } if n & 256 != 0 { - x.mul_digits(&POW10TO256); + x.mul_digits(&POW5TO256); } - x + x.mul_pow2(n) } fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big { @@ -64,7 +65,7 @@ fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big { x.div_rem_small(POW10[largest]); n -= largest; } - x.div_rem_small(TWOPOW10[n]); + x.div_rem_small(POW10[n] << 1); x } diff --git a/core/src/num/int_macros.rs b/core/src/num/int_macros.rs index d40e02352a1d0..dd88e859b30e7 100644 --- a/core/src/num/int_macros.rs +++ b/core/src/num/int_macros.rs @@ -1223,6 +1223,7 @@ macro_rules! int_impl { /// ``` #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")] #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);")] + #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(", stringify!($BITS_MINUS_ONE), "), Some(0));")] /// ``` #[stable(feature = "wrapping", since = "1.7.0")] #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] @@ -2196,10 +2197,11 @@ macro_rules! int_impl { acc.wrapping_mul(base) } - /// Calculates `self` + `rhs` + /// Calculates `self` + `rhs`. /// - /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would - /// occur. If an overflow would have occurred then the wrapped value is returned. + /// Returns a tuple of the addition along with a boolean indicating + /// whether an arithmetic overflow would occur. If an overflow would have + /// occurred then the wrapped value is returned. /// /// # Examples /// @@ -2277,7 +2279,7 @@ macro_rules! int_impl { (c, b != d) } - /// Calculates `self` + `rhs` with an unsigned `rhs` + /// Calculates `self` + `rhs` with an unsigned `rhs`. /// /// Returns a tuple of the addition along with a boolean indicating /// whether an arithmetic overflow would occur. If an overflow would @@ -2600,6 +2602,7 @@ macro_rules! int_impl { /// ``` #[doc = concat!("assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));")] /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true)); + #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shl(", stringify!($BITS_MINUS_ONE), "), (0, false));")] /// ``` #[stable(feature = "wrapping", since = "1.7.0")] #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")] @@ -3389,7 +3392,7 @@ macro_rules! int_impl { #[inline(always)] pub const fn is_negative(self) -> bool { self < 0 } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// big-endian (network) byte order. /// #[doc = $to_xe_bytes_doc] @@ -3409,7 +3412,7 @@ macro_rules! int_impl { self.to_be().to_ne_bytes() } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// little-endian byte order. /// #[doc = $to_xe_bytes_doc] @@ -3429,7 +3432,7 @@ macro_rules! int_impl { self.to_le().to_ne_bytes() } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -3467,7 +3470,7 @@ macro_rules! int_impl { unsafe { mem::transmute(self) } } - /// Create an integer value from its representation as a byte array in + /// Creates an integer value from its representation as a byte array in /// big endian. /// #[doc = $from_xe_bytes_doc] @@ -3496,7 +3499,7 @@ macro_rules! int_impl { Self::from_be(Self::from_ne_bytes(bytes)) } - /// Create an integer value from its representation as a byte array in + /// Creates an integer value from its representation as a byte array in /// little endian. /// #[doc = $from_xe_bytes_doc] @@ -3525,7 +3528,7 @@ macro_rules! int_impl { Self::from_le(Self::from_ne_bytes(bytes)) } - /// Create an integer value from its memory representation as a byte + /// Creates an integer value from its memory representation as a byte /// array in native endianness. /// /// As the target platform's native endianness is used, portable code diff --git a/core/src/num/mod.rs b/core/src/num/mod.rs index 034af6a0d5731..309e1ba958aee 100644 --- a/core/src/num/mod.rs +++ b/core/src/num/mod.rs @@ -2,12 +2,9 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::ascii; -use crate::hint; -use crate::intrinsics; -use crate::mem; use crate::str::FromStr; use crate::ub_checks::assert_unsafe_precondition; +use crate::{ascii, intrinsics, mem}; // Used because the `?` operator is not allowed in a const context. macro_rules! try_opt { @@ -49,39 +46,31 @@ mod overflow_panic; mod saturating; mod wrapping; -#[stable(feature = "saturating_int_impl", since = "1.74.0")] -pub use saturating::Saturating; -#[stable(feature = "rust1", since = "1.0.0")] -pub use wrapping::Wrapping; - #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(no_fp_fmt_parse))] pub use dec2flt::ParseFloatError; - +#[stable(feature = "int_error_matching", since = "1.55.0")] +pub use error::IntErrorKind; #[stable(feature = "rust1", since = "1.0.0")] pub use error::ParseIntError; - +#[stable(feature = "try_from", since = "1.34.0")] +pub use error::TryFromIntError; +#[stable(feature = "generic_nonzero", since = "1.79.0")] +pub use nonzero::NonZero; #[unstable( feature = "nonzero_internals", reason = "implementation detail which may disappear or be replaced at any time", issue = "none" )] pub use nonzero::ZeroablePrimitive; - -#[stable(feature = "generic_nonzero", since = "1.79.0")] -pub use nonzero::NonZero; - #[stable(feature = "signed_nonzero", since = "1.34.0")] pub use nonzero::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize}; - #[stable(feature = "nonzero", since = "1.28.0")] pub use nonzero::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize}; - -#[stable(feature = "try_from", since = "1.34.0")] -pub use error::TryFromIntError; - -#[stable(feature = "int_error_matching", since = "1.55.0")] -pub use error::IntErrorKind; +#[stable(feature = "saturating_int_impl", since = "1.74.0")] +pub use saturating::Saturating; +#[stable(feature = "rust1", since = "1.0.0")] +pub use wrapping::Wrapping; macro_rules! usize_isize_to_xe_bytes_doc { () => { @@ -484,6 +473,7 @@ impl u8 { ActualT = u8, SignedT = i8, BITS = 8, + BITS_MINUS_ONE = 7, MAX = 255, rot = 2, rot_op = "0x82", @@ -1098,6 +1088,7 @@ impl u16 { ActualT = u16, SignedT = i16, BITS = 16, + BITS_MINUS_ONE = 15, MAX = 65535, rot = 4, rot_op = "0xa003", @@ -1146,6 +1137,7 @@ impl u32 { ActualT = u32, SignedT = i32, BITS = 32, + BITS_MINUS_ONE = 31, MAX = 4294967295, rot = 8, rot_op = "0x10000b3", @@ -1169,6 +1161,7 @@ impl u64 { ActualT = u64, SignedT = i64, BITS = 64, + BITS_MINUS_ONE = 63, MAX = 18446744073709551615, rot = 12, rot_op = "0xaa00000000006e1", @@ -1192,6 +1185,7 @@ impl u128 { ActualT = u128, SignedT = i128, BITS = 128, + BITS_MINUS_ONE = 127, MAX = 340282366920938463463374607431768211455, rot = 16, rot_op = "0x13f40000000000000000000000004f76", @@ -1217,6 +1211,7 @@ impl usize { ActualT = u16, SignedT = isize, BITS = 16, + BITS_MINUS_ONE = 15, MAX = 65535, rot = 4, rot_op = "0xa003", @@ -1241,6 +1236,7 @@ impl usize { ActualT = u32, SignedT = isize, BITS = 32, + BITS_MINUS_ONE = 31, MAX = 4294967295, rot = 8, rot_op = "0x10000b3", @@ -1265,6 +1261,7 @@ impl usize { ActualT = u64, SignedT = isize, BITS = 64, + BITS_MINUS_ONE = 63, MAX = 18446744073709551615, rot = 12, rot_op = "0xaa00000000006e1", @@ -1387,6 +1384,7 @@ from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 } #[doc(hidden)] #[inline(always)] #[unstable(issue = "none", feature = "std_internals")] +#[rustc_const_stable(feature = "const_int_from_str", since = "CURRENT_RUSTC_VERSION")] pub const fn can_not_overflow(radix: u32, is_signed_ty: bool, digits: &[u8]) -> bool { radix <= 16 && digits.len() <= mem::size_of::() * 2 - is_signed_ty as usize } @@ -1436,7 +1434,7 @@ macro_rules! from_str_radix { #[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_str_radix(\"A\", 16), Ok(10));")] /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_int_from_str", issue = "59133")] + #[rustc_const_stable(feature = "const_int_from_str", since = "CURRENT_RUSTC_VERSION")] pub const fn from_str_radix(src: &str, radix: u32) -> Result<$int_ty, ParseIntError> { use self::IntErrorKind::*; use self::ParseIntError as PIE; @@ -1566,7 +1564,7 @@ macro_rules! from_str_radix_size_impl { #[doc = concat!("assert_eq!(", stringify!($size), "::from_str_radix(\"A\", 16), Ok(10));")] /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_int_from_str", issue = "59133")] + #[rustc_const_stable(feature = "const_int_from_str", since = "CURRENT_RUSTC_VERSION")] pub const fn from_str_radix(src: &str, radix: u32) -> Result<$size, ParseIntError> { match <$t>::from_str_radix(src, radix) { Ok(x) => Ok(x as $size), diff --git a/core/src/num/nonzero.rs b/core/src/num/nonzero.rs index 0c6f06dc017e7..c6e9c249048a7 100644 --- a/core/src/num/nonzero.rs +++ b/core/src/num/nonzero.rs @@ -1,17 +1,13 @@ //! Definitions of integer that is known not to equal zero. +use super::{IntErrorKind, ParseIntError}; use crate::cmp::Ordering; -use crate::fmt; use crate::hash::{Hash, Hasher}; -use crate::intrinsics; use crate::marker::{Freeze, StructuralPartialEq}; use crate::ops::{BitOr, BitOrAssign, Div, DivAssign, Neg, Rem, RemAssign}; use crate::panic::{RefUnwindSafe, UnwindSafe}; -use crate::ptr; use crate::str::FromStr; -use crate::ub_checks; - -use super::{IntErrorKind, ParseIntError}; +use crate::{fmt, hint, intrinsics, ptr, ub_checks}; /// A marker trait for primitive types which can be zero. /// @@ -454,6 +450,12 @@ macro_rules! nonzero_integer { UnsignedPrimitive = $Uint:ty, // Used in doc comments. + rot = $rot:literal, + rot_op = $rot_op:literal, + rot_result = $rot_result:literal, + swap_op = $swap_op:literal, + swapped = $swapped:literal, + reversed = $reversed:literal, leading_zeros_test = $leading_zeros_test:expr, ) => { /// An integer that is known not to equal zero. @@ -603,8 +605,271 @@ macro_rules! nonzero_integer { unsafe { NonZero::new_unchecked(self.get().count_ones()) } } + /// Shifts the bits to the left by a specified amount, `n`, + /// wrapping the truncated bits to the end of the resulting integer. + /// + /// Please note this isn't the same operation as the `<<` shifting operator! + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(", $rot_op, stringify!($Int), ")?;")] + #[doc = concat!("let m = NonZero::new(", $rot_result, ")?;")] + /// + #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")] + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn rotate_left(self, n: u32) -> Self { + let result = self.get().rotate_left(n); + // SAFETY: Rotating bits preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Shifts the bits to the right by a specified amount, `n`, + /// wrapping the truncated bits to the beginning of the resulting + /// integer. + /// + /// Please note this isn't the same operation as the `>>` shifting operator! + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(", $rot_result, stringify!($Int), ")?;")] + #[doc = concat!("let m = NonZero::new(", $rot_op, ")?;")] + /// + #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")] + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn rotate_right(self, n: u32) -> Self { + let result = self.get().rotate_right(n); + // SAFETY: Rotating bits preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Reverses the byte order of the integer. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(", $swap_op, stringify!($Int), ")?;")] + /// let m = n.swap_bytes(); + /// + #[doc = concat!("assert_eq!(m, NonZero::new(", $swapped, ")?);")] + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn swap_bytes(self) -> Self { + let result = self.get().swap_bytes(); + // SAFETY: Shuffling bytes preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit, + /// second least-significant bit becomes second most-significant bit, etc. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(", $swap_op, stringify!($Int), ")?;")] + /// let m = n.reverse_bits(); + /// + #[doc = concat!("assert_eq!(m, NonZero::new(", $reversed, ")?);")] + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn reverse_bits(self) -> Self { + let result = self.get().reverse_bits(); + // SAFETY: Reversing bits preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Converts an integer from big endian to the target's endianness. + /// + /// On big endian this is a no-op. On little endian the bytes are + /// swapped. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + #[doc = concat!("use std::num::", stringify!($Ty), ";")] + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")] + /// + /// if cfg!(target_endian = "big") { + #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_be(n), n)")] + /// } else { + #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_be(n), n.swap_bytes())")] + /// } + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use] + #[inline(always)] + pub const fn from_be(x: Self) -> Self { + let result = $Int::from_be(x.get()); + // SAFETY: Shuffling bytes preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Converts an integer from little endian to the target's endianness. + /// + /// On little endian this is a no-op. On big endian the bytes are + /// swapped. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + #[doc = concat!("use std::num::", stringify!($Ty), ";")] + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")] + /// + /// if cfg!(target_endian = "little") { + #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_le(n), n)")] + /// } else { + #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_le(n), n.swap_bytes())")] + /// } + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use] + #[inline(always)] + pub const fn from_le(x: Self) -> Self { + let result = $Int::from_le(x.get()); + // SAFETY: Shuffling bytes preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Converts `self` to big endian from the target's endianness. + /// + /// On big endian this is a no-op. On little endian the bytes are + /// swapped. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")] + /// + /// if cfg!(target_endian = "big") { + /// assert_eq!(n.to_be(), n) + /// } else { + /// assert_eq!(n.to_be(), n.swap_bytes()) + /// } + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn to_be(self) -> Self { + let result = self.get().to_be(); + // SAFETY: Shuffling bytes preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Converts `self` to little endian from the target's endianness. + /// + /// On little endian this is a no-op. On big endian the bytes are + /// swapped. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")] + /// + /// if cfg!(target_endian = "little") { + /// assert_eq!(n.to_le(), n) + /// } else { + /// assert_eq!(n.to_le(), n.swap_bytes()) + /// } + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn to_le(self) -> Self { + let result = self.get().to_le(); + // SAFETY: Shuffling bytes preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + nonzero_integer_signedness_dependent_methods! { - Self = $Ty, Primitive = $signedness $Int, UnsignedPrimitive = $Uint, } @@ -823,25 +1088,57 @@ macro_rules! nonzero_integer { } } - nonzero_integer_signedness_dependent_impls!($Ty $signedness $Int); + nonzero_integer_signedness_dependent_impls!($signedness $Int); }; - (Self = $Ty:ident, Primitive = unsigned $Int:ident $(,)?) => { + ( + Self = $Ty:ident, + Primitive = unsigned $Int:ident, + rot = $rot:literal, + rot_op = $rot_op:literal, + rot_result = $rot_result:literal, + swap_op = $swap_op:literal, + swapped = $swapped:literal, + reversed = $reversed:literal, + $(,)? + ) => { nonzero_integer! { #[stable(feature = "nonzero", since = "1.28.0")] Self = $Ty, Primitive = unsigned $Int, UnsignedPrimitive = $Int, + rot = $rot, + rot_op = $rot_op, + rot_result = $rot_result, + swap_op = $swap_op, + swapped = $swapped, + reversed = $reversed, leading_zeros_test = concat!(stringify!($Int), "::MAX"), } }; - (Self = $Ty:ident, Primitive = signed $Int:ident, $($rest:tt)*) => { + ( + Self = $Ty:ident, + Primitive = signed $Int:ident, + UnsignedPrimitive = $UInt:ident, + rot = $rot:literal, + rot_op = $rot_op:literal, + rot_result = $rot_result:literal, + swap_op = $swap_op:literal, + swapped = $swapped:literal, + reversed = $reversed:literal, + ) => { nonzero_integer! { #[stable(feature = "signed_nonzero", since = "1.34.0")] Self = $Ty, Primitive = signed $Int, - $($rest)* + UnsignedPrimitive = $UInt, + rot = $rot, + rot_op = $rot_op, + rot_result = $rot_result, + swap_op = $swap_op, + swapped = $swapped, + reversed = $reversed, leading_zeros_test = concat!("-1", stringify!($Int)), } }; @@ -849,7 +1146,7 @@ macro_rules! nonzero_integer { macro_rules! nonzero_integer_signedness_dependent_impls { // Impls for unsigned nonzero types only. - ($Ty:ident unsigned $Int:ty) => { + (unsigned $Int:ty) => { #[stable(feature = "nonzero_div", since = "1.51.0")] impl Div> for $Int { type Output = $Int; @@ -897,7 +1194,7 @@ macro_rules! nonzero_integer_signedness_dependent_impls { } }; // Impls for signed nonzero types only. - ($Ty:ident signed $Int:ty) => { + (signed $Int:ty) => { #[stable(feature = "signed_nonzero_neg", since = "1.71.0")] impl Neg for NonZero<$Int> { type Output = Self; @@ -918,7 +1215,6 @@ macro_rules! nonzero_integer_signedness_dependent_impls { macro_rules! nonzero_integer_signedness_dependent_methods { // Associated items for unsigned nonzero types only. ( - Self = $Ty:ident, Primitive = unsigned $Int:ident, UnsignedPrimitive = $Uint:ty, ) => { @@ -1224,11 +1520,61 @@ macro_rules! nonzero_integer_signedness_dependent_methods { intrinsics::ctpop(self.get()) < 2 } + + /// Returns the square root of the number, rounded down. + /// + /// # Examples + /// + /// Basic usage: + /// ``` + /// #![feature(isqrt)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let ten = NonZero::new(10", stringify!($Int), ")?;")] + #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")] + /// + /// assert_eq!(ten.isqrt(), three); + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "isqrt", issue = "116226")] + #[rustc_const_unstable(feature = "isqrt", issue = "116226")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub const fn isqrt(self) -> Self { + // The algorithm is based on the one presented in + // + // which cites as source the following C code: + // . + + let mut op = self.get(); + let mut res = 0; + let mut one = 1 << (self.ilog2() & !1); + + while one != 0 { + if op >= res + one { + op -= res + one; + res = (res >> 1) + one; + } else { + res >>= 1; + } + one >>= 2; + } + + // SAFETY: The result fits in an integer with half as many bits. + // Inform the optimizer about it. + unsafe { hint::assert_unchecked(res < 1 << (Self::BITS / 2)) }; + + // SAFETY: The square root of an integer >= 1 is always >= 1. + unsafe { Self::new_unchecked(res) } + } }; // Associated items for signed nonzero types only. ( - Self = $Ty:ident, Primitive = signed $Int:ident, UnsignedPrimitive = $Uint:ty, ) => { @@ -1656,65 +2002,189 @@ macro_rules! sign_dependent_expr { nonzero_integer! { Self = NonZeroU8, Primitive = unsigned u8, + rot = 2, + rot_op = "0x82", + rot_result = "0xa", + swap_op = "0x12", + swapped = "0x12", + reversed = "0x48", } nonzero_integer! { Self = NonZeroU16, Primitive = unsigned u16, + rot = 4, + rot_op = "0xa003", + rot_result = "0x3a", + swap_op = "0x1234", + swapped = "0x3412", + reversed = "0x2c48", } nonzero_integer! { Self = NonZeroU32, Primitive = unsigned u32, + rot = 8, + rot_op = "0x10000b3", + rot_result = "0xb301", + swap_op = "0x12345678", + swapped = "0x78563412", + reversed = "0x1e6a2c48", } nonzero_integer! { Self = NonZeroU64, Primitive = unsigned u64, + rot = 12, + rot_op = "0xaa00000000006e1", + rot_result = "0x6e10aa", + swap_op = "0x1234567890123456", + swapped = "0x5634129078563412", + reversed = "0x6a2c48091e6a2c48", } nonzero_integer! { Self = NonZeroU128, Primitive = unsigned u128, + rot = 16, + rot_op = "0x13f40000000000000000000000004f76", + rot_result = "0x4f7613f4", + swap_op = "0x12345678901234567890123456789012", + swapped = "0x12907856341290785634129078563412", + reversed = "0x48091e6a2c48091e6a2c48091e6a2c48", +} + +#[cfg(target_pointer_width = "16")] +nonzero_integer! { + Self = NonZeroUsize, + Primitive = unsigned usize, + rot = 4, + rot_op = "0xa003", + rot_result = "0x3a", + swap_op = "0x1234", + swapped = "0x3412", + reversed = "0x2c48", +} + +#[cfg(target_pointer_width = "32")] +nonzero_integer! { + Self = NonZeroUsize, + Primitive = unsigned usize, + rot = 8, + rot_op = "0x10000b3", + rot_result = "0xb301", + swap_op = "0x12345678", + swapped = "0x78563412", + reversed = "0x1e6a2c48", } +#[cfg(target_pointer_width = "64")] nonzero_integer! { Self = NonZeroUsize, Primitive = unsigned usize, + rot = 12, + rot_op = "0xaa00000000006e1", + rot_result = "0x6e10aa", + swap_op = "0x1234567890123456", + swapped = "0x5634129078563412", + reversed = "0x6a2c48091e6a2c48", } nonzero_integer! { Self = NonZeroI8, Primitive = signed i8, UnsignedPrimitive = u8, + rot = 2, + rot_op = "-0x7e", + rot_result = "0xa", + swap_op = "0x12", + swapped = "0x12", + reversed = "0x48", } nonzero_integer! { Self = NonZeroI16, Primitive = signed i16, UnsignedPrimitive = u16, + rot = 4, + rot_op = "-0x5ffd", + rot_result = "0x3a", + swap_op = "0x1234", + swapped = "0x3412", + reversed = "0x2c48", } nonzero_integer! { Self = NonZeroI32, Primitive = signed i32, UnsignedPrimitive = u32, + rot = 8, + rot_op = "0x10000b3", + rot_result = "0xb301", + swap_op = "0x12345678", + swapped = "0x78563412", + reversed = "0x1e6a2c48", } nonzero_integer! { Self = NonZeroI64, Primitive = signed i64, UnsignedPrimitive = u64, + rot = 12, + rot_op = "0xaa00000000006e1", + rot_result = "0x6e10aa", + swap_op = "0x1234567890123456", + swapped = "0x5634129078563412", + reversed = "0x6a2c48091e6a2c48", } nonzero_integer! { Self = NonZeroI128, Primitive = signed i128, UnsignedPrimitive = u128, + rot = 16, + rot_op = "0x13f40000000000000000000000004f76", + rot_result = "0x4f7613f4", + swap_op = "0x12345678901234567890123456789012", + swapped = "0x12907856341290785634129078563412", + reversed = "0x48091e6a2c48091e6a2c48091e6a2c48", +} + +#[cfg(target_pointer_width = "16")] +nonzero_integer! { + Self = NonZeroIsize, + Primitive = signed isize, + UnsignedPrimitive = usize, + rot = 4, + rot_op = "-0x5ffd", + rot_result = "0x3a", + swap_op = "0x1234", + swapped = "0x3412", + reversed = "0x2c48", +} + +#[cfg(target_pointer_width = "32")] +nonzero_integer! { + Self = NonZeroIsize, + Primitive = signed isize, + UnsignedPrimitive = usize, + rot = 8, + rot_op = "0x10000b3", + rot_result = "0xb301", + swap_op = "0x12345678", + swapped = "0x78563412", + reversed = "0x1e6a2c48", } +#[cfg(target_pointer_width = "64")] nonzero_integer! { Self = NonZeroIsize, Primitive = signed isize, UnsignedPrimitive = usize, + rot = 12, + rot_op = "0xaa00000000006e1", + rot_result = "0x6e10aa", + swap_op = "0x1234567890123456", + swapped = "0x5634129078563412", + reversed = "0x6a2c48091e6a2c48", } diff --git a/core/src/num/saturating.rs b/core/src/num/saturating.rs index d040539ebe556..3f4791e163e69 100644 --- a/core/src/num/saturating.rs +++ b/core/src/num/saturating.rs @@ -1,10 +1,10 @@ //! Definitions of `Saturating`. use crate::fmt; -use crate::ops::{Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign}; -use crate::ops::{BitXor, BitXorAssign, Div, DivAssign}; -use crate::ops::{Mul, MulAssign, Neg, Not, Rem, RemAssign}; -use crate::ops::{Sub, SubAssign}; +use crate::ops::{ + Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, + Mul, MulAssign, Neg, Not, Rem, RemAssign, Sub, SubAssign, +}; /// Provides intentionally-saturating arithmetic on `T`. /// diff --git a/core/src/num/uint_macros.rs b/core/src/num/uint_macros.rs index ad72c29758bd7..a2e17fae76873 100644 --- a/core/src/num/uint_macros.rs +++ b/core/src/num/uint_macros.rs @@ -9,6 +9,7 @@ macro_rules! uint_impl { // literal is fine if they need to be multiple code tokens. // In non-comments, use the associated constants rather than these. BITS = $BITS:literal, + BITS_MINUS_ONE = $BITS_MINUS_ONE:literal, MAX = $MaxV:literal, rot = $rot:literal, rot_op = $rot_op:literal, @@ -65,8 +66,13 @@ macro_rules! uint_impl { /// /// ``` #[doc = concat!("let n = 0b01001100", stringify!($SelfT), ";")] - /// /// assert_eq!(n.count_ones(), 3); + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + #[doc = concat!("assert_eq!(max.count_ones(), ", stringify!($BITS), ");")] + /// + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + /// assert_eq!(zero.count_ones(), 0); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_math", since = "1.32.0")] @@ -86,7 +92,11 @@ macro_rules! uint_impl { /// Basic usage: /// /// ``` - #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);")] + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + #[doc = concat!("assert_eq!(zero.count_zeros(), ", stringify!($BITS), ");")] + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + /// assert_eq!(max.count_zeros(), 0); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_math", since = "1.32.0")] @@ -108,8 +118,13 @@ macro_rules! uint_impl { /// /// ``` #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")] - /// /// assert_eq!(n.leading_zeros(), 2); + /// + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + #[doc = concat!("assert_eq!(zero.leading_zeros(), ", stringify!($BITS), ");")] + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + /// assert_eq!(max.leading_zeros(), 0); /// ``` #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")] #[stable(feature = "rust1", since = "1.0.0")] @@ -130,8 +145,13 @@ macro_rules! uint_impl { /// /// ``` #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")] - /// /// assert_eq!(n.trailing_zeros(), 3); + /// + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + #[doc = concat!("assert_eq!(zero.trailing_zeros(), ", stringify!($BITS), ");")] + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + #[doc = concat!("assert_eq!(max.trailing_zeros(), 0);")] /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_math", since = "1.32.0")] @@ -150,8 +170,13 @@ macro_rules! uint_impl { /// /// ``` #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")] - /// /// assert_eq!(n.leading_ones(), 2); + /// + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + /// assert_eq!(zero.leading_ones(), 0); + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + #[doc = concat!("assert_eq!(max.leading_ones(), ", stringify!($BITS), ");")] /// ``` #[stable(feature = "leading_trailing_ones", since = "1.46.0")] #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")] @@ -171,8 +196,13 @@ macro_rules! uint_impl { /// /// ``` #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")] - /// /// assert_eq!(n.trailing_ones(), 3); + /// + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + /// assert_eq!(zero.trailing_ones(), 0); + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + #[doc = concat!("assert_eq!(max.trailing_ones(), ", stringify!($BITS), ");")] /// ``` #[stable(feature = "leading_trailing_ones", since = "1.46.0")] #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")] @@ -736,6 +766,67 @@ macro_rules! uint_impl { } } + #[doc = concat!( + "Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`", + stringify!($SignedT), "`], returning `None` if overflow occurred." + )] + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(unsigned_signed_diff)] + #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_signed_diff(2), Some(8));")] + #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_signed_diff(10), Some(-8));")] + #[doc = concat!( + "assert_eq!(", + stringify!($SelfT), + "::MAX.checked_signed_diff(", + stringify!($SignedT), + "::MAX as ", + stringify!($SelfT), + "), None);" + )] + #[doc = concat!( + "assert_eq!((", + stringify!($SignedT), + "::MAX as ", + stringify!($SelfT), + ").checked_signed_diff(", + stringify!($SelfT), + "::MAX), Some(", + stringify!($SignedT), + "::MIN));" + )] + #[doc = concat!( + "assert_eq!((", + stringify!($SignedT), + "::MAX as ", + stringify!($SelfT), + " + 1).checked_signed_diff(0), None);" + )] + #[doc = concat!( + "assert_eq!(", + stringify!($SelfT), + "::MAX.checked_signed_diff(", + stringify!($SelfT), + "::MAX), Some(0));" + )] + /// ``` + #[unstable(feature = "unsigned_signed_diff", issue = "126041")] + #[inline] + pub const fn checked_signed_diff(self, rhs: Self) -> Option<$SignedT> { + let res = self.wrapping_sub(rhs) as $SignedT; + let overflow = (self >= rhs) == (res < 0); + + if !overflow { + Some(res) + } else { + None + } + } + /// Checked integer multiplication. Computes `self * rhs`, returning /// `None` if overflow occurred. /// @@ -859,10 +950,10 @@ macro_rules! uint_impl { } /// Strict integer division. Computes `self / rhs`. - /// Strict division on unsigned types is just normal division. - /// There's no way overflow could ever happen. - /// This function exists, so that all operations - /// are accounted for in the strict operations. + /// + /// Strict division on unsigned types is just normal division. There's no + /// way overflow could ever happen. This function exists so that all + /// operations are accounted for in the strict operations. /// /// # Panics /// @@ -918,12 +1009,11 @@ macro_rules! uint_impl { } /// Strict Euclidean division. Computes `self.div_euclid(rhs)`. - /// Strict division on unsigned types is just normal division. - /// There's no way overflow could ever happen. - /// This function exists, so that all operations - /// are accounted for in the strict operations. - /// Since, for the positive integers, all common - /// definitions of division are equal, this + /// + /// Strict division on unsigned types is just normal division. There's no + /// way overflow could ever happen. This function exists so that all + /// operations are accounted for in the strict operations. Since, for the + /// positive integers, all common definitions of division are equal, this /// is exactly equal to `self.strict_div(rhs)`. /// /// # Panics @@ -981,11 +1071,11 @@ macro_rules! uint_impl { } /// Strict integer remainder. Computes `self % rhs`. - /// Strict remainder calculation on unsigned types is - /// just the regular remainder calculation. - /// There's no way overflow could ever happen. - /// This function exists, so that all operations - /// are accounted for in the strict operations. + /// + /// Strict remainder calculation on unsigned types is just the regular + /// remainder calculation. There's no way overflow could ever happen. + /// This function exists so that all operations are accounted for in the + /// strict operations. /// /// # Panics /// @@ -1041,14 +1131,13 @@ macro_rules! uint_impl { } /// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`. - /// Strict modulo calculation on unsigned types is - /// just the regular remainder calculation. - /// There's no way overflow could ever happen. - /// This function exists, so that all operations - /// are accounted for in the strict operations. - /// Since, for the positive integers, all common - /// definitions of division are equal, this - /// is exactly equal to `self.strict_rem(rhs)`. + /// + /// Strict modulo calculation on unsigned types is just the regular + /// remainder calculation. There's no way overflow could ever happen. + /// This function exists so that all operations are accounted for in the + /// strict operations. Since, for the positive integers, all common + /// definitions of division are equal, this is exactly equal to + /// `self.strict_rem(rhs)`. /// /// # Panics /// @@ -1226,10 +1315,9 @@ macro_rules! uint_impl { without modifying the original"] #[inline] pub const fn checked_ilog2(self) -> Option { - if let Some(x) = NonZero::new(self) { - Some(x.ilog2()) - } else { - None + match NonZero::new(self) { + Some(x) => Some(x.ilog2()), + None => None, } } @@ -1248,10 +1336,9 @@ macro_rules! uint_impl { without modifying the original"] #[inline] pub const fn checked_ilog10(self) -> Option { - if let Some(x) = NonZero::new(self) { - Some(x.ilog10()) - } else { - None + match NonZero::new(self) { + Some(x) => Some(x.ilog10()), + None => None, } } @@ -1325,6 +1412,7 @@ macro_rules! uint_impl { /// ``` #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")] #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")] + #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(", stringify!($BITS_MINUS_ONE), "), Some(0));")] /// ``` #[stable(feature = "wrapping", since = "1.7.0")] #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] @@ -1826,10 +1914,10 @@ macro_rules! uint_impl { } /// Wrapping (modular) division. Computes `self / rhs`. - /// Wrapped division on unsigned types is just normal division. - /// There's no way wrapping could ever happen. - /// This function exists, so that all operations - /// are accounted for in the wrapping operations. + /// + /// Wrapped division on unsigned types is just normal division. There's + /// no way wrapping could ever happen. This function exists so that all + /// operations are accounted for in the wrapping operations. /// /// # Panics /// @@ -1853,13 +1941,12 @@ macro_rules! uint_impl { } /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`. - /// Wrapped division on unsigned types is just normal division. - /// There's no way wrapping could ever happen. - /// This function exists, so that all operations - /// are accounted for in the wrapping operations. - /// Since, for the positive integers, all common - /// definitions of division are equal, this - /// is exactly equal to `self.wrapping_div(rhs)`. + /// + /// Wrapped division on unsigned types is just normal division. There's + /// no way wrapping could ever happen. This function exists so that all + /// operations are accounted for in the wrapping operations. Since, for + /// the positive integers, all common definitions of division are equal, + /// this is exactly equal to `self.wrapping_div(rhs)`. /// /// # Panics /// @@ -1883,11 +1970,11 @@ macro_rules! uint_impl { } /// Wrapping (modular) remainder. Computes `self % rhs`. - /// Wrapped remainder calculation on unsigned types is - /// just the regular remainder calculation. - /// There's no way wrapping could ever happen. - /// This function exists, so that all operations - /// are accounted for in the wrapping operations. + /// + /// Wrapped remainder calculation on unsigned types is just the regular + /// remainder calculation. There's no way wrapping could ever happen. + /// This function exists so that all operations are accounted for in the + /// wrapping operations. /// /// # Panics /// @@ -1911,14 +1998,13 @@ macro_rules! uint_impl { } /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`. - /// Wrapped modulo calculation on unsigned types is - /// just the regular remainder calculation. - /// There's no way wrapping could ever happen. - /// This function exists, so that all operations - /// are accounted for in the wrapping operations. - /// Since, for the positive integers, all common - /// definitions of division are equal, this - /// is exactly equal to `self.wrapping_rem(rhs)`. + /// + /// Wrapped modulo calculation on unsigned types is just the regular + /// remainder calculation. There's no way wrapping could ever happen. + /// This function exists so that all operations are accounted for in the + /// wrapping operations. Since, for the positive integers, all common + /// definitions of division are equal, this is exactly equal to + /// `self.wrapping_rem(rhs)`. /// /// # Panics /// @@ -2074,7 +2160,7 @@ macro_rules! uint_impl { acc.wrapping_mul(base) } - /// Calculates `self` + `rhs` + /// Calculates `self` + `rhs`. /// /// Returns a tuple of the addition along with a boolean indicating /// whether an arithmetic overflow would occur. If an overflow would @@ -2148,7 +2234,7 @@ macro_rules! uint_impl { (c, b || d) } - /// Calculates `self` + `rhs` with a signed `rhs` + /// Calculates `self` + `rhs` with a signed `rhs`. /// /// Returns a tuple of the addition along with a boolean indicating /// whether an arithmetic overflow would occur. If an overflow would @@ -2453,6 +2539,7 @@ macro_rules! uint_impl { /// ``` #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")] #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")] + #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shl(", stringify!($BITS_MINUS_ONE), "), (0, false));")] /// ``` #[stable(feature = "wrapping", since = "1.7.0")] #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] @@ -2590,37 +2677,10 @@ macro_rules! uint_impl { without modifying the original"] #[inline] pub const fn isqrt(self) -> Self { - if self < 2 { - return self; - } - - // The algorithm is based on the one presented in - // - // which cites as source the following C code: - // . - - let mut op = self; - let mut res = 0; - let mut one = 1 << (self.ilog2() & !1); - - while one != 0 { - if op >= res + one { - op -= res + one; - res = (res >> 1) + one; - } else { - res >>= 1; - } - one >>= 2; - } - - // SAFETY: the result is positive and fits in an integer with half as many bits. - // Inform the optimizer about it. - unsafe { - hint::assert_unchecked(0 < res); - hint::assert_unchecked(res < 1 << (Self::BITS / 2)); + match NonZero::new(self) { + Some(x) => x.isqrt().get(), + None => 0, } - - res } /// Performs Euclidean division. @@ -2793,6 +2853,35 @@ macro_rules! uint_impl { } } + /// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise. + /// + /// This function is equivalent to `self % rhs == 0`, except that it will not panic + /// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`, + /// `n.is_multiple_of(0) == false`. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(unsigned_is_multiple_of)] + #[doc = concat!("assert!(6_", stringify!($SelfT), ".is_multiple_of(2));")] + #[doc = concat!("assert!(!5_", stringify!($SelfT), ".is_multiple_of(2));")] + /// + #[doc = concat!("assert!(0_", stringify!($SelfT), ".is_multiple_of(0));")] + #[doc = concat!("assert!(!6_", stringify!($SelfT), ".is_multiple_of(0));")] + /// ``` + #[unstable(feature = "unsigned_is_multiple_of", issue = "128101")] + #[must_use] + #[inline] + #[rustc_inherit_overflow_checks] + pub const fn is_multiple_of(self, rhs: Self) -> bool { + match rhs { + 0 => self == 0, + _ => self % rhs == 0, + } + } + /// Returns `true` if and only if `self == 2^k` for some `k`. /// /// # Examples @@ -2906,7 +2995,7 @@ macro_rules! uint_impl { self.one_less_than_next_power_of_two().wrapping_add(1) } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// big-endian (network) byte order. /// #[doc = $to_xe_bytes_doc] @@ -2926,7 +3015,7 @@ macro_rules! uint_impl { self.to_be().to_ne_bytes() } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// little-endian byte order. /// #[doc = $to_xe_bytes_doc] @@ -2946,7 +3035,7 @@ macro_rules! uint_impl { self.to_le().to_ne_bytes() } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -2984,7 +3073,7 @@ macro_rules! uint_impl { unsafe { mem::transmute(self) } } - /// Create a native endian integer value from its representation + /// Creates a native endian integer value from its representation /// as a byte array in big endian. /// #[doc = $from_xe_bytes_doc] @@ -3013,7 +3102,7 @@ macro_rules! uint_impl { Self::from_be(Self::from_ne_bytes(bytes)) } - /// Create a native endian integer value from its representation + /// Creates a native endian integer value from its representation /// as a byte array in little endian. /// #[doc = $from_xe_bytes_doc] @@ -3042,7 +3131,7 @@ macro_rules! uint_impl { Self::from_le(Self::from_ne_bytes(bytes)) } - /// Create a native endian integer value from its memory representation + /// Creates a native endian integer value from its memory representation /// as a byte array in native endianness. /// /// As the target platform's native endianness is used, portable code diff --git a/core/src/num/wrapping.rs b/core/src/num/wrapping.rs index 16f0b6d913dfb..1ac6d3161c2f9 100644 --- a/core/src/num/wrapping.rs +++ b/core/src/num/wrapping.rs @@ -1,10 +1,10 @@ //! Definitions of `Wrapping`. use crate::fmt; -use crate::ops::{Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign}; -use crate::ops::{BitXor, BitXorAssign, Div, DivAssign}; -use crate::ops::{Mul, MulAssign, Neg, Not, Rem, RemAssign}; -use crate::ops::{Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign}; +use crate::ops::{ + Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, + Mul, MulAssign, Neg, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, +}; /// Provides intentionally-wrapped arithmetic on `T`. /// diff --git a/core/src/ops/async_function.rs b/core/src/ops/async_function.rs index 48d1042d9df4a..37fac2b126fac 100644 --- a/core/src/ops/async_function.rs +++ b/core/src/ops/async_function.rs @@ -4,7 +4,7 @@ use crate::marker::Tuple; /// An async-aware version of the [`Fn`](crate::ops::Fn) trait. /// /// All `async fn` and functions returning futures implement this trait. -#[unstable(feature = "async_fn_traits", issue = "none")] +#[unstable(feature = "async_closure", issue = "62290")] #[rustc_paren_sugar] #[fundamental] #[must_use = "async closures are lazy and do nothing unless called"] @@ -18,7 +18,7 @@ pub trait AsyncFn: AsyncFnMut { /// An async-aware version of the [`FnMut`](crate::ops::FnMut) trait. /// /// All `async fn` and functions returning futures implement this trait. -#[unstable(feature = "async_fn_traits", issue = "none")] +#[unstable(feature = "async_closure", issue = "62290")] #[rustc_paren_sugar] #[fundamental] #[must_use = "async closures are lazy and do nothing unless called"] @@ -39,7 +39,7 @@ pub trait AsyncFnMut: AsyncFnOnce { /// An async-aware version of the [`FnOnce`](crate::ops::FnOnce) trait. /// /// All `async fn` and functions returning futures implement this trait. -#[unstable(feature = "async_fn_traits", issue = "none")] +#[unstable(feature = "async_closure", issue = "62290")] #[rustc_paren_sugar] #[fundamental] #[must_use = "async closures are lazy and do nothing unless called"] diff --git a/core/src/ops/control_flow.rs b/core/src/ops/control_flow.rs index e10c438ef4300..a2709c66b06ad 100644 --- a/core/src/ops/control_flow.rs +++ b/core/src/ops/control_flow.rs @@ -238,7 +238,7 @@ impl ControlFlow { /// They have mediocre names and non-obvious semantics, so aren't /// currently on a path to potential stabilization. impl ControlFlow { - /// Create a `ControlFlow` from any type implementing `Try`. + /// Creates a `ControlFlow` from any type implementing `Try`. #[inline] pub(crate) fn from_try(r: R) -> Self { match R::branch(r) { @@ -247,7 +247,7 @@ impl ControlFlow { } } - /// Convert a `ControlFlow` into any type implementing `Try`; + /// Converts a `ControlFlow` into any type implementing `Try`. #[inline] pub(crate) fn into_try(self) -> R { match self { diff --git a/core/src/ops/coroutine.rs b/core/src/ops/coroutine.rs index 753f14c6b85ec..13df888d24c5c 100644 --- a/core/src/ops/coroutine.rs +++ b/core/src/ops/coroutine.rs @@ -76,7 +76,7 @@ pub trait Coroutine { /// values which are allowed to be returned each time a coroutine yields. /// For example an iterator-as-a-coroutine would likely have this type as /// `T`, the type being iterated over. - #[cfg_attr(not(bootstrap), lang = "coroutine_yield")] + #[lang = "coroutine_yield"] type Yield; /// The type of value this coroutine returns. @@ -85,7 +85,7 @@ pub trait Coroutine { /// `return` statement or implicitly as the last expression of a coroutine /// literal. For example futures would use this as `Result` as it /// represents a completed future. - #[cfg_attr(not(bootstrap), lang = "coroutine_return")] + #[lang = "coroutine_return"] type Return; /// Resumes the execution of this coroutine. diff --git a/core/src/ops/deref.rs b/core/src/ops/deref.rs index 9849410d484ca..f0d2c761ef35b 100644 --- a/core/src/ops/deref.rs +++ b/core/src/ops/deref.rs @@ -282,7 +282,7 @@ impl DerefMut for &mut T { /// FIXME(deref_patterns): The precise semantics are undecided; the rough idea is that /// successive calls to `deref`/`deref_mut` without intermediate mutation should be /// idempotent, in the sense that they return the same value as far as pattern-matching -/// is concerned. Calls to `deref`/`deref_mut`` must leave the pointer itself likewise +/// is concerned. Calls to `deref`/`deref_mut` must leave the pointer itself likewise /// unchanged. #[unstable(feature = "deref_pure_trait", issue = "87121")] #[lang = "deref_pure"] diff --git a/core/src/ops/drop.rs b/core/src/ops/drop.rs index 36ae581e3f723..c6083a121d107 100644 --- a/core/src/ops/drop.rs +++ b/core/src/ops/drop.rs @@ -171,12 +171,13 @@ /// still be live when `T` gets dropped. The exact details of this analysis are not yet /// stably guaranteed and **subject to change**. Currently, the analysis works as follows: /// - If `T` has no drop glue, then trivially nothing is required to be live. This is the case if -/// neither `T` nor any of its (recursive) fields have a destructor (`impl Drop`). [`PhantomData`] -/// and [`ManuallyDrop`] are considered to never have a destructor, no matter their field type. +/// neither `T` nor any of its (recursive) fields have a destructor (`impl Drop`). [`PhantomData`], +/// arrays of length 0 and [`ManuallyDrop`] are considered to never have a destructor, no matter +/// their field type. /// - If `T` has drop glue, then, for all types `U` that are *owned* by any field of `T`, /// recursively add the types and lifetimes that need to be live when `U` gets dropped. The set of /// owned types is determined by recursively traversing `T`: -/// - Recursively descend through `PhantomData`, `Box`, tuples, and arrays (including arrays of +/// - Recursively descend through `PhantomData`, `Box`, tuples, and arrays (excluding arrays of /// length 0). /// - Stop at reference and raw pointer types as well as function pointers and function items; /// they do not own anything. diff --git a/core/src/ops/mod.rs b/core/src/ops/mod.rs index 7bcfaadbe372b..98d41b71e8eb8 100644 --- a/core/src/ops/mod.rs +++ b/core/src/ops/mod.rs @@ -156,65 +156,44 @@ mod unsize; pub use self::arith::{Add, Div, Mul, Neg, Rem, Sub}; #[stable(feature = "op_assign_traits", since = "1.8.0")] pub use self::arith::{AddAssign, DivAssign, MulAssign, RemAssign, SubAssign}; - +#[unstable(feature = "async_fn_traits", issue = "none")] +pub use self::async_function::{AsyncFn, AsyncFnMut, AsyncFnOnce}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::bit::{BitAnd, BitOr, BitXor, Not, Shl, Shr}; #[stable(feature = "op_assign_traits", since = "1.8.0")] pub use self::bit::{BitAndAssign, BitOrAssign, BitXorAssign, ShlAssign, ShrAssign}; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::deref::{Deref, DerefMut}; - +#[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")] +pub use self::control_flow::ControlFlow; +#[unstable(feature = "coroutine_trait", issue = "43122")] +pub use self::coroutine::{Coroutine, CoroutineState}; #[unstable(feature = "deref_pure_trait", issue = "87121")] pub use self::deref::DerefPure; - #[unstable(feature = "receiver_trait", issue = "none")] pub use self::deref::Receiver; - #[stable(feature = "rust1", since = "1.0.0")] -pub use self::drop::Drop; - +pub use self::deref::{Deref, DerefMut}; pub(crate) use self::drop::fallback_surface_drop; - +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::drop::Drop; #[stable(feature = "rust1", since = "1.0.0")] pub use self::function::{Fn, FnMut, FnOnce}; - -#[unstable(feature = "async_fn_traits", issue = "none")] -pub use self::async_function::{AsyncFn, AsyncFnMut, AsyncFnOnce}; - #[stable(feature = "rust1", since = "1.0.0")] pub use self::index::{Index, IndexMut}; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::range::{Range, RangeFrom, RangeFull, RangeTo}; - pub(crate) use self::index_range::IndexRange; - -#[stable(feature = "inclusive_range", since = "1.26.0")] -pub use self::range::{Bound, RangeBounds, RangeInclusive, RangeToInclusive}; - #[unstable(feature = "one_sided_range", issue = "69780")] pub use self::range::OneSidedRange; - -#[unstable(feature = "try_trait_v2", issue = "84277")] -pub use self::try_trait::{FromResidual, Try}; - -#[unstable(feature = "try_trait_v2_yeet", issue = "96374")] -pub use self::try_trait::Yeet; - +#[stable(feature = "inclusive_range", since = "1.26.0")] +pub use self::range::{Bound, RangeBounds, RangeInclusive, RangeToInclusive}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::range::{Range, RangeFrom, RangeFull, RangeTo}; #[unstable(feature = "try_trait_v2_residual", issue = "91285")] pub use self::try_trait::Residual; - +#[unstable(feature = "try_trait_v2_yeet", issue = "96374")] +pub use self::try_trait::Yeet; pub(crate) use self::try_trait::{ChangeOutputType, NeverShortCircuit}; - -#[unstable(feature = "coroutine_trait", issue = "43122")] -pub use self::coroutine::{Coroutine, CoroutineState}; - +#[unstable(feature = "try_trait_v2", issue = "84277")] +pub use self::try_trait::{FromResidual, Try}; #[unstable(feature = "coerce_unsized", issue = "18598")] pub use self::unsize::CoerceUnsized; - #[unstable(feature = "dispatch_from_dyn", issue = "none")] pub use self::unsize::DispatchFromDyn; - -#[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")] -pub use self::control_flow::ControlFlow; diff --git a/core/src/option.rs b/core/src/option.rs index 8ec7716012f59..6c89c81018038 100644 --- a/core/src/option.rs +++ b/core/src/option.rs @@ -557,13 +557,10 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::iter::{self, FusedIterator, TrustedLen}; +use crate::ops::{self, ControlFlow, Deref, DerefMut}; use crate::panicking::{panic, panic_display}; use crate::pin::Pin; -use crate::{ - cmp, convert, hint, mem, - ops::{self, ControlFlow, Deref, DerefMut}, - slice, -}; +use crate::{cmp, convert, hint, mem, slice}; /// The `Option` type. See [the module level documentation](self) for more. #[derive(Copy, Eq, Debug, Hash)] @@ -770,6 +767,13 @@ impl Option { } } + #[inline] + const fn len(&self) -> usize { + // Using the intrinsic avoids emitting a branch to get the 0 or 1. + let discriminant: isize = crate::intrinsics::discriminant_value(self); + discriminant as usize + } + /// Returns a slice of the contained value, if any. If this is `None`, an /// empty slice is returned. This can be useful to have a single type of /// iterator over an `Option` or slice. @@ -812,7 +816,7 @@ impl Option { unsafe { slice::from_raw_parts( (self as *const Self).byte_add(core::mem::offset_of!(Self, Some.0)).cast(), - self.is_some() as usize, + self.len(), ) } } @@ -869,7 +873,7 @@ impl Option { unsafe { slice::from_raw_parts_mut( (self as *mut Self).byte_add(core::mem::offset_of!(Self, Some.0)).cast(), - self.is_some() as usize, + self.len(), ) } } @@ -2242,10 +2246,8 @@ impl Iterator for Item { #[inline] fn size_hint(&self) -> (usize, Option) { - match self.opt { - Some(_) => (1, Some(1)), - None => (0, Some(0)), - } + let len = self.len(); + (len, Some(len)) } } @@ -2256,7 +2258,12 @@ impl DoubleEndedIterator for Item { } } -impl ExactSizeIterator for Item {} +impl ExactSizeIterator for Item { + #[inline] + fn len(&self) -> usize { + self.opt.len() + } +} impl FusedIterator for Item {} unsafe impl TrustedLen for Item {} @@ -2497,6 +2504,7 @@ impl ops::FromResidual for Option { } } +#[diagnostic::do_not_recommend] #[unstable(feature = "try_trait_v2_yeet", issue = "96374")] impl ops::FromResidual> for Option { #[inline] diff --git a/core/src/panic.rs b/core/src/panic.rs index 37c338dd9b778..6c5236ed99ce8 100644 --- a/core/src/panic.rs +++ b/core/src/panic.rs @@ -6,16 +6,15 @@ mod location; mod panic_info; mod unwind_safe; -use crate::any::Any; - #[stable(feature = "panic_hooks", since = "1.10.0")] pub use self::location::Location; #[stable(feature = "panic_hooks", since = "1.10.0")] pub use self::panic_info::PanicInfo; -#[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "panic_info_message", since = "1.81.0")] pub use self::panic_info::PanicMessage; #[stable(feature = "catch_unwind", since = "1.9.0")] pub use self::unwind_safe::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe}; +use crate::any::Any; #[doc(hidden)] #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")] @@ -160,7 +159,7 @@ pub unsafe trait PanicPayload: crate::fmt::Display { /// Just borrow the contents. fn get(&mut self) -> &(dyn Any + Send); - /// Try to borrow the contents as `&str`, if possible without doing any allocations. + /// Tries to borrow the contents as `&str`, if possible without doing any allocations. fn as_str(&mut self) -> Option<&str> { None } diff --git a/core/src/panic/panic_info.rs b/core/src/panic/panic_info.rs index 6bbb9c3017110..e4d0c897b65ca 100644 --- a/core/src/panic/panic_info.rs +++ b/core/src/panic/panic_info.rs @@ -24,7 +24,7 @@ pub struct PanicInfo<'a> { /// that were given to the `panic!()` macro. /// /// See [`PanicInfo::message`]. -#[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "panic_info_message", since = "1.81.0")] pub struct PanicMessage<'a> { message: fmt::Arguments<'a>, } @@ -57,7 +57,7 @@ impl<'a> PanicInfo<'a> { /// } /// ``` #[must_use] - #[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "panic_info_message", since = "1.81.0")] pub fn message(&self) -> PanicMessage<'_> { PanicMessage { message: self.message } } @@ -152,7 +152,7 @@ impl Display for PanicInfo<'_> { } impl<'a> PanicMessage<'a> { - /// Get the formatted message, if it has no arguments to be formatted at runtime. + /// Gets the formatted message, if it has no arguments to be formatted at runtime. /// /// This can be used to avoid allocations in some cases. /// @@ -164,7 +164,7 @@ impl<'a> PanicMessage<'a> { /// For most cases with placeholders, this function will return `None`. /// /// See [`fmt::Arguments::as_str`] for details. - #[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "panic_info_message", since = "1.81.0")] #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "103900")] #[must_use] #[inline] @@ -173,7 +173,7 @@ impl<'a> PanicMessage<'a> { } } -#[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "panic_info_message", since = "1.81.0")] impl Display for PanicMessage<'_> { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -181,7 +181,7 @@ impl Display for PanicMessage<'_> { } } -#[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "panic_info_message", since = "1.81.0")] impl fmt::Debug for PanicMessage<'_> { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/core/src/panicking.rs b/core/src/panicking.rs index 97fb1d6b7323f..7affe63825719 100644 --- a/core/src/panicking.rs +++ b/core/src/panicking.rs @@ -294,10 +294,11 @@ fn panic_misaligned_pointer_dereference(required: usize, found: usize) -> ! { ) } -/// Panic because we cannot unwind out of a function. +/// Panics because we cannot unwind out of a function. /// /// This is a separate function to avoid the codesize impact of each crate containing the string to /// pass to `panic_nounwind`. +/// /// This function is called directly by the codegen backend, and must not have /// any extra arguments (including those synthesized by track_caller). #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] @@ -309,10 +310,11 @@ fn panic_cannot_unwind() -> ! { panic_nounwind("panic in a function that cannot unwind") } -/// Panic because we are unwinding out of a destructor during cleanup. +/// Panics because we are unwinding out of a destructor during cleanup. /// /// This is a separate function to avoid the codesize impact of each crate containing the string to /// pass to `panic_nounwind`. +/// /// This function is called directly by the codegen backend, and must not have /// any extra arguments (including those synthesized by track_caller). #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] diff --git a/core/src/pin.rs b/core/src/pin.rs index 0d2aa3070a19f..d752151d10cc8 100644 --- a/core/src/pin.rs +++ b/core/src/pin.rs @@ -421,7 +421,7 @@ //! } //! //! impl Unmovable { -//! /// Create a new `Unmovable`. +//! /// Creates a new `Unmovable`. //! /// //! /// To ensure the data doesn't move we place it on the heap behind a pinning Box. //! /// Note that the data is pinned, but the `Pin>` which is pinning it can @@ -920,11 +920,8 @@ #![stable(feature = "pin", since = "1.33.0")] -use crate::cmp; -use crate::fmt; use crate::hash::{Hash, Hasher}; use crate::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver}; - #[allow(unused_imports)] use crate::{ cell::{RefCell, UnsafeCell}, @@ -932,6 +929,7 @@ use crate::{ marker::PhantomPinned, mem, ptr, }; +use crate::{cmp, fmt}; /// A pointer which pins its pointee in place. /// @@ -1168,7 +1166,7 @@ impl> Hash for Pin { } impl> Pin { - /// Construct a new `Pin` around a pointer to some data of a type that + /// Constructs a new `Pin` around a pointer to some data of a type that /// implements [`Unpin`]. /// /// Unlike `Pin::new_unchecked`, this method is safe because the pointer @@ -1223,7 +1221,7 @@ impl> Pin { } impl Pin { - /// Construct a new `Pin` around a reference to some data of a type that + /// Constructs a new `Pin` around a reference to some data of a type that /// may or may not implement [`Unpin`]. /// /// If `pointer` dereferences to an [`Unpin`] type, [`Pin::new`] should be used @@ -1569,7 +1567,7 @@ impl<'a, T: ?Sized> Pin<&'a mut T> { self.__pointer } - /// Construct a new pin by mapping the interior value. + /// Constructs a new pin by mapping the interior value. /// /// For example, if you wanted to get a `Pin` of a field of something, /// you could use this to get access to that field in one line of code. @@ -1602,7 +1600,7 @@ impl<'a, T: ?Sized> Pin<&'a mut T> { } impl Pin<&'static T> { - /// Get a pinning reference from a `&'static` reference. + /// Gets a pinning reference from a `&'static` reference. /// /// This is safe because `T` is borrowed immutably for the `'static` lifetime, which /// never ends. @@ -1639,8 +1637,8 @@ impl<'a, Ptr: DerefMut> Pin<&'a mut Pin> { // // We need to ensure that two things hold for that to be the case: // - // 1) Once we give out a `Pin<&mut Ptr::Target>`, an `&mut Ptr::Target` will not be given out. - // 2) By giving out a `Pin<&mut Ptr::Target>`, we do not risk of violating + // 1) Once we give out a `Pin<&mut Ptr::Target>`, a `&mut Ptr::Target` will not be given out. + // 2) By giving out a `Pin<&mut Ptr::Target>`, we do not risk violating // `Pin<&mut Pin>` // // The existence of `Pin` is sufficient to guarantee #1: since we already have a @@ -1656,7 +1654,7 @@ impl<'a, Ptr: DerefMut> Pin<&'a mut Pin> { } impl Pin<&'static mut T> { - /// Get a pinning mutable reference from a static mutable reference. + /// Gets a pinning mutable reference from a static mutable reference. /// /// This is safe because `T` is borrowed for the `'static` lifetime, which /// never ends. diff --git a/core/src/primitive.rs b/core/src/primitive.rs index e20b2c5c9382a..81a72118614dd 100644 --- a/core/src/primitive.rs +++ b/core/src/primitive.rs @@ -12,7 +12,7 @@ //! const SOME_PROPERTY: bool = true; //! } //! -//! # trait QueryId { const SOME_PROPERTY: core::primitive::bool; } +//! # trait QueryId { const SOME_PROPERTY: ::core::primitive::bool; } //! ``` //! //! Note that the `SOME_PROPERTY` associated constant would not compile, as its @@ -25,11 +25,17 @@ //! pub struct bool; //! //! impl QueryId for bool { -//! const SOME_PROPERTY: core::primitive::bool = true; +//! const SOME_PROPERTY: ::core::primitive::bool = true; //! } //! -//! # trait QueryId { const SOME_PROPERTY: core::primitive::bool; } +//! # trait QueryId { const SOME_PROPERTY: ::core::primitive::bool; } //! ``` +//! +//! We also used `::core` instead of `core`, because `core` can be +//! shadowed, too. Paths, starting with `::`, are searched in +//! the [extern prelude] since Edition 2018. +//! +//! [extern prelude]: https://doc.rust-lang.org/nightly/reference/names/preludes.html#extern-prelude #[stable(feature = "core_primitive", since = "1.43.0")] pub use bool; diff --git a/core/src/ptr/const_ptr.rs b/core/src/ptr/const_ptr.rs index 3e7933e9eec86..93bbd92593f2c 100644 --- a/core/src/ptr/const_ptr.rs +++ b/core/src/ptr/const_ptr.rs @@ -61,7 +61,7 @@ impl *const T { self as _ } - /// Use the pointer value in a new pointer of another type. + /// Uses the pointer value in a new pointer of another type. /// /// In case `meta` is a (fat) pointer to an unsized type, this operation /// will ignore the pointer part, whereas for (thin) pointers to sized diff --git a/core/src/ptr/metadata.rs b/core/src/ptr/metadata.rs index eb86bf6620652..ccc9f8754f00c 100644 --- a/core/src/ptr/metadata.rs +++ b/core/src/ptr/metadata.rs @@ -2,9 +2,9 @@ use crate::fmt; use crate::hash::{Hash, Hasher}; -use crate::intrinsics::aggregate_raw_ptr; -use crate::intrinsics::ptr_metadata; +use crate::intrinsics::{aggregate_raw_ptr, ptr_metadata}; use crate::marker::Freeze; +use crate::ptr::NonNull; /// Provides the pointer metadata type of any pointed-to type. /// @@ -80,7 +80,7 @@ pub trait Pointee { // NOTE: don’t stabilize this before trait aliases are stable in the language? pub trait Thin = Pointee; -/// Extract the metadata component of a pointer. +/// Extracts the metadata component of a pointer. /// /// Values of type `*mut T`, `&T`, or `&mut T` can be passed directly to this function /// as they implicitly coerce to `*const T`. @@ -153,7 +153,7 @@ pub const fn from_raw_parts_mut( /// compare equal (since identical vtables can be deduplicated within a codegen unit). #[lang = "dyn_metadata"] pub struct DynMetadata { - _vtable_ptr: &'static VTable, + _vtable_ptr: NonNull, _phantom: crate::marker::PhantomData, } @@ -166,15 +166,18 @@ extern "C" { } impl DynMetadata { - /// One of the things that rustc_middle does with this being a lang item is - /// give it `FieldsShape::Primitive`, which means that as far as codegen can - /// tell, it *is* a reference, and thus doesn't have any fields. - /// That means we can't use field access, and have to transmute it instead. + /// When `DynMetadata` appears as the metadata field of a wide pointer, the rustc_middle layout + /// computation does magic and the resulting layout is *not* a `FieldsShape::Aggregate`, instead + /// it is a `FieldsShape::Primitive`. This means that the same type can have different layout + /// depending on whether it appears as the metadata field of a wide pointer or as a stand-alone + /// type, which understandably confuses codegen and leads to ICEs when trying to project to a + /// field of `DynMetadata`. To work around that issue, we use `transmute` instead of using a + /// field projection. #[inline] fn vtable_ptr(self) -> *const VTable { // SAFETY: this layout assumption is hard-coded into the compiler. // If it's somehow not a size match, the transmute will error. - unsafe { crate::mem::transmute::(self) } + unsafe { crate::mem::transmute::(self) } } /// Returns the size of the type associated with this vtable. diff --git a/core/src/ptr/mod.rs b/core/src/ptr/mod.rs index f2247e83ec5c5..25d8f4a0adbd9 100644 --- a/core/src/ptr/mod.rs +++ b/core/src/ptr/mod.rs @@ -196,9 +196,9 @@ //! * The **provenance** it has, defining the memory it has permission to access. //! Provenance can be absent, in which case the pointer does not have permission to access any memory. //! -//! Under Strict Provenance, a usize *cannot* accurately represent a pointer, and converting from -//! a pointer to a usize is generally an operation which *only* extracts the address. It is -//! therefore *impossible* to construct a valid pointer from a usize because there is no way +//! Under Strict Provenance, a `usize` *cannot* accurately represent a pointer, and converting from +//! a pointer to a `usize` is generally an operation which *only* extracts the address. It is +//! therefore *impossible* to construct a valid pointer from a `usize` because there is no way //! to restore the address-space and provenance. In other words, pointer-integer-pointer //! roundtrips are not possible (in the sense that the resulting pointer is not dereferenceable). //! @@ -234,16 +234,16 @@ //! //! Most code needs no changes to conform to strict provenance, as the only really concerning //! operation that *wasn't* obviously already Undefined Behaviour is casts from usize to a -//! pointer. For code which *does* cast a usize to a pointer, the scope of the change depends +//! pointer. For code which *does* cast a `usize` to a pointer, the scope of the change depends //! on exactly what you're doing. //! -//! In general, you just need to make sure that if you want to convert a usize address to a +//! In general, you just need to make sure that if you want to convert a `usize` address to a //! pointer and then use that pointer to read/write memory, you need to keep around a pointer //! that has sufficient provenance to perform that read/write itself. In this way all of your //! casts from an address to a pointer are essentially just applying offsets/indexing. //! //! This is generally trivial to do for simple cases like tagged pointers *as long as you -//! represent the tagged pointer as an actual pointer and not a usize*. For instance: +//! represent the tagged pointer as an actual pointer and not a `usize`*. For instance: //! //! ``` //! #![feature(strict_provenance)] @@ -409,13 +409,9 @@ #![allow(clippy::not_unsafe_ptr_arg_deref)] use crate::cmp::Ordering; -use crate::fmt; -use crate::hash; -use crate::intrinsics; use crate::marker::FnPtr; -use crate::ub_checks; - use crate::mem::{self, MaybeUninit}; +use crate::{fmt, hash, intrinsics, ub_checks}; mod alignment; #[unstable(feature = "ptr_alignment_type", issue = "102070")] @@ -423,12 +419,10 @@ pub use alignment::Alignment; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] -pub use crate::intrinsics::copy_nonoverlapping; - +pub use crate::intrinsics::copy; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] -pub use crate::intrinsics::copy; - +pub use crate::intrinsics::copy_nonoverlapping; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] pub use crate::intrinsics::write_bytes; @@ -606,7 +600,7 @@ pub const fn null_mut() -> *mut T { /// Without provenance, this pointer is not associated with any actual allocation. Such a /// no-provenance pointer may be used for zero-sized memory accesses (if suitably aligned), but /// non-zero-sized memory accesses with a no-provenance pointer are UB. No-provenance pointers are -/// little more than a usize address in disguise. +/// little more than a `usize` address in disguise. /// /// This is different from `addr as *const T`, which creates a pointer that picks up a previously /// exposed provenance. See [`with_exposed_provenance`] for more details on that operation. @@ -650,7 +644,7 @@ pub const fn dangling() -> *const T { /// Without provenance, this pointer is not associated with any actual allocation. Such a /// no-provenance pointer may be used for zero-sized memory accesses (if suitably aligned), but /// non-zero-sized memory accesses with a no-provenance pointer are UB. No-provenance pointers are -/// little more than a usize address in disguise. +/// little more than a `usize` address in disguise. /// /// This is different from `addr as *mut T`, which creates a pointer that picks up a previously /// exposed provenance. See [`with_exposed_provenance_mut`] for more details on that operation. @@ -687,7 +681,7 @@ pub const fn dangling_mut() -> *mut T { without_provenance_mut(mem::align_of::()) } -/// Convert an address back to a pointer, picking up a previously 'exposed' provenance. +/// Converts an address back to a pointer, picking up a previously 'exposed' provenance. /// /// This is a more rigorously specified alternative to `addr as *const T`. The provenance of the /// returned pointer is that of *any* pointer that was previously exposed by passing it to @@ -735,7 +729,7 @@ where addr as *const T } -/// Convert an address back to a mutable pointer, picking up a previously 'exposed' provenance. +/// Converts an address back to a mutable pointer, picking up a previously 'exposed' provenance. /// /// This is a more rigorously specified alternative to `addr as *mut T`. The provenance of the /// returned pointer is that of *any* pointer that was previously passed to @@ -775,10 +769,53 @@ where addr as *mut T } -/// Convert a reference to a raw pointer. +/// Converts a reference to a raw pointer. /// -/// This is equivalent to `r as *const T`, but is a bit safer since it will never silently change -/// type or mutability, in particular if the code is refactored. +/// For `r: &T`, `from_ref(r)` is equivalent to `r as *const T` (except for the caveat noted below), +/// but is a bit safer since it will never silently change type or mutability, in particular if the +/// code is refactored. +/// +/// The caller must ensure that the pointee outlives the pointer this function returns, or else it +/// will end up dangling. +/// +/// The caller must also ensure that the memory the pointer (non-transitively) points to is never +/// written to (except inside an `UnsafeCell`) using this pointer or any pointer derived from it. If +/// you need to mutate the pointee, use [`from_mut`]. Specifically, to turn a mutable reference `m: +/// &mut T` into `*const T`, prefer `from_mut(m).cast_const()` to obtain a pointer that can later be +/// used for mutation. +/// +/// ## Interaction with lifetime extension +/// +/// Note that this has subtle interactions with the rules for lifetime extension of temporaries in +/// tail expressions. This code is valid, albeit in a non-obvious way: +/// ```rust +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// // The temporary holding the return value of `foo` has its lifetime extended, +/// // because the surrounding expression involves no function call. +/// let p = &foo() as *const T; +/// unsafe { p.read() }; +/// ``` +/// Naively replacing the cast with `from_ref` is not valid: +/// ```rust,no_run +/// # use std::ptr; +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// // The temporary holding the return value of `foo` does *not* have its lifetime extended, +/// // because the surrounding expression involves no function call. +/// let p = ptr::from_ref(&foo()); +/// unsafe { p.read() }; // UB! Reading from a dangling pointer ⚠️ +/// ``` +/// The recommended way to write this code is to avoid relying on lifetime extension +/// when raw pointers are involved: +/// ```rust +/// # use std::ptr; +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// let x = foo(); +/// let p = ptr::from_ref(&x); +/// unsafe { p.read() }; +/// ``` #[inline(always)] #[must_use] #[stable(feature = "ptr_from_ref", since = "1.76.0")] @@ -789,10 +826,47 @@ pub const fn from_ref(r: &T) -> *const T { r } -/// Convert a mutable reference to a raw pointer. +/// Converts a mutable reference to a raw pointer. +/// +/// For `r: &mut T`, `from_mut(r)` is equivalent to `r as *mut T` (except for the caveat noted +/// below), but is a bit safer since it will never silently change type or mutability, in particular +/// if the code is refactored. +/// +/// The caller must ensure that the pointee outlives the pointer this function returns, or else it +/// will end up dangling. +/// +/// ## Interaction with lifetime extension /// -/// This is equivalent to `r as *mut T`, but is a bit safer since it will never silently change -/// type or mutability, in particular if the code is refactored. +/// Note that this has subtle interactions with the rules for lifetime extension of temporaries in +/// tail expressions. This code is valid, albeit in a non-obvious way: +/// ```rust +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// // The temporary holding the return value of `foo` has its lifetime extended, +/// // because the surrounding expression involves no function call. +/// let p = &mut foo() as *mut T; +/// unsafe { p.write(T::default()) }; +/// ``` +/// Naively replacing the cast with `from_mut` is not valid: +/// ```rust,no_run +/// # use std::ptr; +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// // The temporary holding the return value of `foo` does *not* have its lifetime extended, +/// // because the surrounding expression involves no function call. +/// let p = ptr::from_mut(&mut foo()); +/// unsafe { p.write(T::default()) }; // UB! Writing to a dangling pointer ⚠️ +/// ``` +/// The recommended way to write this code is to avoid relying on lifetime extension +/// when raw pointers are involved: +/// ```rust +/// # use std::ptr; +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// let mut x = foo(); +/// let p = ptr::from_mut(&mut x); +/// unsafe { p.write(T::default()) }; +/// ``` #[inline(always)] #[must_use] #[stable(feature = "ptr_from_ref", since = "1.76.0")] @@ -1388,7 +1462,7 @@ pub const unsafe fn read(src: *const T) -> T { /// /// # Examples /// -/// Read a usize value from a byte buffer: +/// Read a `usize` value from a byte buffer: /// /// ``` /// use std::mem; @@ -1599,7 +1673,7 @@ pub const unsafe fn write(dst: *mut T, src: T) { /// /// # Examples /// -/// Write a usize value to a byte buffer: +/// Write a `usize` value to a byte buffer: /// /// ``` /// use std::mem; @@ -1934,7 +2008,7 @@ pub(crate) const unsafe fn align_offset(p: *const T, a: usize) -> usiz let y = cttz_nonzero(a); if x < y { x } else { y } }; - // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a usize. + // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a `usize`. let gcd = unsafe { unchecked_shl(1usize, gcdpow) }; // SAFETY: gcd is always greater or equal to 1. if addr & unsafe { unchecked_sub(gcd, 1) } == 0 { @@ -2133,7 +2207,7 @@ impl fmt::Debug for F { } } -/// Create a `const` raw pointer to a place, without creating an intermediate reference. +/// Creates a `const` raw pointer to a place, without creating an intermediate reference. /// /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned /// and points to initialized data. For cases where those requirements do not hold, @@ -2207,7 +2281,7 @@ pub macro addr_of($place:expr) { &raw const $place } -/// Create a `mut` raw pointer to a place, without creating an intermediate reference. +/// Creates a `mut` raw pointer to a place, without creating an intermediate reference. /// /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned /// and points to initialized data. For cases where those requirements do not hold, diff --git a/core/src/ptr/mut_ptr.rs b/core/src/ptr/mut_ptr.rs index 904d6c62dcf1e..bcf9b889182c7 100644 --- a/core/src/ptr/mut_ptr.rs +++ b/core/src/ptr/mut_ptr.rs @@ -60,7 +60,7 @@ impl *mut T { self as _ } - /// Use the pointer value in a new pointer of another type. + /// Uses the pointer value in a new pointer of another type. /// /// In case `meta` is a (fat) pointer to an unsized type, this operation /// will ignore the pointer part, whereas for (thin) pointers to sized diff --git a/core/src/ptr/non_null.rs b/core/src/ptr/non_null.rs index 796c85d0cacc7..4a716a7503964 100644 --- a/core/src/ptr/non_null.rs +++ b/core/src/ptr/non_null.rs @@ -1,15 +1,12 @@ use crate::cmp::Ordering; -use crate::fmt; -use crate::hash; -use crate::intrinsics; use crate::marker::Unsize; use crate::mem::{MaybeUninit, SizedTypeProperties}; use crate::num::NonZero; use crate::ops::{CoerceUnsized, DispatchFromDyn}; -use crate::ptr; use crate::ptr::Unique; use crate::slice::{self, SliceIndex}; use crate::ub_checks::assert_unsafe_precondition; +use crate::{fmt, hash, intrinsics, ptr}; /// `*mut T` but non-zero and [covariant]. /// diff --git a/core/src/range.rs b/core/src/range.rs index bfbbf123b1ca5..408972c267f1a 100644 --- a/core/src/range.rs +++ b/core/src/range.rs @@ -25,15 +25,13 @@ mod iter; pub mod legacy; #[doc(inline)] -pub use crate::ops::{Bound, OneSidedRange, RangeBounds, RangeFull, RangeTo, RangeToInclusive}; - +pub use iter::{IterRange, IterRangeFrom, IterRangeInclusive}; use Bound::{Excluded, Included, Unbounded}; #[doc(inline)] pub use crate::iter::Step; - #[doc(inline)] -pub use iter::{IterRange, IterRangeFrom, IterRangeInclusive}; +pub use crate::ops::{Bound, OneSidedRange, RangeBounds, RangeFull, RangeTo, RangeToInclusive}; /// A (half-open) range bounded inclusively below and exclusively above /// (`start..end` in a future edition). @@ -72,7 +70,7 @@ impl fmt::Debug for Range { } impl Range { - /// Create an iterator over the elements within this range. + /// Creates an iterator over the elements within this range. /// /// Shorthand for `.clone().into_iter()` /// @@ -292,7 +290,7 @@ impl> RangeInclusive { } impl RangeInclusive { - /// Create an iterator over the elements within this range. + /// Creates an iterator over the elements within this range. /// /// Shorthand for `.clone().into_iter()` /// @@ -408,7 +406,7 @@ impl fmt::Debug for RangeFrom { } impl RangeFrom { - /// Create an iterator over the elements within this range. + /// Creates an iterator over the elements within this range. /// /// Shorthand for `.clone().into_iter()` /// diff --git a/core/src/range/iter.rs b/core/src/range/iter.rs index 2b7db475ffb2c..4935280df60bc 100644 --- a/core/src/range/iter.rs +++ b/core/src/range/iter.rs @@ -1,9 +1,8 @@ -use crate::num::NonZero; -use crate::range::{legacy, Range, RangeFrom, RangeInclusive}; - use crate::iter::{ FusedIterator, Step, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, TrustedStep, }; +use crate::num::NonZero; +use crate::range::{legacy, Range, RangeFrom, RangeInclusive}; /// By-value [`Range`] iterator. #[unstable(feature = "new_range_api", issue = "125687")] diff --git a/core/src/result.rs b/core/src/result.rs index f8cdcc000c50e..7f278296b7b88 100644 --- a/core/src/result.rs +++ b/core/src/result.rs @@ -1990,7 +1990,7 @@ impl> ops::FromResidual> for Res } } } - +#[diagnostic::do_not_recommend] #[unstable(feature = "try_trait_v2_yeet", issue = "96374")] impl> ops::FromResidual> for Result { #[inline] diff --git a/core/src/slice/ascii.rs b/core/src/slice/ascii.rs index bf444d2f68af8..d1ea52fab6b87 100644 --- a/core/src/slice/ascii.rs +++ b/core/src/slice/ascii.rs @@ -1,12 +1,10 @@ //! Operations on ASCII `[u8]`. -use crate::ascii; -use crate::fmt::{self, Write}; -use crate::iter; -use crate::mem; -use crate::ops; use core::ascii::EscapeDefault; +use crate::fmt::{self, Write}; +use crate::{ascii, iter, mem, ops}; + #[cfg(not(test))] impl [u8] { /// Checks if all bytes in this slice are within the ASCII range. diff --git a/core/src/slice/cmp.rs b/core/src/slice/cmp.rs index 5bee4d551352e..d19d0eae16671 100644 --- a/core/src/slice/cmp.rs +++ b/core/src/slice/cmp.rs @@ -1,12 +1,10 @@ //! Comparison traits for `[T]`. +use super::{from_raw_parts, memchr}; use crate::cmp::{self, BytewiseEq, Ordering}; use crate::intrinsics::compare_bytes; use crate::mem; -use super::from_raw_parts; -use super::memchr; - #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq<[U]> for [T] where diff --git a/core/src/slice/index.rs b/core/src/slice/index.rs index 2624a44bb4bcb..de1492e82ce7d 100644 --- a/core/src/slice/index.rs +++ b/core/src/slice/index.rs @@ -1,9 +1,8 @@ //! Indexing implementations for `[T]`. use crate::intrinsics::const_eval_select; -use crate::ops; -use crate::range; use crate::ub_checks::assert_unsafe_precondition; +use crate::{ops, range}; #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index for [T] @@ -214,6 +213,7 @@ pub unsafe trait SliceIndex: private_slice_index::Sealed { /// Returns a pointer to the output at this location, without /// performing any bounds checking. + /// /// Calling this method with an out-of-bounds index or a dangling `slice` pointer /// is *[undefined behavior]* even if the resulting pointer is not used. /// @@ -223,6 +223,7 @@ pub unsafe trait SliceIndex: private_slice_index::Sealed { /// Returns a mutable pointer to the output at this location, without /// performing any bounds checking. + /// /// Calling this method with an out-of-bounds index or a dangling `slice` pointer /// is *[undefined behavior]* even if the resulting pointer is not used. /// @@ -802,13 +803,13 @@ unsafe impl SliceIndex<[T]> for ops::RangeToInclusive { } } -/// Performs bounds-checking of a range. +/// Performs bounds checking of a range. /// /// This method is similar to [`Index::index`] for slices, but it returns a /// [`Range`] equivalent to `range`. You can use this method to turn any range /// into `start` and `end` values. /// -/// `bounds` is the range of the slice to use for bounds-checking. It should +/// `bounds` is the range of the slice to use for bounds checking. It should /// be a [`RangeTo`] range that ends at the length of the slice. /// /// The returned [`Range`] is safe to pass to [`slice::get_unchecked`] and @@ -898,7 +899,7 @@ where ops::Range { start, end } } -/// Performs bounds-checking of a range without panicking. +/// Performs bounds checking of a range without panicking. /// /// This is a version of [`range()`] that returns [`None`] instead of panicking. /// @@ -951,7 +952,8 @@ where if start > end || end > len { None } else { Some(ops::Range { start, end }) } } -/// Convert pair of `ops::Bound`s into `ops::Range` without performing any bounds checking and (in debug) overflow checking +/// Converts a pair of `ops::Bound`s into `ops::Range` without performing any +/// bounds checking or (in debug) overflow checking. pub(crate) fn into_range_unchecked( len: usize, (start, end): (ops::Bound, ops::Bound), @@ -970,7 +972,7 @@ pub(crate) fn into_range_unchecked( start..end } -/// Convert pair of `ops::Bound`s into `ops::Range`. +/// Converts pair of `ops::Bound`s into `ops::Range`. /// Returns `None` on overflowing indices. pub(crate) fn into_range( len: usize, @@ -995,7 +997,7 @@ pub(crate) fn into_range( Some(start..end) } -/// Convert pair of `ops::Bound`s into `ops::Range`. +/// Converts pair of `ops::Bound`s into `ops::Range`. /// Panics on overflowing indices. pub(crate) fn into_slice_range( len: usize, diff --git a/core/src/slice/iter.rs b/core/src/slice/iter.rs index 504676ce187a8..62b170a87d445 100644 --- a/core/src/slice/iter.rs +++ b/core/src/slice/iter.rs @@ -3,8 +3,7 @@ #[macro_use] // import iterator! and forward_iterator! mod macros; -use crate::cmp; -use crate::fmt; +use super::{from_raw_parts, from_raw_parts_mut}; use crate::hint::assert_unchecked; use crate::iter::{ FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, UncheckedIterator, @@ -13,8 +12,7 @@ use crate::marker::PhantomData; use crate::mem::{self, SizedTypeProperties}; use crate::num::NonZero; use crate::ptr::{self, without_provenance, without_provenance_mut, NonNull}; - -use super::{from_raw_parts, from_raw_parts_mut}; +use crate::{cmp, fmt}; #[stable(feature = "boxed_slice_into_iter", since = "1.80.0")] impl !Iterator for [T] {} diff --git a/core/src/slice/mod.rs b/core/src/slice/mod.rs index 68508e85f8e14..b1440214d795a 100644 --- a/core/src/slice/mod.rs +++ b/core/src/slice/mod.rs @@ -7,16 +7,13 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::cmp::Ordering::{self, Equal, Greater, Less}; -use crate::fmt; -use crate::hint; -use crate::intrinsics::{exact_div, unchecked_sub}; +use crate::intrinsics::{exact_div, select_unpredictable, unchecked_sub}; use crate::mem::{self, SizedTypeProperties}; use crate::num::NonZero; use crate::ops::{Bound, OneSidedRange, Range, RangeBounds}; -use crate::ptr; use crate::simd::{self, Simd}; -use crate::slice; use crate::ub_checks::assert_unsafe_precondition; +use crate::{fmt, hint, ptr, slice}; #[unstable( feature = "slice_internals", @@ -44,52 +41,38 @@ mod specialize; #[unstable(feature = "str_internals", issue = "none")] #[doc(hidden)] pub use ascii::is_ascii_simple; - +#[stable(feature = "inherent_ascii_escape", since = "1.60.0")] +pub use ascii::EscapeAscii; +#[stable(feature = "slice_get_slice", since = "1.28.0")] +pub use index::SliceIndex; +#[unstable(feature = "slice_range", issue = "76393")] +pub use index::{range, try_range}; +#[unstable(feature = "array_windows", issue = "75027")] +pub use iter::ArrayWindows; +#[unstable(feature = "array_chunks", issue = "74985")] +pub use iter::{ArrayChunks, ArrayChunksMut}; +#[stable(feature = "slice_group_by", since = "1.77.0")] +pub use iter::{ChunkBy, ChunkByMut}; #[stable(feature = "rust1", since = "1.0.0")] pub use iter::{Chunks, ChunksMut, Windows}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use iter::{Iter, IterMut}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut}; - -#[stable(feature = "slice_rsplit", since = "1.27.0")] -pub use iter::{RSplit, RSplitMut}; - #[stable(feature = "chunks_exact", since = "1.31.0")] pub use iter::{ChunksExact, ChunksExactMut}; - +#[stable(feature = "rust1", since = "1.0.0")] +pub use iter::{Iter, IterMut}; #[stable(feature = "rchunks", since = "1.31.0")] pub use iter::{RChunks, RChunksExact, RChunksExactMut, RChunksMut}; - -#[unstable(feature = "array_chunks", issue = "74985")] -pub use iter::{ArrayChunks, ArrayChunksMut}; - -#[unstable(feature = "array_windows", issue = "75027")] -pub use iter::ArrayWindows; - -#[stable(feature = "slice_group_by", since = "1.77.0")] -pub use iter::{ChunkBy, ChunkByMut}; - +#[stable(feature = "slice_rsplit", since = "1.27.0")] +pub use iter::{RSplit, RSplitMut}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut}; #[stable(feature = "split_inclusive", since = "1.51.0")] pub use iter::{SplitInclusive, SplitInclusiveMut}; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use raw::{from_raw_parts, from_raw_parts_mut}; - #[stable(feature = "from_ref", since = "1.28.0")] pub use raw::{from_mut, from_ref}; - #[unstable(feature = "slice_from_ptr_range", issue = "89792")] pub use raw::{from_mut_ptr_range, from_ptr_range}; - -#[stable(feature = "slice_get_slice", since = "1.28.0")] -pub use index::SliceIndex; - -#[unstable(feature = "slice_range", issue = "76393")] -pub use index::{range, try_range}; - -#[stable(feature = "inherent_ascii_escape", since = "1.60.0")] -pub use ascii::EscapeAscii; +#[stable(feature = "rust1", since = "1.0.0")] +pub use raw::{from_raw_parts, from_raw_parts_mut}; /// Calculates the direction and split point of a one-sided range. /// @@ -321,7 +304,7 @@ impl [T] { if let [.., last] = self { Some(last) } else { None } } - /// Return an array reference to the first `N` items in the slice. + /// Returns an array reference to the first `N` items in the slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -350,7 +333,7 @@ impl [T] { } } - /// Return a mutable array reference to the first `N` items in the slice. + /// Returns a mutable array reference to the first `N` items in the slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -381,7 +364,7 @@ impl [T] { } } - /// Return an array reference to the first `N` items in the slice and the remaining slice. + /// Returns an array reference to the first `N` items in the slice and the remaining slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -413,7 +396,7 @@ impl [T] { } } - /// Return a mutable array reference to the first `N` items in the slice and the remaining + /// Returns a mutable array reference to the first `N` items in the slice and the remaining /// slice. /// /// If the slice is not at least `N` in length, this will return `None`. @@ -451,7 +434,7 @@ impl [T] { } } - /// Return an array reference to the last `N` items in the slice and the remaining slice. + /// Returns an array reference to the last `N` items in the slice and the remaining slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -483,7 +466,7 @@ impl [T] { } } - /// Return a mutable array reference to the last `N` items in the slice and the remaining + /// Returns a mutable array reference to the last `N` items in the slice and the remaining /// slice. /// /// If the slice is not at least `N` in length, this will return `None`. @@ -521,7 +504,7 @@ impl [T] { } } - /// Return an array reference to the last `N` items in the slice. + /// Returns an array reference to the last `N` items in the slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -539,7 +522,7 @@ impl [T] { /// ``` #[inline] #[stable(feature = "slice_first_last_chunk", since = "1.77.0")] - #[rustc_const_stable(feature = "slice_first_last_chunk", since = "1.77.0")] + #[rustc_const_stable(feature = "const_slice_last_chunk", since = "1.80.0")] pub const fn last_chunk(&self) -> Option<&[T; N]> { if self.len() < N { None @@ -554,7 +537,7 @@ impl [T] { } } - /// Return a mutable array reference to the last `N` items in the slice. + /// Returns a mutable array reference to the last `N` items in the slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -726,7 +709,7 @@ impl [T] { /// Returns a raw pointer to the slice's buffer. /// /// The caller must ensure that the slice outlives the pointer this - /// function returns, or else it will end up pointing to garbage. + /// function returns, or else it will end up dangling. /// /// The caller must also ensure that the memory the pointer (non-transitively) points to /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer @@ -761,7 +744,7 @@ impl [T] { /// Returns an unsafe mutable pointer to the slice's buffer. /// /// The caller must ensure that the slice outlives the pointer this - /// function returns, or else it will end up pointing to garbage. + /// function returns, or else it will end up dangling. /// /// Modifying the container referenced by this slice may cause its buffer /// to be reallocated, which would also make any pointers to it invalid. @@ -828,7 +811,7 @@ impl [T] { // - Both pointers are part of the same object, as pointing directly // past the object also counts. // - // - The size of the slice is never larger than isize::MAX bytes, as + // - The size of the slice is never larger than `isize::MAX` bytes, as // noted here: // - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447 // - https://doc.rust-lang.org/reference/behavior-considered-undefined.html @@ -839,7 +822,7 @@ impl [T] { // - There is no wrapping around involved, as slices do not wrap past // the end of the address space. // - // See the documentation of pointer::add. + // See the documentation of [`pointer::add`]. let end = unsafe { start.add(self.len()) }; start..end } @@ -2787,41 +2770,54 @@ impl [T] { where F: FnMut(&'a T) -> Ordering, { - // INVARIANTS: - // - 0 <= left <= left + size = right <= self.len() - // - f returns Less for everything in self[..left] - // - f returns Greater for everything in self[right..] let mut size = self.len(); - let mut left = 0; - let mut right = size; - while left < right { - let mid = left + size / 2; - - // SAFETY: the while condition means `size` is strictly positive, so - // `size/2 < size`. Thus `left + size/2 < left + size`, which - // coupled with the `left + size <= self.len()` invariant means - // we have `left + size/2 < self.len()`, and this is in-bounds. + if size == 0 { + return Err(0); + } + let mut base = 0usize; + + // This loop intentionally doesn't have an early exit if the comparison + // returns Equal. We want the number of loop iterations to depend *only* + // on the size of the input slice so that the CPU can reliably predict + // the loop count. + while size > 1 { + let half = size / 2; + let mid = base + half; + + // SAFETY: the call is made safe by the following inconstants: + // - `mid >= 0`: by definition + // - `mid < size`: `mid = size / 2 + size / 4 + size / 8 ...` let cmp = f(unsafe { self.get_unchecked(mid) }); - // This control flow produces conditional moves, which results in - // fewer branches and instructions than if/else or matching on - // cmp::Ordering. - // This is x86 asm for u8: https://rust.godbolt.org/z/698eYffTx. - left = if cmp == Less { mid + 1 } else { left }; - right = if cmp == Greater { mid } else { right }; - if cmp == Equal { - // SAFETY: same as the `get_unchecked` above - unsafe { hint::assert_unchecked(mid < self.len()) }; - return Ok(mid); - } - - size = right - left; + // Binary search interacts poorly with branch prediction, so force + // the compiler to use conditional moves if supported by the target + // architecture. + base = select_unpredictable(cmp == Greater, base, mid); + + // This is imprecise in the case where `size` is odd and the + // comparison returns Greater: the mid element still gets included + // by `size` even though it's known to be larger than the element + // being searched for. + // + // This is fine though: we gain more performance by keeping the + // loop iteration count invariant (and thus predictable) than we + // lose from considering one additional element. + size -= half; } - // SAFETY: directly true from the overall invariant. - // Note that this is `<=`, unlike the assume in the `Ok` path. - unsafe { hint::assert_unchecked(left <= self.len()) }; - Err(left) + // SAFETY: base is always in [0, size) because base <= mid. + let cmp = f(unsafe { self.get_unchecked(base) }); + if cmp == Equal { + // SAFETY: same as the `get_unchecked` above. + unsafe { hint::assert_unchecked(base < self.len()) }; + Ok(base) + } else { + let result = base + (cmp == Less) as usize; + // SAFETY: same as the `get_unchecked` above. + // Note that this is `<=`, unlike the assume in the `Ok` path. + unsafe { hint::assert_unchecked(result <= self.len()) }; + Err(result) + } } /// Binary searches this slice with a key extraction function. @@ -3021,7 +3017,7 @@ impl [T] { sort::unstable::sort(self, &mut |a, b| f(a).lt(&f(b))); } - /// Reorder the slice such that the element at `index` after the reordering is at its final + /// Reorders the slice such that the element at `index` after the reordering is at its final /// sorted position. /// /// This reordering has the additional property that any value at position `i < index` will be @@ -3082,7 +3078,7 @@ impl [T] { sort::select::partition_at_index(self, index, T::lt) } - /// Reorder the slice with a comparator function such that the element at `index` after the + /// Reorders the slice with a comparator function such that the element at `index` after the /// reordering is at its final sorted position. /// /// This reordering has the additional property that any value at position `i < index` will be @@ -3147,7 +3143,7 @@ impl [T] { sort::select::partition_at_index(self, index, |a: &T, b: &T| compare(a, b) == Less) } - /// Reorder the slice with a key extraction function such that the element at `index` after the + /// Reorders the slice with a key extraction function such that the element at `index` after the /// reordering is at its final sorted position. /// /// This reordering has the additional property that any value at position `i < index` will be @@ -3405,8 +3401,10 @@ impl [T] { /// Rotates the slice in-place such that the first `mid` elements of the /// slice move to the end while the last `self.len() - mid` elements move to - /// the front. After calling `rotate_left`, the element previously at index - /// `mid` will become the first element in the slice. + /// the front. + /// + /// After calling `rotate_left`, the element previously at index `mid` will + /// become the first element in the slice. /// /// # Panics /// @@ -3448,8 +3446,10 @@ impl [T] { /// Rotates the slice in-place such that the first `self.len() - k` /// elements of the slice move to the end while the last `k` elements move - /// to the front. After calling `rotate_right`, the element previously at - /// index `self.len() - k` will become the first element in the slice. + /// to the front. + /// + /// After calling `rotate_right`, the element previously at index + /// `self.len() - k` will become the first element in the slice. /// /// # Panics /// @@ -3819,7 +3819,7 @@ impl [T] { (us_len, ts_len) } - /// Transmute the slice to a slice of another type, ensuring alignment of the types is + /// Transmutes the slice to a slice of another type, ensuring alignment of the types is /// maintained. /// /// This method splits the slice into three distinct slices: prefix, correctly aligned middle @@ -3884,7 +3884,7 @@ impl [T] { } } - /// Transmute the mutable slice to a mutable slice of another type, ensuring alignment of the + /// Transmutes the mutable slice to a mutable slice of another type, ensuring alignment of the /// types is maintained. /// /// This method splits the slice into three distinct slices: prefix, correctly aligned middle @@ -3957,7 +3957,7 @@ impl [T] { } } - /// Split a slice into a prefix, a middle of aligned SIMD types, and a suffix. + /// Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix. /// /// This is a safe wrapper around [`slice::align_to`], so inherits the same /// guarantees as that method. @@ -4021,7 +4021,7 @@ impl [T] { unsafe { self.align_to() } } - /// Split a mutable slice into a mutable prefix, a middle of aligned SIMD types, + /// Splits a mutable slice into a mutable prefix, a middle of aligned SIMD types, /// and a mutable suffix. /// /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same @@ -4069,7 +4069,6 @@ impl [T] { /// # Examples /// /// ``` - /// #![feature(is_sorted)] /// let empty: [i32; 0] = []; /// /// assert!([1, 2, 2, 9].is_sorted()); @@ -4079,7 +4078,7 @@ impl [T] { /// assert!(![0.0, 1.0, f32::NAN].is_sorted()); /// ``` #[inline] - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn is_sorted(&self) -> bool where @@ -4096,8 +4095,6 @@ impl [T] { /// # Examples /// /// ``` - /// #![feature(is_sorted)] - /// /// assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b)); /// assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b)); /// @@ -4108,7 +4105,7 @@ impl [T] { /// assert!(empty.is_sorted_by(|a, b| false)); /// assert!(empty.is_sorted_by(|a, b| true)); /// ``` - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn is_sorted_by<'a, F>(&'a self, mut compare: F) -> bool where @@ -4128,13 +4125,11 @@ impl [T] { /// # Examples /// /// ``` - /// #![feature(is_sorted)] - /// /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len())); /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs())); /// ``` #[inline] - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool where @@ -4522,6 +4517,121 @@ impl [T] { // are disjunct and in bounds. unsafe { Ok(self.get_many_unchecked_mut(indices)) } } + + /// Returns the index that an element reference points to. + /// + /// Returns `None` if `element` does not point within the slice or if it points between elements. + /// + /// This method is useful for extending slice iterators like [`slice::split`]. + /// + /// Note that this uses pointer arithmetic and **does not compare elements**. + /// To find the index of an element via comparison, use + /// [`.iter().position()`](crate::iter::Iterator::position) instead. + /// + /// # Panics + /// Panics if `T` is zero-sized. + /// + /// # Examples + /// Basic usage: + /// ``` + /// #![feature(substr_range)] + /// + /// let nums: &[u32] = &[1, 7, 1, 1]; + /// let num = &nums[2]; + /// + /// assert_eq!(num, &1); + /// assert_eq!(nums.elem_offset(num), Some(2)); + /// ``` + /// Returning `None` with an in-between element: + /// ``` + /// #![feature(substr_range)] + /// + /// let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; + /// let flat_arr: &[u32] = arr.as_flattened(); + /// + /// let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); + /// let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); + /// + /// assert_eq!(ok_elm, &[0, 1]); + /// assert_eq!(weird_elm, &[1, 2]); + /// + /// assert_eq!(arr.elem_offset(ok_elm), Some(0)); // Points to element 0 + /// assert_eq!(arr.elem_offset(weird_elm), None); // Points between element 0 and 1 + /// ``` + #[must_use] + #[unstable(feature = "substr_range", issue = "126769")] + pub fn elem_offset(&self, element: &T) -> Option { + if T::IS_ZST { + panic!("elements are zero-sized"); + } + + let self_start = self.as_ptr() as usize; + let elem_start = element as *const T as usize; + + let byte_offset = elem_start.wrapping_sub(self_start); + + if byte_offset % mem::size_of::() != 0 { + return None; + } + + let offset = byte_offset / mem::size_of::(); + + if offset < self.len() { Some(offset) } else { None } + } + + /// Returns the range of indices that a subslice points to. + /// + /// Returns `None` if `subslice` does not point within the slice or if it points between elements. + /// + /// This method **does not compare elements**. Instead, this method finds the location in the slice that + /// `subslice` was obtained from. To find the index of a subslice via comparison, instead use + /// [`.windows()`](slice::windows)[`.position()`](crate::iter::Iterator::position). + /// + /// This method is useful for extending slice iterators like [`slice::split`]. + /// + /// Note that this may return a false positive (either `Some(0..0)` or `Some(self.len()..self.len())`) + /// if `subslice` has a length of zero and points to the beginning or end of another, separate, slice. + /// + /// # Panics + /// Panics if `T` is zero-sized. + /// + /// # Examples + /// Basic usage: + /// ``` + /// #![feature(substr_range)] + /// + /// let nums = &[0, 5, 10, 0, 0, 5]; + /// + /// let mut iter = nums + /// .split(|t| *t == 0) + /// .map(|n| nums.subslice_range(n).unwrap()); + /// + /// assert_eq!(iter.next(), Some(0..0)); + /// assert_eq!(iter.next(), Some(1..3)); + /// assert_eq!(iter.next(), Some(4..4)); + /// assert_eq!(iter.next(), Some(5..6)); + /// ``` + #[must_use] + #[unstable(feature = "substr_range", issue = "126769")] + pub fn subslice_range(&self, subslice: &[T]) -> Option> { + if T::IS_ZST { + panic!("elements are zero-sized"); + } + + let self_start = self.as_ptr() as usize; + let subslice_start = subslice.as_ptr() as usize; + + let byte_start = subslice_start.wrapping_sub(self_start); + + if byte_start % core::mem::size_of::() != 0 { + return None; + } + + let start = byte_start / core::mem::size_of::(); + let end = start.wrapping_add(subslice.len()); + + if start <= self.len() && end <= self.len() { Some(start..end) } else { None } + } } impl [[T; N]] { diff --git a/core/src/slice/raw.rs b/core/src/slice/raw.rs index 280aead270e76..85507eb8a7381 100644 --- a/core/src/slice/raw.rs +++ b/core/src/slice/raw.rs @@ -1,9 +1,7 @@ //! Free functions to create `&[T]` and `&mut [T]`. -use crate::array; use crate::ops::Range; -use crate::ptr; -use crate::ub_checks; +use crate::{array, ptr, ub_checks}; /// Forms a slice from a pointer and a length. /// diff --git a/core/src/slice/rotate.rs b/core/src/slice/rotate.rs index 1d7b86339799b..1e4865a7caad9 100644 --- a/core/src/slice/rotate.rs +++ b/core/src/slice/rotate.rs @@ -1,6 +1,5 @@ -use crate::cmp; use crate::mem::{self, MaybeUninit, SizedTypeProperties}; -use crate::ptr; +use crate::{cmp, ptr}; /// Rotates the range `[mid-left, mid+right)` such that the element at `mid` becomes the first /// element. Equivalently, rotates the range `left` elements to the left or `right` elements to the diff --git a/core/src/slice/sort/select.rs b/core/src/slice/sort/select.rs index 6212def30416b..f6529f23bcb3f 100644 --- a/core/src/slice/sort/select.rs +++ b/core/src/slice/sort/select.rs @@ -7,12 +7,11 @@ //! better performance than one would get using heapsort as fallback. use crate::mem::{self, SizedTypeProperties}; - use crate::slice::sort::shared::pivot::choose_pivot; use crate::slice::sort::shared::smallsort::insertion_sort_shift_left; use crate::slice::sort::unstable::quicksort::partition; -/// Reorder the slice such that the element at `index` is at its final sorted position. +/// Reorders the slice such that the element at `index` is at its final sorted position. pub(crate) fn partition_at_index( v: &mut [T], index: usize, diff --git a/core/src/slice/sort/shared/smallsort.rs b/core/src/slice/sort/shared/smallsort.rs index 5111ed8756bf1..5064c5a0ae55a 100644 --- a/core/src/slice/sort/shared/smallsort.rs +++ b/core/src/slice/sort/shared/smallsort.rs @@ -1,11 +1,8 @@ //! This module contains a variety of sort implementations that are optimized for small lengths. -use crate::intrinsics; use crate::mem::{self, ManuallyDrop, MaybeUninit}; -use crate::ptr; -use crate::slice; - use crate::slice::sort::shared::FreezeMarker; +use crate::{intrinsics, ptr, slice}; // It's important to differentiate between SMALL_SORT_THRESHOLD performance for // small slices and small-sort performance sorting small sub-slices as part of diff --git a/core/src/slice/sort/stable/drift.rs b/core/src/slice/sort/stable/drift.rs index 2d9c4ac9fcf7c..644e75a4581e9 100644 --- a/core/src/slice/sort/stable/drift.rs +++ b/core/src/slice/sort/stable/drift.rs @@ -1,14 +1,12 @@ //! This module contains the hybrid top-level loop combining bottom-up Mergesort with top-down //! Quicksort. -use crate::cmp; -use crate::intrinsics; use crate::mem::MaybeUninit; - use crate::slice::sort::shared::find_existing_run; use crate::slice::sort::shared::smallsort::StableSmallSortTypeImpl; use crate::slice::sort::stable::merge::merge; use crate::slice::sort::stable::quicksort::quicksort; +use crate::{cmp, intrinsics}; /// Sorts `v` based on comparison function `is_less`. If `eager_sort` is true, /// it will only do small-sorts and physical merges, ensuring O(N * log(N)) @@ -273,7 +271,7 @@ fn stable_quicksort bool>( } /// Compactly stores the length of a run, and whether or not it is sorted. This -/// can always fit in a usize because the maximum slice length is isize::MAX. +/// can always fit in a `usize` because the maximum slice length is [`isize::MAX`]. #[derive(Copy, Clone)] struct DriftsortRun(usize); diff --git a/core/src/slice/sort/stable/merge.rs b/core/src/slice/sort/stable/merge.rs index 6739e114b130a..0cb21740795b7 100644 --- a/core/src/slice/sort/stable/merge.rs +++ b/core/src/slice/sort/stable/merge.rs @@ -1,8 +1,7 @@ //! This module contains logic for performing a merge of two sorted sub-slices. -use crate::cmp; use crate::mem::MaybeUninit; -use crate::ptr; +use crate::{cmp, ptr}; /// Merges non-decreasing runs `v[..mid]` and `v[mid..]` using `scratch` as /// temporary storage, and stores the result into `v[..]`. diff --git a/core/src/slice/sort/stable/mod.rs b/core/src/slice/sort/stable/mod.rs index 18f7b2ac54af5..a383b0f589ccf 100644 --- a/core/src/slice/sort/stable/mod.rs +++ b/core/src/slice/sort/stable/mod.rs @@ -1,12 +1,10 @@ //! This module contains the entry points for `slice::sort`. -use crate::cmp; -use crate::intrinsics; use crate::mem::{self, MaybeUninit, SizedTypeProperties}; - use crate::slice::sort::shared::smallsort::{ insertion_sort_shift_left, StableSmallSortTypeImpl, SMALL_SORT_GENERAL_SCRATCH_LEN, }; +use crate::{cmp, intrinsics}; pub(crate) mod drift; pub(crate) mod merge; diff --git a/core/src/slice/sort/stable/quicksort.rs b/core/src/slice/sort/stable/quicksort.rs index 181fe603d2325..3319d67ab52fa 100644 --- a/core/src/slice/sort/stable/quicksort.rs +++ b/core/src/slice/sort/stable/quicksort.rs @@ -1,12 +1,10 @@ //! This module contains a stable quicksort and partition implementation. -use crate::intrinsics; use crate::mem::{self, ManuallyDrop, MaybeUninit}; -use crate::ptr; - use crate::slice::sort::shared::pivot::choose_pivot; use crate::slice::sort::shared::smallsort::StableSmallSortTypeImpl; use crate::slice::sort::shared::FreezeMarker; +use crate::{intrinsics, ptr}; /// Sorts `v` recursively using quicksort. /// @@ -196,7 +194,8 @@ struct PartitionState { impl PartitionState { /// # Safety - /// scan and scratch must point to valid disjoint buffers of length len. The + /// + /// `scan` and `scratch` must point to valid disjoint buffers of length `len`. The /// scan buffer must be initialized. unsafe fn new(scan: *const T, scratch: *mut T, len: usize) -> Self { // SAFETY: See function safety comment. @@ -208,6 +207,7 @@ impl PartitionState { /// branchless core of the partition. /// /// # Safety + /// /// This function may be called at most `len` times. If it is called exactly /// `len` times the scratch buffer then contains a copy of each element from /// the scan buffer exactly once - a permutation, and num_left <= len. diff --git a/core/src/slice/sort/unstable/heapsort.rs b/core/src/slice/sort/unstable/heapsort.rs index 559605ef4b6b3..27e2ad588ea09 100644 --- a/core/src/slice/sort/unstable/heapsort.rs +++ b/core/src/slice/sort/unstable/heapsort.rs @@ -1,7 +1,6 @@ //! This module contains a branchless heapsort as fallback for unstable quicksort. -use crate::intrinsics; -use crate::ptr; +use crate::{intrinsics, ptr}; /// Sorts `v` using heapsort, which guarantees *O*(*n* \* log(*n*)) worst-case. /// diff --git a/core/src/slice/sort/unstable/mod.rs b/core/src/slice/sort/unstable/mod.rs index 692c2d8f7c7ba..ed735e1ebfbc0 100644 --- a/core/src/slice/sort/unstable/mod.rs +++ b/core/src/slice/sort/unstable/mod.rs @@ -2,7 +2,6 @@ use crate::intrinsics; use crate::mem::SizedTypeProperties; - use crate::slice::sort::shared::find_existing_run; use crate::slice::sort::shared::smallsort::insertion_sort_shift_left; diff --git a/core/src/slice/sort/unstable/quicksort.rs b/core/src/slice/sort/unstable/quicksort.rs index 533b5b0eec767..cd53656e9b4b8 100644 --- a/core/src/slice/sort/unstable/quicksort.rs +++ b/core/src/slice/sort/unstable/quicksort.rs @@ -1,11 +1,9 @@ //! This module contains an unstable quicksort and two partition implementations. -use crate::intrinsics; use crate::mem::{self, ManuallyDrop}; -use crate::ptr; - use crate::slice::sort::shared::pivot::choose_pivot; use crate::slice::sort::shared::smallsort::UnstableSmallSortTypeImpl; +use crate::{intrinsics, ptr}; /// Sorts `v` recursively. /// diff --git a/core/src/str/converts.rs b/core/src/str/converts.rs index 397759bd5cae7..1956a04829d1d 100644 --- a/core/src/str/converts.rs +++ b/core/src/str/converts.rs @@ -1,9 +1,8 @@ //! Ways to create a `str` from bytes slice. -use crate::{mem, ptr}; - use super::validations::run_utf8_validation; use super::Utf8Error; +use crate::{mem, ptr}; /// Converts a slice of bytes to a string slice. /// @@ -206,7 +205,7 @@ pub const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str { unsafe { &mut *(v as *mut [u8] as *mut str) } } -/// Creates an `&str` from a pointer and a length. +/// Creates a `&str` from a pointer and a length. /// /// The pointed-to bytes must be valid UTF-8. /// If this might not be the case, use `str::from_utf8(slice::from_raw_parts(ptr, len))`, @@ -225,7 +224,7 @@ pub const unsafe fn from_raw_parts<'a>(ptr: *const u8, len: usize) -> &'a str { unsafe { &*ptr::from_raw_parts(ptr, len) } } -/// Creates an `&mut str` from a pointer and a length. +/// Creates a `&mut str` from a pointer and a length. /// /// The pointed-to bytes must be valid UTF-8. /// If this might not be the case, use `str::from_utf8_mut(slice::from_raw_parts_mut(ptr, len))`, diff --git a/core/src/str/iter.rs b/core/src/str/iter.rs index 19627f28e64f8..06f796f9f3ad8 100644 --- a/core/src/str/iter.rs +++ b/core/src/str/iter.rs @@ -1,23 +1,20 @@ //! Iterators for `str` methods. -use crate::char as char_mod; +use super::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher}; +use super::validations::{next_code_point, next_code_point_reverse}; +use super::{ + from_utf8_unchecked, BytesIsNotEmpty, CharEscapeDebugContinue, CharEscapeDefault, + CharEscapeUnicode, IsAsciiWhitespace, IsNotEmpty, IsWhitespace, LinesMap, UnsafeBytesToStr, +}; use crate::fmt::{self, Write}; -use crate::iter::{Chain, FlatMap, Flatten}; -use crate::iter::{Copied, Filter, FusedIterator, Map, TrustedLen}; -use crate::iter::{TrustedRandomAccess, TrustedRandomAccessNoCoerce}; +use crate::iter::{ + Chain, Copied, Filter, FlatMap, Flatten, FusedIterator, Map, TrustedLen, TrustedRandomAccess, + TrustedRandomAccessNoCoerce, +}; use crate::num::NonZero; use crate::ops::Try; -use crate::option; use crate::slice::{self, Split as SliceSplit}; - -use super::from_utf8_unchecked; -use super::pattern::Pattern; -use super::pattern::{DoubleEndedSearcher, ReverseSearcher, Searcher}; -use super::validations::{next_code_point, next_code_point_reverse}; -use super::LinesMap; -use super::{BytesIsNotEmpty, UnsafeBytesToStr}; -use super::{CharEscapeDebugContinue, CharEscapeDefault, CharEscapeUnicode}; -use super::{IsAsciiWhitespace, IsNotEmpty, IsWhitespace}; +use crate::{char as char_mod, option}; /// An iterator over the [`char`]s of a string slice. /// @@ -411,7 +408,7 @@ macro_rules! derive_pattern_clone { (clone $t:ident with |$s:ident| $e:expr) => { impl<'a, P> Clone for $t<'a, P> where - P: Pattern<'a, Searcher: Clone>, + P: Pattern: Clone>, { fn clone(&self) -> Self { let $s = self; @@ -424,7 +421,7 @@ macro_rules! derive_pattern_clone { /// This macro generates two public iterator structs /// wrapping a private internal one that makes use of the `Pattern` API. /// -/// For all patterns `P: Pattern<'a>` the following items will be +/// For all patterns `P: Pattern` the following items will be /// generated (generics omitted): /// /// struct $forward_iterator($internal_iterator); @@ -484,12 +481,12 @@ macro_rules! generate_pattern_iterators { } => { $(#[$forward_iterator_attribute])* $(#[$common_stability_attribute])* - pub struct $forward_iterator<'a, P: Pattern<'a>>(pub(super) $internal_iterator<'a, P>); + pub struct $forward_iterator<'a, P: Pattern>(pub(super) $internal_iterator<'a, P>); $(#[$common_stability_attribute])* impl<'a, P> fmt::Debug for $forward_iterator<'a, P> where - P: Pattern<'a, Searcher: fmt::Debug>, + P: Pattern: fmt::Debug>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple(stringify!($forward_iterator)) @@ -499,7 +496,7 @@ macro_rules! generate_pattern_iterators { } $(#[$common_stability_attribute])* - impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> { + impl<'a, P: Pattern> Iterator for $forward_iterator<'a, P> { type Item = $iterty; #[inline] @@ -511,7 +508,7 @@ macro_rules! generate_pattern_iterators { $(#[$common_stability_attribute])* impl<'a, P> Clone for $forward_iterator<'a, P> where - P: Pattern<'a, Searcher: Clone>, + P: Pattern: Clone>, { fn clone(&self) -> Self { $forward_iterator(self.0.clone()) @@ -520,12 +517,12 @@ macro_rules! generate_pattern_iterators { $(#[$reverse_iterator_attribute])* $(#[$common_stability_attribute])* - pub struct $reverse_iterator<'a, P: Pattern<'a>>(pub(super) $internal_iterator<'a, P>); + pub struct $reverse_iterator<'a, P: Pattern>(pub(super) $internal_iterator<'a, P>); $(#[$common_stability_attribute])* impl<'a, P> fmt::Debug for $reverse_iterator<'a, P> where - P: Pattern<'a, Searcher: fmt::Debug>, + P: Pattern: fmt::Debug>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple(stringify!($reverse_iterator)) @@ -537,7 +534,7 @@ macro_rules! generate_pattern_iterators { $(#[$common_stability_attribute])* impl<'a, P> Iterator for $reverse_iterator<'a, P> where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + P: Pattern: ReverseSearcher<'a>>, { type Item = $iterty; @@ -550,7 +547,7 @@ macro_rules! generate_pattern_iterators { $(#[$common_stability_attribute])* impl<'a, P> Clone for $reverse_iterator<'a, P> where - P: Pattern<'a, Searcher: Clone>, + P: Pattern: Clone>, { fn clone(&self) -> Self { $reverse_iterator(self.0.clone()) @@ -558,12 +555,12 @@ macro_rules! generate_pattern_iterators { } #[stable(feature = "fused", since = "1.26.0")] - impl<'a, P: Pattern<'a>> FusedIterator for $forward_iterator<'a, P> {} + impl<'a, P: Pattern> FusedIterator for $forward_iterator<'a, P> {} #[stable(feature = "fused", since = "1.26.0")] impl<'a, P> FusedIterator for $reverse_iterator<'a, P> where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + P: Pattern: ReverseSearcher<'a>>, {} generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*, @@ -578,7 +575,7 @@ macro_rules! generate_pattern_iterators { $(#[$common_stability_attribute])* impl<'a, P> DoubleEndedIterator for $forward_iterator<'a, P> where - P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>, + P: Pattern: DoubleEndedSearcher<'a>>, { #[inline] fn next_back(&mut self) -> Option<$iterty> { @@ -589,7 +586,7 @@ macro_rules! generate_pattern_iterators { $(#[$common_stability_attribute])* impl<'a, P> DoubleEndedIterator for $reverse_iterator<'a, P> where - P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>, + P: Pattern: DoubleEndedSearcher<'a>>, { #[inline] fn next_back(&mut self) -> Option<$iterty> { @@ -609,17 +606,17 @@ derive_pattern_clone! { with |s| SplitInternal { matcher: s.matcher.clone(), ..*s } } -pub(super) struct SplitInternal<'a, P: Pattern<'a>> { +pub(super) struct SplitInternal<'a, P: Pattern> { pub(super) start: usize, pub(super) end: usize, - pub(super) matcher: P::Searcher, + pub(super) matcher: P::Searcher<'a>, pub(super) allow_trailing_empty: bool, pub(super) finished: bool, } impl<'a, P> fmt::Debug for SplitInternal<'a, P> where - P: Pattern<'a, Searcher: fmt::Debug>, + P: Pattern: fmt::Debug>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SplitInternal") @@ -632,7 +629,7 @@ where } } -impl<'a, P: Pattern<'a>> SplitInternal<'a, P> { +impl<'a, P: Pattern> SplitInternal<'a, P> { #[inline] fn get_end(&mut self) -> Option<&'a str> { if !self.finished { @@ -689,7 +686,7 @@ impl<'a, P: Pattern<'a>> SplitInternal<'a, P> { #[inline] fn next_back(&mut self) -> Option<&'a str> where - P::Searcher: ReverseSearcher<'a>, + P::Searcher<'a>: ReverseSearcher<'a>, { if self.finished { return None; @@ -726,7 +723,7 @@ impl<'a, P: Pattern<'a>> SplitInternal<'a, P> { #[inline] fn next_back_inclusive(&mut self) -> Option<&'a str> where - P::Searcher: ReverseSearcher<'a>, + P::Searcher<'a>: ReverseSearcher<'a>, { if self.finished { return None; @@ -796,7 +793,7 @@ generate_pattern_iterators! { delegate double ended; } -impl<'a, P: Pattern<'a>> Split<'a, P> { +impl<'a, P: Pattern> Split<'a, P> { /// Returns remainder of the split string. /// /// If the iterator is empty, returns `None`. @@ -819,7 +816,7 @@ impl<'a, P: Pattern<'a>> Split<'a, P> { } } -impl<'a, P: Pattern<'a>> RSplit<'a, P> { +impl<'a, P: Pattern> RSplit<'a, P> { /// Returns remainder of the split string. /// /// If the iterator is empty, returns `None`. @@ -860,7 +857,7 @@ generate_pattern_iterators! { delegate double ended; } -impl<'a, P: Pattern<'a>> SplitTerminator<'a, P> { +impl<'a, P: Pattern> SplitTerminator<'a, P> { /// Returns remainder of the split string. /// /// If the iterator is empty, returns `None`. @@ -883,7 +880,7 @@ impl<'a, P: Pattern<'a>> SplitTerminator<'a, P> { } } -impl<'a, P: Pattern<'a>> RSplitTerminator<'a, P> { +impl<'a, P: Pattern> RSplitTerminator<'a, P> { /// Returns remainder of the split string. /// /// If the iterator is empty, returns `None`. @@ -911,7 +908,7 @@ derive_pattern_clone! { with |s| SplitNInternal { iter: s.iter.clone(), ..*s } } -pub(super) struct SplitNInternal<'a, P: Pattern<'a>> { +pub(super) struct SplitNInternal<'a, P: Pattern> { pub(super) iter: SplitInternal<'a, P>, /// The number of splits remaining pub(super) count: usize, @@ -919,7 +916,7 @@ pub(super) struct SplitNInternal<'a, P: Pattern<'a>> { impl<'a, P> fmt::Debug for SplitNInternal<'a, P> where - P: Pattern<'a, Searcher: fmt::Debug>, + P: Pattern: fmt::Debug>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SplitNInternal") @@ -929,7 +926,7 @@ where } } -impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> { +impl<'a, P: Pattern> SplitNInternal<'a, P> { #[inline] fn next(&mut self) -> Option<&'a str> { match self.count { @@ -948,7 +945,7 @@ impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> { #[inline] fn next_back(&mut self) -> Option<&'a str> where - P::Searcher: ReverseSearcher<'a>, + P::Searcher<'a>: ReverseSearcher<'a>, { match self.count { 0 => None, @@ -987,7 +984,7 @@ generate_pattern_iterators! { delegate single ended; } -impl<'a, P: Pattern<'a>> SplitN<'a, P> { +impl<'a, P: Pattern> SplitN<'a, P> { /// Returns remainder of the split string. /// /// If the iterator is empty, returns `None`. @@ -1010,7 +1007,7 @@ impl<'a, P: Pattern<'a>> SplitN<'a, P> { } } -impl<'a, P: Pattern<'a>> RSplitN<'a, P> { +impl<'a, P: Pattern> RSplitN<'a, P> { /// Returns remainder of the split string. /// /// If the iterator is empty, returns `None`. @@ -1038,18 +1035,18 @@ derive_pattern_clone! { with |s| MatchIndicesInternal(s.0.clone()) } -pub(super) struct MatchIndicesInternal<'a, P: Pattern<'a>>(pub(super) P::Searcher); +pub(super) struct MatchIndicesInternal<'a, P: Pattern>(pub(super) P::Searcher<'a>); impl<'a, P> fmt::Debug for MatchIndicesInternal<'a, P> where - P: Pattern<'a, Searcher: fmt::Debug>, + P: Pattern: fmt::Debug>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("MatchIndicesInternal").field(&self.0).finish() } } -impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> { +impl<'a, P: Pattern> MatchIndicesInternal<'a, P> { #[inline] fn next(&mut self) -> Option<(usize, &'a str)> { self.0 @@ -1061,7 +1058,7 @@ impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> { #[inline] fn next_back(&mut self) -> Option<(usize, &'a str)> where - P::Searcher: ReverseSearcher<'a>, + P::Searcher<'a>: ReverseSearcher<'a>, { self.0 .next_match_back() @@ -1093,18 +1090,18 @@ derive_pattern_clone! { with |s| MatchesInternal(s.0.clone()) } -pub(super) struct MatchesInternal<'a, P: Pattern<'a>>(pub(super) P::Searcher); +pub(super) struct MatchesInternal<'a, P: Pattern>(pub(super) P::Searcher<'a>); impl<'a, P> fmt::Debug for MatchesInternal<'a, P> where - P: Pattern<'a, Searcher: fmt::Debug>, + P: Pattern: fmt::Debug>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("MatchesInternal").field(&self.0).finish() } } -impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> { +impl<'a, P: Pattern> MatchesInternal<'a, P> { #[inline] fn next(&mut self) -> Option<&'a str> { // SAFETY: `Searcher` guarantees that `start` and `end` lie on unicode boundaries. @@ -1117,7 +1114,7 @@ impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> { #[inline] fn next_back(&mut self) -> Option<&'a str> where - P::Searcher: ReverseSearcher<'a>, + P::Searcher<'a>: ReverseSearcher<'a>, { // SAFETY: `Searcher` guarantees that `start` and `end` lie on unicode boundaries. self.0.next_match_back().map(|(a, b)| unsafe { @@ -1288,7 +1285,7 @@ pub struct SplitAsciiWhitespace<'a> { /// /// [`split_inclusive`]: str::split_inclusive #[stable(feature = "split_inclusive", since = "1.51.0")] -pub struct SplitInclusive<'a, P: Pattern<'a>>(pub(super) SplitInternal<'a, P>); +pub struct SplitInclusive<'a, P: Pattern>(pub(super) SplitInternal<'a, P>); #[stable(feature = "split_whitespace", since = "1.1.0")] impl<'a> Iterator for SplitWhitespace<'a> { @@ -1410,7 +1407,7 @@ impl<'a> SplitAsciiWhitespace<'a> { } #[stable(feature = "split_inclusive", since = "1.51.0")] -impl<'a, P: Pattern<'a>> Iterator for SplitInclusive<'a, P> { +impl<'a, P: Pattern> Iterator for SplitInclusive<'a, P> { type Item = &'a str; #[inline] @@ -1420,7 +1417,7 @@ impl<'a, P: Pattern<'a>> Iterator for SplitInclusive<'a, P> { } #[stable(feature = "split_inclusive", since = "1.51.0")] -impl<'a, P: Pattern<'a, Searcher: fmt::Debug>> fmt::Debug for SplitInclusive<'a, P> { +impl<'a, P: Pattern: fmt::Debug>> fmt::Debug for SplitInclusive<'a, P> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SplitInclusive").field("0", &self.0).finish() } @@ -1428,14 +1425,14 @@ impl<'a, P: Pattern<'a, Searcher: fmt::Debug>> fmt::Debug for SplitInclusive<'a, // FIXME(#26925) Remove in favor of `#[derive(Clone)]` #[stable(feature = "split_inclusive", since = "1.51.0")] -impl<'a, P: Pattern<'a, Searcher: Clone>> Clone for SplitInclusive<'a, P> { +impl<'a, P: Pattern: Clone>> Clone for SplitInclusive<'a, P> { fn clone(&self) -> Self { SplitInclusive(self.0.clone()) } } #[stable(feature = "split_inclusive", since = "1.51.0")] -impl<'a, P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>> DoubleEndedIterator +impl<'a, P: Pattern: DoubleEndedSearcher<'a>>> DoubleEndedIterator for SplitInclusive<'a, P> { #[inline] @@ -1445,9 +1442,9 @@ impl<'a, P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>> DoubleEndedIterator } #[stable(feature = "split_inclusive", since = "1.51.0")] -impl<'a, P: Pattern<'a>> FusedIterator for SplitInclusive<'a, P> {} +impl<'a, P: Pattern> FusedIterator for SplitInclusive<'a, P> {} -impl<'a, P: Pattern<'a>> SplitInclusive<'a, P> { +impl<'a, P: Pattern> SplitInclusive<'a, P> { /// Returns remainder of the split string. /// /// If the iterator is empty, returns `None`. diff --git a/core/src/str/lossy.rs b/core/src/str/lossy.rs index 51a0777c2d613..3f31107acf050 100644 --- a/core/src/str/lossy.rs +++ b/core/src/str/lossy.rs @@ -1,10 +1,8 @@ -use crate::fmt; -use crate::fmt::Formatter; -use crate::fmt::Write; -use crate::iter::FusedIterator; - use super::from_utf8_unchecked; use super::validations::utf8_char_width; +use crate::fmt; +use crate::fmt::{Formatter, Write}; +use crate::iter::FusedIterator; impl [u8] { /// Creates an iterator over the contiguous valid UTF-8 ranges of this diff --git a/core/src/str/mod.rs b/core/src/str/mod.rs index 683109380439c..56517348dc7d2 100644 --- a/core/src/str/mod.rs +++ b/core/src/str/mod.rs @@ -13,73 +13,52 @@ mod iter; mod traits; mod validations; -use self::pattern::Pattern; -use self::pattern::{DoubleEndedSearcher, ReverseSearcher, Searcher}; - -use crate::ascii; +use self::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher}; use crate::char::{self, EscapeDebugExtArgs}; -use crate::mem; +use crate::ops::Range; use crate::slice::{self, SliceIndex}; +use crate::{ascii, mem}; pub mod pattern; mod lossy; -#[stable(feature = "utf8_chunks", since = "1.79.0")] -pub use lossy::{Utf8Chunk, Utf8Chunks}; - +#[unstable(feature = "str_from_raw_parts", issue = "119206")] +pub use converts::{from_raw_parts, from_raw_parts_mut}; #[stable(feature = "rust1", since = "1.0.0")] pub use converts::{from_utf8, from_utf8_unchecked}; - #[stable(feature = "str_mut_extras", since = "1.20.0")] pub use converts::{from_utf8_mut, from_utf8_unchecked_mut}; - -#[unstable(feature = "str_from_raw_parts", issue = "119206")] -pub use converts::{from_raw_parts, from_raw_parts_mut}; - #[stable(feature = "rust1", since = "1.0.0")] pub use error::{ParseBoolError, Utf8Error}; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use traits::FromStr; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use iter::{Bytes, CharIndices, Chars, Lines, SplitWhitespace}; - +#[stable(feature = "encode_utf16", since = "1.8.0")] +pub use iter::EncodeUtf16; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] pub use iter::LinesAny; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use iter::{RSplit, RSplitTerminator, Split, SplitTerminator}; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use iter::{RSplitN, SplitN}; - -#[stable(feature = "str_matches", since = "1.2.0")] -pub use iter::{Matches, RMatches}; - -#[stable(feature = "str_match_indices", since = "1.5.0")] -pub use iter::{MatchIndices, RMatchIndices}; - -#[stable(feature = "encode_utf16", since = "1.8.0")] -pub use iter::EncodeUtf16; - -#[stable(feature = "str_escape", since = "1.34.0")] -pub use iter::{EscapeDebug, EscapeDefault, EscapeUnicode}; - #[stable(feature = "split_ascii_whitespace", since = "1.34.0")] pub use iter::SplitAsciiWhitespace; - #[stable(feature = "split_inclusive", since = "1.51.0")] pub use iter::SplitInclusive; - +#[stable(feature = "rust1", since = "1.0.0")] +pub use iter::{Bytes, CharIndices, Chars, Lines, SplitWhitespace}; +#[stable(feature = "str_escape", since = "1.34.0")] +pub use iter::{EscapeDebug, EscapeDefault, EscapeUnicode}; +#[stable(feature = "str_match_indices", since = "1.5.0")] +pub use iter::{MatchIndices, RMatchIndices}; +use iter::{MatchIndicesInternal, MatchesInternal, SplitInternal, SplitNInternal}; +#[stable(feature = "str_matches", since = "1.2.0")] +pub use iter::{Matches, RMatches}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use iter::{RSplit, RSplitTerminator, Split, SplitTerminator}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use iter::{RSplitN, SplitN}; +#[stable(feature = "utf8_chunks", since = "1.79.0")] +pub use lossy::{Utf8Chunk, Utf8Chunks}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use traits::FromStr; #[unstable(feature = "str_internals", issue = "none")] pub use validations::{next_code_point, utf8_char_width}; -use iter::MatchIndicesInternal; -use iter::SplitInternal; -use iter::{MatchesInternal, SplitNInternal}; - #[inline(never)] #[cold] #[track_caller] @@ -591,6 +570,7 @@ impl str { /// Creates a string slice from another string slice, bypassing safety /// checks. + /// /// This is generally not recommended, use with caution! For a safe /// alternative see [`str`] and [`IndexMut`]. /// @@ -622,7 +602,7 @@ impl str { unsafe { &mut *(begin..end).get_unchecked_mut(self) } } - /// Divide one string slice into two at an index. + /// Divides one string slice into two at an index. /// /// The argument, `mid`, should be a byte offset from the start of the /// string. It must also be on the boundary of a UTF-8 code point. @@ -661,7 +641,7 @@ impl str { } } - /// Divide one mutable string slice into two at an index. + /// Divides one mutable string slice into two at an index. /// /// The argument, `mid`, should be a byte offset from the start of the /// string. It must also be on the boundary of a UTF-8 code point. @@ -704,7 +684,7 @@ impl str { } } - /// Divide one string slice into two at an index. + /// Divides one string slice into two at an index. /// /// The argument, `mid`, should be a valid byte offset from the start of the /// string. It must also be on the boundary of a UTF-8 code point. The @@ -743,7 +723,7 @@ impl str { } } - /// Divide one mutable string slice into two at an index. + /// Divides one mutable string slice into two at an index. /// /// The argument, `mid`, should be a valid byte offset from the start of the /// string. It must also be on the boundary of a UTF-8 code point. The @@ -783,7 +763,7 @@ impl str { } } - /// Divide one string slice into two at an index. + /// Divides one string slice into two at an index. /// /// # Safety /// @@ -911,7 +891,7 @@ impl str { CharIndices { front_offset: 0, iter: self.chars() } } - /// An iterator over the bytes of a string slice. + /// Returns an iterator over the bytes of a string slice. /// /// As a string slice consists of a sequence of bytes, we can iterate /// through a string slice by byte. This method returns such an iterator. @@ -1037,7 +1017,7 @@ impl str { SplitAsciiWhitespace { inner } } - /// An iterator over the lines of a string, as string slices. + /// Returns an iterator over the lines of a string, as string slices. /// /// Lines are split at line endings that are either newlines (`\n`) or /// sequences of a carriage return followed by a line feed (`\r\n`). @@ -1088,7 +1068,7 @@ impl str { Lines(self.split_inclusive('\n').map(LinesMap)) } - /// An iterator over the lines of a string. + /// Returns an iterator over the lines of a string. #[stable(feature = "rust1", since = "1.0.0")] #[deprecated(since = "1.4.0", note = "use lines() instead now", suggestion = "lines")] #[inline] @@ -1137,7 +1117,7 @@ impl str { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool { + pub fn contains(&self, pat: P) -> bool { pat.is_contained_in(self) } @@ -1174,7 +1154,7 @@ impl str { /// assert!(bananas.starts_with(&['a', 'b', 'c', 'd'])); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool { + pub fn starts_with(&self, pat: P) -> bool { pat.is_prefix_of(self) } @@ -1198,9 +1178,9 @@ impl str { /// assert!(!bananas.ends_with("nana")); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn ends_with<'a, P>(&'a self, pat: P) -> bool + pub fn ends_with(&self, pat: P) -> bool where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + for<'a> P::Searcher<'a>: ReverseSearcher<'a>, { pat.is_suffix_of(self) } @@ -1249,7 +1229,7 @@ impl str { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option { + pub fn find(&self, pat: P) -> Option { pat.into_searcher(self).next_match().map(|(i, _)| i) } @@ -1295,14 +1275,14 @@ impl str { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn rfind<'a, P>(&'a self, pat: P) -> Option + pub fn rfind(&self, pat: P) -> Option where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + for<'a> P::Searcher<'a>: ReverseSearcher<'a>, { pat.into_searcher(self).next_match_back().map(|(i, _)| i) } - /// An iterator over substrings of this string slice, separated by + /// Returns an iterator over substrings of this string slice, separated by /// characters matched by a pattern. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a @@ -1417,7 +1397,7 @@ impl str { /// [`split_whitespace`]: str::split_whitespace #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> { + pub fn split(&self, pat: P) -> Split<'_, P> { Split(SplitInternal { start: 0, end: self.len(), @@ -1427,10 +1407,11 @@ impl str { }) } - /// An iterator over substrings of this string slice, separated by - /// characters matched by a pattern. Differs from the iterator produced by - /// `split` in that `split_inclusive` leaves the matched part as the - /// terminator of the substring. + /// Returns an iterator over substrings of this string slice, separated by + /// characters matched by a pattern. + /// + /// Differs from the iterator produced by `split` in that `split_inclusive` + /// leaves the matched part as the terminator of the substring. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a /// function or closure that determines if a character matches. @@ -1457,7 +1438,7 @@ impl str { /// ``` #[stable(feature = "split_inclusive", since = "1.51.0")] #[inline] - pub fn split_inclusive<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitInclusive<'a, P> { + pub fn split_inclusive(&self, pat: P) -> SplitInclusive<'_, P> { SplitInclusive(SplitInternal { start: 0, end: self.len(), @@ -1467,8 +1448,8 @@ impl str { }) } - /// An iterator over substrings of the given string slice, separated by - /// characters matched by a pattern and yielded in reverse order. + /// Returns an iterator over substrings of the given string slice, separated + /// by characters matched by a pattern and yielded in reverse order. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a /// function or closure that determines if a character matches. @@ -1512,15 +1493,15 @@ impl str { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P> + pub fn rsplit(&self, pat: P) -> RSplit<'_, P> where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + for<'a> P::Searcher<'a>: ReverseSearcher<'a>, { RSplit(self.split(pat).0) } - /// An iterator over substrings of the given string slice, separated by - /// characters matched by a pattern. + /// Returns an iterator over substrings of the given string slice, separated + /// by characters matched by a pattern. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a /// function or closure that determines if a character matches. @@ -1561,11 +1542,11 @@ impl str { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> { + pub fn split_terminator(&self, pat: P) -> SplitTerminator<'_, P> { SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 }) } - /// An iterator over substrings of `self`, separated by characters + /// Returns an iterator over substrings of `self`, separated by characters /// matched by a pattern and yielded in reverse order. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a @@ -1607,15 +1588,15 @@ impl str { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P> + pub fn rsplit_terminator(&self, pat: P) -> RSplitTerminator<'_, P> where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + for<'a> P::Searcher<'a>: ReverseSearcher<'a>, { RSplitTerminator(self.split_terminator(pat).0) } - /// An iterator over substrings of the given string slice, separated by a - /// pattern, restricted to returning at most `n` items. + /// Returns an iterator over substrings of the given string slice, separated + /// by a pattern, restricted to returning at most `n` items. /// /// If `n` substrings are returned, the last substring (the `n`th substring) /// will contain the remainder of the string. @@ -1662,13 +1643,13 @@ impl str { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> { + pub fn splitn(&self, n: usize, pat: P) -> SplitN<'_, P> { SplitN(SplitNInternal { iter: self.split(pat).0, count: n }) } - /// An iterator over substrings of this string slice, separated by a - /// pattern, starting from the end of the string, restricted to returning - /// at most `n` items. + /// Returns an iterator over substrings of this string slice, separated by a + /// pattern, starting from the end of the string, restricted to returning at + /// most `n` items. /// /// If `n` substrings are returned, the last substring (the `n`th substring) /// will contain the remainder of the string. @@ -1711,9 +1692,9 @@ impl str { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P> + pub fn rsplitn(&self, n: usize, pat: P) -> RSplitN<'_, P> where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + for<'a> P::Searcher<'a>: ReverseSearcher<'a>, { RSplitN(self.splitn(n, pat).0) } @@ -1731,7 +1712,7 @@ impl str { /// ``` #[stable(feature = "str_split_once", since = "1.52.0")] #[inline] - pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> { + pub fn split_once(&self, delimiter: P) -> Option<(&'_ str, &'_ str)> { let (start, end) = delimiter.into_searcher(self).next_match()?; // SAFETY: `Searcher` is known to return valid indices. unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) } @@ -1749,17 +1730,17 @@ impl str { /// ``` #[stable(feature = "str_split_once", since = "1.52.0")] #[inline] - pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> + pub fn rsplit_once(&self, delimiter: P) -> Option<(&'_ str, &'_ str)> where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + for<'a> P::Searcher<'a>: ReverseSearcher<'a>, { let (start, end) = delimiter.into_searcher(self).next_match_back()?; // SAFETY: `Searcher` is known to return valid indices. unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) } } - /// An iterator over the disjoint matches of a pattern within the given string - /// slice. + /// Returns an iterator over the disjoint matches of a pattern within the + /// given string slice. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a /// function or closure that determines if a character matches. @@ -1789,12 +1770,12 @@ impl str { /// ``` #[stable(feature = "str_matches", since = "1.2.0")] #[inline] - pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> { + pub fn matches(&self, pat: P) -> Matches<'_, P> { Matches(MatchesInternal(pat.into_searcher(self))) } - /// An iterator over the disjoint matches of a pattern within this string slice, - /// yielded in reverse order. + /// Returns an iterator over the disjoint matches of a pattern within this + /// string slice, yielded in reverse order. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a /// function or closure that determines if a character matches. @@ -1823,14 +1804,14 @@ impl str { /// ``` #[stable(feature = "str_matches", since = "1.2.0")] #[inline] - pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P> + pub fn rmatches(&self, pat: P) -> RMatches<'_, P> where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + for<'a> P::Searcher<'a>: ReverseSearcher<'a>, { RMatches(self.matches(pat).0) } - /// An iterator over the disjoint matches of a pattern within this string + /// Returns an iterator over the disjoint matches of a pattern within this string /// slice as well as the index that the match starts at. /// /// For matches of `pat` within `self` that overlap, only the indices @@ -1867,11 +1848,11 @@ impl str { /// ``` #[stable(feature = "str_match_indices", since = "1.5.0")] #[inline] - pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> { + pub fn match_indices(&self, pat: P) -> MatchIndices<'_, P> { MatchIndices(MatchIndicesInternal(pat.into_searcher(self))) } - /// An iterator over the disjoint matches of a pattern within `self`, + /// Returns an iterator over the disjoint matches of a pattern within `self`, /// yielded in reverse order along with the index of the match. /// /// For matches of `pat` within `self` that overlap, only the indices @@ -1907,9 +1888,9 @@ impl str { /// ``` #[stable(feature = "str_match_indices", since = "1.5.0")] #[inline] - pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P> + pub fn rmatch_indices(&self, pat: P) -> RMatchIndices<'_, P> where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + for<'a> P::Searcher<'a>: ReverseSearcher<'a>, { RMatchIndices(self.match_indices(pat).0) } @@ -2122,9 +2103,9 @@ impl str { #[must_use = "this returns the trimmed string as a new slice, \ without modifying the original"] #[stable(feature = "rust1", since = "1.0.0")] - pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str + pub fn trim_matches(&self, pat: P) -> &str where - P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>, + for<'a> P::Searcher<'a>: DoubleEndedSearcher<'a>, { let mut i = 0; let mut j = 0; @@ -2169,7 +2150,7 @@ impl str { #[must_use = "this returns the trimmed string as a new slice, \ without modifying the original"] #[stable(feature = "trim_direction", since = "1.30.0")] - pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str { + pub fn trim_start_matches(&self, pat: P) -> &str { let mut i = self.len(); let mut matcher = pat.into_searcher(self); if let Some((a, _)) = matcher.next_reject() { @@ -2202,7 +2183,7 @@ impl str { #[must_use = "this returns the remaining substring as a new slice, \ without modifying the original"] #[stable(feature = "str_strip", since = "1.45.0")] - pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> { + pub fn strip_prefix(&self, prefix: P) -> Option<&str> { prefix.strip_prefix_of(self) } @@ -2229,10 +2210,9 @@ impl str { #[must_use = "this returns the remaining substring as a new slice, \ without modifying the original"] #[stable(feature = "str_strip", since = "1.45.0")] - pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str> + pub fn strip_suffix(&self, suffix: P) -> Option<&str> where - P: Pattern<'a>, -

>::Searcher: ReverseSearcher<'a>, + for<'a> P::Searcher<'a>: ReverseSearcher<'a>, { suffix.strip_suffix_of(self) } @@ -2273,9 +2253,9 @@ impl str { #[must_use = "this returns the trimmed string as a new slice, \ without modifying the original"] #[stable(feature = "trim_direction", since = "1.30.0")] - pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str + pub fn trim_end_matches(&self, pat: P) -> &str where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + for<'a> P::Searcher<'a>: ReverseSearcher<'a>, { let mut j = 0; let mut matcher = pat.into_searcher(self); @@ -2317,7 +2297,7 @@ impl str { note = "superseded by `trim_start_matches`", suggestion = "trim_start_matches" )] - pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str { + pub fn trim_left_matches(&self, pat: P) -> &str { self.trim_start_matches(pat) } @@ -2360,9 +2340,9 @@ impl str { note = "superseded by `trim_end_matches`", suggestion = "trim_end_matches" )] - pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str + pub fn trim_right_matches(&self, pat: P) -> &str where - P: Pattern<'a, Searcher: ReverseSearcher<'a>>, + for<'a> P::Searcher<'a>: ReverseSearcher<'a>, { self.trim_end_matches(pat) } @@ -2597,7 +2577,7 @@ impl str { unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii()) } } - /// Return an iterator that escapes each char in `self` with [`char::escape_debug`]. + /// Returns an iterator that escapes each char in `self` with [`char::escape_debug`]. /// /// Note: only extended grapheme codepoints that begin the string will be /// escaped. @@ -2646,7 +2626,7 @@ impl str { } } - /// Return an iterator that escapes each char in `self` with [`char::escape_default`]. + /// Returns an iterator that escapes each char in `self` with [`char::escape_default`]. /// /// # Examples /// @@ -2684,7 +2664,7 @@ impl str { EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) } } - /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`]. + /// Returns an iterator that escapes each char in `self` with [`char::escape_unicode`]. /// /// # Examples /// @@ -2721,6 +2701,39 @@ impl str { pub fn escape_unicode(&self) -> EscapeUnicode<'_> { EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) } } + + /// Returns the range that a substring points to. + /// + /// Returns `None` if `substr` does not point within `self`. + /// + /// Unlike [`str::find`], **this does not search through the string**. + /// Instead, it uses pointer arithmetic to find where in the string + /// `substr` is derived from. + /// + /// This is useful for extending [`str::split`] and similar methods. + /// + /// Note that this method may return false positives (typically either + /// `Some(0..0)` or `Some(self.len()..self.len())`) if `substr` is a + /// zero-length `str` that points at the beginning or end of another, + /// independent, `str`. + /// + /// # Examples + /// ``` + /// #![feature(substr_range)] + /// + /// let data = "a, b, b, a"; + /// let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap()); + /// + /// assert_eq!(iter.next(), Some(0..1)); + /// assert_eq!(iter.next(), Some(3..4)); + /// assert_eq!(iter.next(), Some(6..7)); + /// assert_eq!(iter.next(), Some(9..10)); + /// ``` + #[must_use] + #[unstable(feature = "substr_range", issue = "126769")] + pub fn substr_range(&self, substr: &str) -> Option> { + self.as_bytes().subslice_range(substr.as_bytes()) + } } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/core/src/str/pattern.rs b/core/src/str/pattern.rs index 8988229be2e57..2f1096db8f00c 100644 --- a/core/src/str/pattern.rs +++ b/core/src/str/pattern.rs @@ -38,18 +38,17 @@ issue = "27721" )] -use crate::cmp; use crate::cmp::Ordering; use crate::convert::TryInto as _; -use crate::fmt; use crate::slice::memchr; +use crate::{cmp, fmt}; // Pattern /// A string pattern. /// -/// A `Pattern<'a>` expresses that the implementing type -/// can be used as a string pattern for searching in a [`&'a str`][str]. +/// A `Pattern` expresses that the implementing type +/// can be used as a string pattern for searching in a [`&str`][str]. /// /// For example, both `'a'` and `"aa"` are patterns that /// would match at index `1` in the string `"baaaab"`. @@ -97,38 +96,38 @@ use crate::slice::memchr; /// assert_eq!("abcdef_z".find(|ch| ch > 'd' && ch < 'y'), Some(4)); /// assert_eq!("abcddd_z".find(|ch| ch > 'd' && ch < 'y'), None); /// ``` -pub trait Pattern<'a>: Sized { +pub trait Pattern: Sized { /// Associated searcher for this pattern - type Searcher: Searcher<'a>; + type Searcher<'a>: Searcher<'a>; /// Constructs the associated searcher from /// `self` and the `haystack` to search in. - fn into_searcher(self, haystack: &'a str) -> Self::Searcher; + fn into_searcher(self, haystack: &str) -> Self::Searcher<'_>; /// Checks whether the pattern matches anywhere in the haystack #[inline] - fn is_contained_in(self, haystack: &'a str) -> bool { + fn is_contained_in(self, haystack: &str) -> bool { self.into_searcher(haystack).next_match().is_some() } /// Checks whether the pattern matches at the front of the haystack #[inline] - fn is_prefix_of(self, haystack: &'a str) -> bool { + fn is_prefix_of(self, haystack: &str) -> bool { matches!(self.into_searcher(haystack).next(), SearchStep::Match(0, _)) } /// Checks whether the pattern matches at the back of the haystack #[inline] - fn is_suffix_of(self, haystack: &'a str) -> bool + fn is_suffix_of<'a>(self, haystack: &'a str) -> bool where - Self::Searcher: ReverseSearcher<'a>, + Self::Searcher<'a>: ReverseSearcher<'a>, { matches!(self.into_searcher(haystack).next_back(), SearchStep::Match(_, j) if haystack.len() == j) } /// Removes the pattern from the front of haystack, if it matches. #[inline] - fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> { + fn strip_prefix_of(self, haystack: &str) -> Option<&str> { if let SearchStep::Match(start, len) = self.into_searcher(haystack).next() { debug_assert_eq!( start, 0, @@ -144,9 +143,9 @@ pub trait Pattern<'a>: Sized { /// Removes the pattern from the back of haystack, if it matches. #[inline] - fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> + fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str> where - Self::Searcher: ReverseSearcher<'a>, + Self::Searcher<'a>: ReverseSearcher<'a>, { if let SearchStep::Match(start, end) = self.into_searcher(haystack).next_back() { debug_assert_eq!( @@ -349,7 +348,7 @@ pub trait DoubleEndedSearcher<'a>: ReverseSearcher<'a> {} // Impl for char ///////////////////////////////////////////////////////////////////////////// -/// Associated type for `>::Searcher`. +/// Associated type for `::Searcher<'a>`. #[derive(Clone, Debug)] pub struct CharSearcher<'a> { haystack: &'a str, @@ -543,11 +542,11 @@ impl<'a> DoubleEndedSearcher<'a> for CharSearcher<'a> {} /// ``` /// assert_eq!("Hello world".find('o'), Some(4)); /// ``` -impl<'a> Pattern<'a> for char { - type Searcher = CharSearcher<'a>; +impl Pattern for char { + type Searcher<'a> = CharSearcher<'a>; #[inline] - fn into_searcher(self, haystack: &'a str) -> Self::Searcher { + fn into_searcher(self, haystack: &str) -> Self::Searcher<'_> { let mut utf8_encoded = [0; 4]; let utf8_size = self .encode_utf8(&mut utf8_encoded) @@ -566,7 +565,7 @@ impl<'a> Pattern<'a> for char { } #[inline] - fn is_contained_in(self, haystack: &'a str) -> bool { + fn is_contained_in(self, haystack: &str) -> bool { if (self as u32) < 128 { haystack.as_bytes().contains(&(self as u8)) } else { @@ -576,27 +575,27 @@ impl<'a> Pattern<'a> for char { } #[inline] - fn is_prefix_of(self, haystack: &'a str) -> bool { + fn is_prefix_of(self, haystack: &str) -> bool { self.encode_utf8(&mut [0u8; 4]).is_prefix_of(haystack) } #[inline] - fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> { + fn strip_prefix_of(self, haystack: &str) -> Option<&str> { self.encode_utf8(&mut [0u8; 4]).strip_prefix_of(haystack) } #[inline] - fn is_suffix_of(self, haystack: &'a str) -> bool + fn is_suffix_of<'a>(self, haystack: &'a str) -> bool where - Self::Searcher: ReverseSearcher<'a>, + Self::Searcher<'a>: ReverseSearcher<'a>, { self.encode_utf8(&mut [0u8; 4]).is_suffix_of(haystack) } #[inline] - fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> + fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str> where - Self::Searcher: ReverseSearcher<'a>, + Self::Searcher<'a>: ReverseSearcher<'a>, { self.encode_utf8(&mut [0u8; 4]).strip_suffix_of(haystack) } @@ -651,11 +650,11 @@ struct MultiCharEqSearcher<'a, C: MultiCharEq> { char_indices: super::CharIndices<'a>, } -impl<'a, C: MultiCharEq> Pattern<'a> for MultiCharEqPattern { - type Searcher = MultiCharEqSearcher<'a, C>; +impl Pattern for MultiCharEqPattern { + type Searcher<'a> = MultiCharEqSearcher<'a, C>; #[inline] - fn into_searcher(self, haystack: &'a str) -> MultiCharEqSearcher<'a, C> { + fn into_searcher(self, haystack: &str) -> MultiCharEqSearcher<'_, C> { MultiCharEqSearcher { haystack, char_eq: self.0, char_indices: haystack.char_indices() } } } @@ -710,41 +709,41 @@ impl<'a, C: MultiCharEq> DoubleEndedSearcher<'a> for MultiCharEqSearcher<'a, C> ///////////////////////////////////////////////////////////////////////////// macro_rules! pattern_methods { - ($t:ty, $pmap:expr, $smap:expr) => { - type Searcher = $t; + ($a:lifetime, $t:ty, $pmap:expr, $smap:expr) => { + type Searcher<$a> = $t; #[inline] - fn into_searcher(self, haystack: &'a str) -> $t { + fn into_searcher<$a>(self, haystack: &$a str) -> $t { ($smap)(($pmap)(self).into_searcher(haystack)) } #[inline] - fn is_contained_in(self, haystack: &'a str) -> bool { + fn is_contained_in<$a>(self, haystack: &$a str) -> bool { ($pmap)(self).is_contained_in(haystack) } #[inline] - fn is_prefix_of(self, haystack: &'a str) -> bool { + fn is_prefix_of<$a>(self, haystack: &$a str) -> bool { ($pmap)(self).is_prefix_of(haystack) } #[inline] - fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> { + fn strip_prefix_of<$a>(self, haystack: &$a str) -> Option<&$a str> { ($pmap)(self).strip_prefix_of(haystack) } #[inline] - fn is_suffix_of(self, haystack: &'a str) -> bool + fn is_suffix_of<$a>(self, haystack: &$a str) -> bool where - $t: ReverseSearcher<'a>, + $t: ReverseSearcher<$a>, { ($pmap)(self).is_suffix_of(haystack) } #[inline] - fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> + fn strip_suffix_of<$a>(self, haystack: &$a str) -> Option<&$a str> where - $t: ReverseSearcher<'a>, + $t: ReverseSearcher<$a>, { ($pmap)(self).strip_suffix_of(haystack) } @@ -786,16 +785,16 @@ macro_rules! searcher_methods { }; } -/// Associated type for `<[char; N] as Pattern<'a>>::Searcher`. +/// Associated type for `<[char; N] as Pattern>::Searcher<'a>`. #[derive(Clone, Debug)] pub struct CharArraySearcher<'a, const N: usize>( - as Pattern<'a>>::Searcher, + as Pattern>::Searcher<'a>, ); -/// Associated type for `<&[char; N] as Pattern<'a>>::Searcher`. +/// Associated type for `<&[char; N] as Pattern>::Searcher<'a>`. #[derive(Clone, Debug)] pub struct CharArrayRefSearcher<'a, 'b, const N: usize>( - as Pattern<'a>>::Searcher, + as Pattern>::Searcher<'a>, ); /// Searches for chars that are equal to any of the [`char`]s in the array. @@ -806,8 +805,8 @@ pub struct CharArrayRefSearcher<'a, 'b, const N: usize>( /// assert_eq!("Hello world".find(['o', 'l']), Some(2)); /// assert_eq!("Hello world".find(['h', 'w']), Some(6)); /// ``` -impl<'a, const N: usize> Pattern<'a> for [char; N] { - pattern_methods!(CharArraySearcher<'a, N>, MultiCharEqPattern, CharArraySearcher); +impl Pattern for [char; N] { + pattern_methods!('a, CharArraySearcher<'a, N>, MultiCharEqPattern, CharArraySearcher); } unsafe impl<'a, const N: usize> Searcher<'a> for CharArraySearcher<'a, N> { @@ -828,8 +827,8 @@ impl<'a, const N: usize> DoubleEndedSearcher<'a> for CharArraySearcher<'a, N> {} /// assert_eq!("Hello world".find(&['o', 'l']), Some(2)); /// assert_eq!("Hello world".find(&['h', 'w']), Some(6)); /// ``` -impl<'a, 'b, const N: usize> Pattern<'a> for &'b [char; N] { - pattern_methods!(CharArrayRefSearcher<'a, 'b, N>, MultiCharEqPattern, CharArrayRefSearcher); +impl<'b, const N: usize> Pattern for &'b [char; N] { + pattern_methods!('a, CharArrayRefSearcher<'a, 'b, N>, MultiCharEqPattern, CharArrayRefSearcher); } unsafe impl<'a, 'b, const N: usize> Searcher<'a> for CharArrayRefSearcher<'a, 'b, N> { @@ -848,9 +847,9 @@ impl<'a, 'b, const N: usize> DoubleEndedSearcher<'a> for CharArrayRefSearcher<'a // Todo: Change / Remove due to ambiguity in meaning. -/// Associated type for `<&[char] as Pattern<'a>>::Searcher`. +/// Associated type for `<&[char] as Pattern>::Searcher<'a>`. #[derive(Clone, Debug)] -pub struct CharSliceSearcher<'a, 'b>( as Pattern<'a>>::Searcher); +pub struct CharSliceSearcher<'a, 'b>( as Pattern>::Searcher<'a>); unsafe impl<'a, 'b> Searcher<'a> for CharSliceSearcher<'a, 'b> { searcher_methods!(forward); @@ -870,17 +869,17 @@ impl<'a, 'b> DoubleEndedSearcher<'a> for CharSliceSearcher<'a, 'b> {} /// assert_eq!("Hello world".find(&['l', 'l'] as &[_]), Some(2)); /// assert_eq!("Hello world".find(&['l', 'l'][..]), Some(2)); /// ``` -impl<'a, 'b> Pattern<'a> for &'b [char] { - pattern_methods!(CharSliceSearcher<'a, 'b>, MultiCharEqPattern, CharSliceSearcher); +impl<'b> Pattern for &'b [char] { + pattern_methods!('a, CharSliceSearcher<'a, 'b>, MultiCharEqPattern, CharSliceSearcher); } ///////////////////////////////////////////////////////////////////////////// // Impl for F: FnMut(char) -> bool ///////////////////////////////////////////////////////////////////////////// -/// Associated type for `>::Searcher`. +/// Associated type for `::Searcher<'a>`. #[derive(Clone)] -pub struct CharPredicateSearcher<'a, F>( as Pattern<'a>>::Searcher) +pub struct CharPredicateSearcher<'a, F>( as Pattern>::Searcher<'a>) where F: FnMut(char) -> bool; @@ -919,11 +918,11 @@ impl<'a, F> DoubleEndedSearcher<'a> for CharPredicateSearcher<'a, F> where F: Fn /// assert_eq!("Hello world".find(char::is_uppercase), Some(0)); /// assert_eq!("Hello world".find(|c| "aeiou".contains(c)), Some(1)); /// ``` -impl<'a, F> Pattern<'a> for F +impl Pattern for F where F: FnMut(char) -> bool, { - pattern_methods!(CharPredicateSearcher<'a, F>, MultiCharEqPattern, CharPredicateSearcher); + pattern_methods!('a, CharPredicateSearcher<'a, F>, MultiCharEqPattern, CharPredicateSearcher); } ///////////////////////////////////////////////////////////////////////////// @@ -931,8 +930,8 @@ where ///////////////////////////////////////////////////////////////////////////// /// Delegates to the `&str` impl. -impl<'a, 'b, 'c> Pattern<'a> for &'c &'b str { - pattern_methods!(StrSearcher<'a, 'b>, |&s| s, |s| s); +impl<'b, 'c> Pattern for &'c &'b str { + pattern_methods!('a, StrSearcher<'a, 'b>, |&s| s, |s| s); } ///////////////////////////////////////////////////////////////////////////// @@ -949,23 +948,23 @@ impl<'a, 'b, 'c> Pattern<'a> for &'c &'b str { /// ``` /// assert_eq!("Hello world".find("world"), Some(6)); /// ``` -impl<'a, 'b> Pattern<'a> for &'b str { - type Searcher = StrSearcher<'a, 'b>; +impl<'b> Pattern for &'b str { + type Searcher<'a> = StrSearcher<'a, 'b>; #[inline] - fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b> { + fn into_searcher(self, haystack: &str) -> StrSearcher<'_, 'b> { StrSearcher::new(haystack, self) } /// Checks whether the pattern matches at the front of the haystack. #[inline] - fn is_prefix_of(self, haystack: &'a str) -> bool { + fn is_prefix_of(self, haystack: &str) -> bool { haystack.as_bytes().starts_with(self.as_bytes()) } /// Checks whether the pattern matches anywhere in the haystack #[inline] - fn is_contained_in(self, haystack: &'a str) -> bool { + fn is_contained_in(self, haystack: &str) -> bool { if self.len() == 0 { return true; } @@ -991,7 +990,7 @@ impl<'a, 'b> Pattern<'a> for &'b str { /// Removes the pattern from the front of haystack, if it matches. #[inline] - fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> { + fn strip_prefix_of(self, haystack: &str) -> Option<&str> { if self.is_prefix_of(haystack) { // SAFETY: prefix was just verified to exist. unsafe { Some(haystack.get_unchecked(self.as_bytes().len()..)) } @@ -1002,13 +1001,19 @@ impl<'a, 'b> Pattern<'a> for &'b str { /// Checks whether the pattern matches at the back of the haystack. #[inline] - fn is_suffix_of(self, haystack: &'a str) -> bool { + fn is_suffix_of<'a>(self, haystack: &'a str) -> bool + where + Self::Searcher<'a>: ReverseSearcher<'a>, + { haystack.as_bytes().ends_with(self.as_bytes()) } /// Removes the pattern from the back of haystack, if it matches. #[inline] - fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> { + fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str> + where + Self::Searcher<'a>: ReverseSearcher<'a>, + { if self.is_suffix_of(haystack) { let i = haystack.len() - self.as_bytes().len(); // SAFETY: suffix was just verified to exist. @@ -1024,7 +1029,7 @@ impl<'a, 'b> Pattern<'a> for &'b str { ///////////////////////////////////////////////////////////////////////////// #[derive(Clone, Debug)] -/// Associated type for `<&str as Pattern<'a>>::Searcher`. +/// Associated type for `<&str as Pattern>::Searcher<'a>`. pub struct StrSearcher<'a, 'b> { haystack: &'a str, needle: &'b str, @@ -1753,8 +1758,7 @@ fn simd_contains(needle: &str, haystack: &str) -> Option { use crate::ops::BitAnd; use crate::simd::cmp::SimdPartialEq; - use crate::simd::mask8x16 as Mask; - use crate::simd::u8x16 as Block; + use crate::simd::{mask8x16 as Mask, u8x16 as Block}; let first_probe = needle[0]; let last_byte_offset = needle.len() - 1; diff --git a/core/src/str/traits.rs b/core/src/str/traits.rs index 3de5546c4d4e3..b69c476ae5e53 100644 --- a/core/src/str/traits.rs +++ b/core/src/str/traits.rs @@ -1,14 +1,11 @@ //! Trait implementations for `str`. +use super::ParseBoolError; use crate::cmp::Ordering; use crate::intrinsics::unchecked_sub; -use crate::ops; -use crate::ptr; -use crate::range; use crate::slice::SliceIndex; use crate::ub_checks::assert_unsafe_precondition; - -use super::ParseBoolError; +use crate::{ops, ptr, range}; /// Implements ordering of strings. /// diff --git a/core/src/str/validations.rs b/core/src/str/validations.rs index a11d7fee8af0c..cca8ff74dda8b 100644 --- a/core/src/str/validations.rs +++ b/core/src/str/validations.rs @@ -1,8 +1,7 @@ //! Operations related to UTF-8 validation. -use crate::mem; - use super::Utf8Error; +use crate::mem; /// Returns the initial codepoint accumulator for the first byte. /// The first byte is special, only want bottom 5 bits for width 2, 4 bits diff --git a/core/src/sync/atomic.rs b/core/src/sync/atomic.rs index efc07f38f68e0..495d9191a9f85 100644 --- a/core/src/sync/atomic.rs +++ b/core/src/sync/atomic.rs @@ -223,12 +223,9 @@ #![allow(clippy::not_unsafe_ptr_arg_deref)] use self::Ordering::*; - use crate::cell::UnsafeCell; -use crate::fmt; -use crate::intrinsics; - use crate::hint::spin_loop; +use crate::{fmt, intrinsics}; // Some architectures don't have byte-sized atomics, which results in LLVM // emulating them using a LL/SC loop. However for AtomicBool we can take @@ -481,7 +478,7 @@ impl AtomicBool { unsafe { &mut *(self.v.get() as *mut bool) } } - /// Get atomic access to a `&mut bool`. + /// Gets atomic access to a `&mut bool`. /// /// # Examples /// @@ -503,7 +500,7 @@ impl AtomicBool { unsafe { &mut *(v as *mut bool as *mut Self) } } - /// Get non-atomic access to a `&mut [AtomicBool]` slice. + /// Gets non-atomic access to a `&mut [AtomicBool]` slice. /// /// This is safe because the mutable reference guarantees that no other threads are /// concurrently accessing the atomic data. @@ -537,7 +534,7 @@ impl AtomicBool { unsafe { &mut *(this as *mut [Self] as *mut [bool]) } } - /// Get atomic access to a `&mut [bool]` slice. + /// Gets atomic access to a `&mut [bool]` slice. /// /// # Examples /// @@ -1080,7 +1077,7 @@ impl AtomicBool { /// assert_eq!(foo.load(Ordering::SeqCst), true); /// ``` #[inline] - #[stable(feature = "atomic_bool_fetch_not", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "atomic_bool_fetch_not", since = "1.81.0")] #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces pub fn fetch_not(&self, order: Ordering) -> bool { @@ -1276,7 +1273,7 @@ impl AtomicPtr { self.p.get_mut() } - /// Get atomic access to a pointer. + /// Gets atomic access to a pointer. /// /// # Examples /// @@ -1303,7 +1300,7 @@ impl AtomicPtr { unsafe { &mut *(v as *mut *mut T as *mut Self) } } - /// Get non-atomic access to a `&mut [AtomicPtr]` slice. + /// Gets non-atomic access to a `&mut [AtomicPtr]` slice. /// /// This is safe because the mutable reference guarantees that no other threads are /// concurrently accessing the atomic data. @@ -1343,7 +1340,7 @@ impl AtomicPtr { unsafe { &mut *(this as *mut [Self] as *mut [*mut T]) } } - /// Get atomic access to a slice of pointers. + /// Gets atomic access to a slice of pointers. /// /// # Examples /// diff --git a/core/src/sync/exclusive.rs b/core/src/sync/exclusive.rs index e8170c13ed263..fbf8dafad1869 100644 --- a/core/src/sync/exclusive.rs +++ b/core/src/sync/exclusive.rs @@ -114,7 +114,7 @@ impl Exclusive { } impl Exclusive { - /// Get exclusive access to the underlying value. + /// Gets exclusive access to the underlying value. #[unstable(feature = "exclusive_wrapper", issue = "98407")] #[must_use] #[inline] @@ -122,7 +122,7 @@ impl Exclusive { &mut self.inner } - /// Get pinned exclusive access to the underlying value. + /// Gets pinned exclusive access to the underlying value. /// /// `Exclusive` is considered to _structurally pin_ the underlying /// value, which means _unpinned_ `Exclusive`s can produce _unpinned_ diff --git a/core/src/task/wake.rs b/core/src/task/wake.rs index 86a965f68e085..8ce3eb2ea3921 100644 --- a/core/src/task/wake.rs +++ b/core/src/task/wake.rs @@ -1,12 +1,10 @@ #![stable(feature = "futures_api", since = "1.36.0")] -use crate::mem::transmute; - use crate::any::Any; -use crate::fmt; use crate::marker::PhantomData; +use crate::mem::{transmute, ManuallyDrop}; use crate::panic::AssertUnwindSafe; -use crate::ptr; +use crate::{fmt, ptr}; /// A `RawWaker` allows the implementor of a task executor to create a [`Waker`] /// or a [`LocalWaker`] which provides customized wakeup behavior. @@ -62,7 +60,7 @@ impl RawWaker { RawWaker { data, vtable } } - /// Get the `data` pointer used to create this `RawWaker`. + /// Gets the `data` pointer used to create this `RawWaker`. #[inline] #[must_use] #[unstable(feature = "waker_getters", issue = "96992")] @@ -70,7 +68,7 @@ impl RawWaker { self.data } - /// Get the `vtable` pointer used to create this `RawWaker`. + /// Gets the `vtable` pointer used to create this `RawWaker`. #[inline] #[must_use] #[unstable(feature = "waker_getters", issue = "96992")] @@ -151,7 +149,7 @@ pub struct RawWakerVTable { /// pointer. wake_by_ref: unsafe fn(*const ()), - /// This function gets called when a [`Waker`] gets dropped. + /// This function will be called when a [`Waker`] gets dropped. /// /// The implementation of this function must make sure to release any /// resources that are associated with this instance of a [`RawWaker`] and @@ -204,7 +202,8 @@ impl RawWakerVTable { /// /// # `drop` /// - /// This function gets called when a [`Waker`]/[`LocalWaker`] gets dropped. + /// This function will be called when a [`Waker`]/[`LocalWaker`] gets + /// dropped. /// /// The implementation of this function must make sure to release any /// resources that are associated with this instance of a [`RawWaker`] and @@ -249,9 +248,9 @@ pub struct Context<'a> { } impl<'a> Context<'a> { - /// Create a new `Context` from a [`&Waker`](Waker). + /// Creates a new `Context` from a [`&Waker`](Waker). #[stable(feature = "futures_api", since = "1.36.0")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_stable(feature = "const_waker", since = "CURRENT_RUSTC_VERSION")] #[must_use] #[inline] pub const fn from_waker(waker: &'a Waker) -> Self { @@ -262,7 +261,7 @@ impl<'a> Context<'a> { #[inline] #[must_use] #[stable(feature = "futures_api", since = "1.36.0")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_stable(feature = "const_waker", since = "CURRENT_RUSTC_VERSION")] pub const fn waker(&self) -> &'a Waker { &self.waker } @@ -270,7 +269,7 @@ impl<'a> Context<'a> { /// Returns a reference to the [`LocalWaker`] for the current task. #[inline] #[unstable(feature = "local_waker", issue = "118959")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "local_waker", issue = "118959")] pub const fn local_waker(&self) -> &'a LocalWaker { &self.local_waker } @@ -278,7 +277,7 @@ impl<'a> Context<'a> { /// Returns a reference to the extension data for the current task. #[inline] #[unstable(feature = "context_ext", issue = "123392")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "context_ext", issue = "123392")] pub const fn ext(&mut self) -> &mut dyn Any { // FIXME: this field makes Context extra-weird about unwind safety // can we justify AssertUnwindSafe if we stabilize this? do we care? @@ -335,10 +334,10 @@ pub struct ContextBuilder<'a> { } impl<'a> ContextBuilder<'a> { - /// Create a ContextBuilder from a Waker. + /// Creates a ContextBuilder from a Waker. #[inline] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] #[unstable(feature = "local_waker", issue = "118959")] + #[rustc_const_stable(feature = "const_waker", since = "CURRENT_RUSTC_VERSION")] pub const fn from_waker(waker: &'a Waker) -> Self { // SAFETY: LocalWaker is just Waker without thread safety let local_waker = unsafe { transmute(waker) }; @@ -351,10 +350,10 @@ impl<'a> ContextBuilder<'a> { } } - /// Create a ContextBuilder from an existing Context. + /// Creates a ContextBuilder from an existing Context. #[inline] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] #[unstable(feature = "context_ext", issue = "123392")] + #[rustc_const_unstable(feature = "context_ext", issue = "123392")] pub const fn from(cx: &'a mut Context<'_>) -> Self { let ext = match &mut cx.ext.0 { ExtData::Some(ext) => ExtData::Some(*ext), @@ -369,26 +368,26 @@ impl<'a> ContextBuilder<'a> { } } - /// This method is used to set the value for the waker on `Context`. + /// Sets the value for the waker on `Context`. #[inline] #[unstable(feature = "context_ext", issue = "123392")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "context_ext", issue = "123392")] pub const fn waker(self, waker: &'a Waker) -> Self { Self { waker, ..self } } - /// This method is used to set the value for the local waker on `Context`. + /// Sets the value for the local waker on `Context`. #[inline] #[unstable(feature = "local_waker", issue = "118959")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "local_waker", issue = "118959")] pub const fn local_waker(self, local_waker: &'a LocalWaker) -> Self { Self { local_waker, ..self } } - /// This method is used to set the value for the extension data on `Context`. + /// Sets the value for the extension data on `Context`. #[inline] #[unstable(feature = "context_ext", issue = "123392")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "context_ext", issue = "123392")] pub const fn ext(self, data: &'a mut dyn Any) -> Self { Self { ext: ExtData::Some(data), ..self } } @@ -396,7 +395,7 @@ impl<'a> ContextBuilder<'a> { /// Builds the `Context`. #[inline] #[unstable(feature = "local_waker", issue = "118959")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_stable(feature = "const_waker", since = "CURRENT_RUSTC_VERSION")] pub const fn build(self) -> Context<'a> { let ContextBuilder { waker, local_waker, ext, _marker, _marker2 } = self; Context { waker, local_waker, ext: AssertUnwindSafe(ext), _marker, _marker2 } @@ -429,7 +428,7 @@ impl<'a> ContextBuilder<'a> { /// [`Future::poll()`]: core::future::Future::poll /// [`Poll::Pending`]: core::task::Poll::Pending /// [`Wake`]: ../../alloc/task/trait.Wake.html -#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/66401 +#[repr(transparent)] #[stable(feature = "futures_api", since = "1.36.0")] pub struct Waker { waker: RawWaker, @@ -443,7 +442,7 @@ unsafe impl Send for Waker {} unsafe impl Sync for Waker {} impl Waker { - /// Wake up the task associated with this `Waker`. + /// Wakes up the task associated with this `Waker`. /// /// As long as the executor keeps running and the task is not finished, it is /// guaranteed that each invocation of [`wake()`](Self::wake) (or @@ -465,19 +464,17 @@ impl Waker { pub fn wake(self) { // The actual wakeup call is delegated through a virtual function call // to the implementation which is defined by the executor. - let wake = self.waker.vtable.wake; - let data = self.waker.data; // Don't call `drop` -- the waker will be consumed by `wake`. - crate::mem::forget(self); + let this = ManuallyDrop::new(self); // SAFETY: This is safe because `Waker::from_raw` is the only way // to initialize `wake` and `data` requiring the user to acknowledge // that the contract of `RawWaker` is upheld. - unsafe { (wake)(data) }; + unsafe { (this.waker.vtable.wake)(this.waker.data) }; } - /// Wake up the task associated with this `Waker` without consuming the `Waker`. + /// Wakes up the task associated with this `Waker` without consuming the `Waker`. /// /// This is similar to [`wake()`](Self::wake), but may be slightly less efficient in /// the case where an owned `Waker` is available. This method should be preferred to @@ -524,7 +521,7 @@ impl Waker { #[inline] #[must_use] #[stable(feature = "futures_api", since = "1.36.0")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_stable(feature = "const_waker", since = "CURRENT_RUSTC_VERSION")] pub const unsafe fn from_raw(waker: RawWaker) -> Waker { Waker { waker } } @@ -558,7 +555,7 @@ impl Waker { WAKER } - /// Get a reference to the underlying [`RawWaker`]. + /// Gets a reference to the underlying [`RawWaker`]. #[inline] #[must_use] #[unstable(feature = "waker_getters", issue = "96992")] @@ -695,7 +692,7 @@ impl fmt::Debug for Waker { /// [`Poll::Pending`]: core::task::Poll::Pending /// [`local_waker`]: core::task::Context::local_waker #[unstable(feature = "local_waker", issue = "118959")] -#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/66401 +#[repr(transparent)] pub struct LocalWaker { waker: RawWaker, } @@ -704,7 +701,7 @@ pub struct LocalWaker { impl Unpin for LocalWaker {} impl LocalWaker { - /// Wake up the task associated with this `LocalWaker`. + /// Wakes up the task associated with this `LocalWaker`. /// /// As long as the executor keeps running and the task is not finished, it is /// guaranteed that each invocation of [`wake()`](Self::wake) (or @@ -726,19 +723,17 @@ impl LocalWaker { pub fn wake(self) { // The actual wakeup call is delegated through a virtual function call // to the implementation which is defined by the executor. - let wake = self.waker.vtable.wake; - let data = self.waker.data; // Don't call `drop` -- the waker will be consumed by `wake`. - crate::mem::forget(self); + let this = ManuallyDrop::new(self); // SAFETY: This is safe because `Waker::from_raw` is the only way // to initialize `wake` and `data` requiring the user to acknowledge // that the contract of `RawWaker` is upheld. - unsafe { (wake)(data) }; + unsafe { (this.waker.vtable.wake)(this.waker.data) }; } - /// Wake up the task associated with this `LocalWaker` without consuming the `LocalWaker`. + /// Wakes up the task associated with this `LocalWaker` without consuming the `LocalWaker`. /// /// This is similar to [`wake()`](Self::wake), but may be slightly less efficient in /// the case where an owned `Waker` is available. This method should be preferred to @@ -777,7 +772,7 @@ impl LocalWaker { #[inline] #[must_use] #[unstable(feature = "local_waker", issue = "118959")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "local_waker", issue = "118959")] pub const unsafe fn from_raw(waker: RawWaker) -> LocalWaker { Self { waker } } @@ -812,7 +807,7 @@ impl LocalWaker { WAKER } - /// Get a reference to the underlying [`RawWaker`]. + /// Gets a reference to the underlying [`RawWaker`]. #[inline] #[must_use] #[unstable(feature = "waker_getters", issue = "96992")] diff --git a/core/src/time.rs b/core/src/time.rs index d66f558078ea8..0390bb59a8984 100644 --- a/core/src/time.rs +++ b/core/src/time.rs @@ -617,16 +617,14 @@ impl Duration { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// use std::time::Duration; /// /// assert_eq!(Duration::new(100, 0).abs_diff(Duration::new(80, 0)), Duration::new(20, 0)); /// assert_eq!(Duration::new(100, 400_000_000).abs_diff(Duration::new(110, 0)), Duration::new(9, 600_000_000)); /// ``` - #[stable(feature = "duration_abs_diff", since = "CURRENT_RUSTC_VERSION")] - #[rustc_const_stable(feature = "duration_abs_diff", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "duration_abs_diff", since = "1.81.0")] + #[rustc_const_stable(feature = "duration_abs_diff", since = "1.81.0")] #[rustc_allow_const_fn_unstable(const_option)] #[must_use = "this returns the result of the operation, \ without modifying the original"] @@ -640,8 +638,6 @@ impl Duration { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// use std::time::Duration; /// @@ -700,8 +696,6 @@ impl Duration { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// use std::time::Duration; /// @@ -758,8 +752,6 @@ impl Duration { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// use std::time::Duration; /// @@ -814,8 +806,6 @@ impl Duration { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// use std::time::Duration; /// @@ -1037,7 +1027,7 @@ impl Duration { Duration::from_secs_f32(rhs * self.as_secs_f32()) } - /// Divide `Duration` by `f64`. + /// Divides `Duration` by `f64`. /// /// # Panics /// This method will panic if result is negative, overflows `Duration` or not finite. @@ -1058,7 +1048,7 @@ impl Duration { Duration::from_secs_f64(self.as_secs_f64() / rhs) } - /// Divide `Duration` by `f32`. + /// Divides `Duration` by `f32`. /// /// # Panics /// This method will panic if result is negative, overflows `Duration` or not finite. @@ -1081,7 +1071,7 @@ impl Duration { Duration::from_secs_f32(self.as_secs_f32() / rhs) } - /// Divide `Duration` by `Duration` and return `f64`. + /// Divides `Duration` by `Duration` and returns `f64`. /// /// # Examples /// ``` @@ -1102,7 +1092,7 @@ impl Duration { self_nanos / rhs_nanos } - /// Divide `Duration` by `Duration` and return `f32`. + /// Divides `Duration` by `Duration` and returns `f32`. /// /// # Examples /// ``` diff --git a/core/src/tuple.rs b/core/src/tuple.rs index 8e961d8adc372..65d4d5cf2ce41 100644 --- a/core/src/tuple.rs +++ b/core/src/tuple.rs @@ -1,8 +1,7 @@ // See core/src/primitive_docs.rs for documentation. use crate::cmp::Ordering::{self, *}; -use crate::marker::ConstParamTy; -use crate::marker::StructuralPartialEq; +use crate::marker::{ConstParamTy_, StructuralPartialEq, UnsizedConstParamTy}; // Recursive macro for implementing n-ary tuple functions and operations // @@ -49,8 +48,15 @@ macro_rules! tuple_impls { maybe_tuple_doc! { $($T)+ @ - #[unstable(feature = "structural_match", issue = "31434")] - impl<$($T: ConstParamTy),+> ConstParamTy for ($($T,)+) + #[unstable(feature = "adt_const_params", issue = "95174")] + impl<$($T: ConstParamTy_),+> ConstParamTy_ for ($($T,)+) + {} + } + + maybe_tuple_doc! { + $($T)+ @ + #[unstable(feature = "unsized_const_params", issue = "95174")] + impl<$($T: UnsizedConstParamTy),+> UnsizedConstParamTy for ($($T,)+) {} } diff --git a/core/src/ub_checks.rs b/core/src/ub_checks.rs index 1aa6a288e7082..b65b48c162d9c 100644 --- a/core/src/ub_checks.rs +++ b/core/src/ub_checks.rs @@ -3,9 +3,11 @@ use crate::intrinsics::{self, const_eval_select}; -/// Check that the preconditions of an unsafe function are followed. The check is enabled at -/// runtime if debug assertions are enabled when the caller is monomorphized. In const-eval/Miri -/// checks implemented with this macro for language UB are always ignored. +/// Checks that the preconditions of an unsafe function are followed. +/// +/// The check is enabled at runtime if debug assertions are enabled when the +/// caller is monomorphized. In const-eval/Miri checks implemented with this +/// macro for language UB are always ignored. /// /// This macro should be called as /// `assert_unsafe_precondition!(check_{library,lang}_ub, "message", (ident: type = expr, ident: type = expr) => check_expr)` @@ -79,7 +81,6 @@ macro_rules! assert_unsafe_precondition { } #[unstable(feature = "ub_checks", issue = "none")] pub use assert_unsafe_precondition; - /// Checking library UB is always enabled when UB-checking is done /// (and we use a reexport so that there is no unnecessary wrapper function). #[unstable(feature = "ub_checks", issue = "none")] diff --git a/core/src/unicode/mod.rs b/core/src/unicode/mod.rs index 5ddd9f7476dd8..6066aa9921607 100644 --- a/core/src/unicode/mod.rs +++ b/core/src/unicode/mod.rs @@ -1,13 +1,15 @@ #![unstable(feature = "unicode_internals", issue = "none")] #![allow(missing_docs)] -// The `pub use` ones are for use in alloc, and are not re-exported in std. - -pub(crate) use unicode_data::alphabetic::lookup as Alphabetic; +// for use in alloc, not re-exported in std. +#[rustfmt::skip] pub use unicode_data::case_ignorable::lookup as Case_Ignorable; pub use unicode_data::cased::lookup as Cased; -pub(crate) use unicode_data::cc::lookup as Cc; pub use unicode_data::conversions; + +#[rustfmt::skip] +pub(crate) use unicode_data::alphabetic::lookup as Alphabetic; +pub(crate) use unicode_data::cc::lookup as Cc; pub(crate) use unicode_data::grapheme_extend::lookup as Grapheme_Extend; pub(crate) use unicode_data::lowercase::lookup as Lowercase; pub(crate) use unicode_data::n::lookup as N; diff --git a/core/tests/array.rs b/core/tests/array.rs index e7773d138c255..b6d18f1ec3822 100644 --- a/core/tests/array.rs +++ b/core/tests/array.rs @@ -259,7 +259,8 @@ fn iterator_drops() { #[test] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn array_default_impl_avoids_leaks_on_panic() { - use core::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + use core::sync::atomic::AtomicUsize; + use core::sync::atomic::Ordering::Relaxed; static COUNTER: AtomicUsize = AtomicUsize::new(0); #[derive(Debug)] struct Bomb(#[allow(dead_code)] usize); diff --git a/core/tests/clone.rs b/core/tests/clone.rs index 23efab2f1b598..b7130f16f8795 100644 --- a/core/tests/clone.rs +++ b/core/tests/clone.rs @@ -36,7 +36,8 @@ fn test_clone_to_uninit_slice_success() { #[test] #[cfg(panic = "unwind")] fn test_clone_to_uninit_slice_drops_on_panic() { - use core::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + use core::sync::atomic::AtomicUsize; + use core::sync::atomic::Ordering::Relaxed; /// A static counter is OK to use as long as _this one test_ isn't run several times in /// multiple threads. diff --git a/core/tests/cmp.rs b/core/tests/cmp.rs index 72fdd490da152..6c4e2146f9148 100644 --- a/core/tests/cmp.rs +++ b/core/tests/cmp.rs @@ -1,7 +1,5 @@ -use core::cmp::{ - self, - Ordering::{self, *}, -}; +use core::cmp::Ordering::{self, *}; +use core::cmp::{self}; #[test] fn test_int_totalord() { diff --git a/core/tests/ffi.rs b/core/tests/ffi.rs new file mode 100644 index 0000000000000..2b33fbd95f073 --- /dev/null +++ b/core/tests/ffi.rs @@ -0,0 +1 @@ +mod cstr; diff --git a/core/tests/ffi/cstr.rs b/core/tests/ffi/cstr.rs new file mode 100644 index 0000000000000..9bf4c21a9ab97 --- /dev/null +++ b/core/tests/ffi/cstr.rs @@ -0,0 +1,15 @@ +use core::ffi::CStr; + +#[test] +fn compares_as_u8s() { + let a: &CStr = c"Hello!"; // Starts with ascii + let a_bytes: &[u8] = a.to_bytes(); + assert!((..0b1000_0000).contains(&a_bytes[0])); + + let b: &CStr = c"こんにちは!"; // Starts with non ascii + let b_bytes: &[u8] = b.to_bytes(); + assert!((0b1000_0000..).contains(&b_bytes[0])); + + assert_eq!(Ord::cmp(a, b), Ord::cmp(a_bytes, b_bytes)); + assert_eq!(PartialOrd::partial_cmp(a, b), PartialOrd::partial_cmp(a_bytes, b_bytes)); +} diff --git a/core/tests/future.rs b/core/tests/future.rs index db417256dd01e..93aca72d59082 100644 --- a/core/tests/future.rs +++ b/core/tests/future.rs @@ -56,7 +56,7 @@ fn test_join() { let y = String::new(); let x = join!(async { - println!("{}", &y); + println!("{y}"); 1 }) .await; diff --git a/core/tests/hash/sip.rs b/core/tests/hash/sip.rs index 0a67c485c98bb..f79954f916b77 100644 --- a/core/tests/hash/sip.rs +++ b/core/tests/hash/sip.rs @@ -1,7 +1,6 @@ #![allow(deprecated)] -use core::hash::{Hash, Hasher}; -use core::hash::{SipHasher, SipHasher13}; +use core::hash::{Hash, Hasher, SipHasher, SipHasher13}; use core::{mem, slice}; // Hash just the bytes of the slice, without length prefix diff --git a/core/tests/iter/adapters/chain.rs b/core/tests/iter/adapters/chain.rs index c93510df524cf..1b2c026ee1eb4 100644 --- a/core/tests/iter/adapters/chain.rs +++ b/core/tests/iter/adapters/chain.rs @@ -1,7 +1,8 @@ -use super::*; use core::iter::*; use core::num::NonZero; +use super::*; + #[test] fn test_chain() { let xs = [0, 1, 2, 3, 4, 5]; diff --git a/core/tests/iter/adapters/flatten.rs b/core/tests/iter/adapters/flatten.rs index 1f953f2aa0110..66b7b6cb563e9 100644 --- a/core/tests/iter/adapters/flatten.rs +++ b/core/tests/iter/adapters/flatten.rs @@ -1,8 +1,9 @@ -use super::*; use core::assert_eq; use core::iter::*; use core::num::NonZero; +use super::*; + #[test] fn test_iterator_flatten() { let xs = [0, 3, 6]; diff --git a/core/tests/iter/adapters/map_windows.rs b/core/tests/iter/adapters/map_windows.rs index 6744eff3fa26f..01cebc9b27fd8 100644 --- a/core/tests/iter/adapters/map_windows.rs +++ b/core/tests/iter/adapters/map_windows.rs @@ -1,10 +1,12 @@ -use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering::SeqCst; #[cfg(not(panic = "abort"))] mod drop_checks { //! These tests mainly make sure the elements are correctly dropped. - use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}; + use std::sync::atomic::Ordering::SeqCst; + use std::sync::atomic::{AtomicBool, AtomicUsize}; #[derive(Debug)] struct DropInfo { diff --git a/core/tests/iter/adapters/peekable.rs b/core/tests/iter/adapters/peekable.rs index c1a1c29b609b7..7f4341b8902c8 100644 --- a/core/tests/iter/adapters/peekable.rs +++ b/core/tests/iter/adapters/peekable.rs @@ -1,6 +1,7 @@ -use super::*; use core::iter::*; +use super::*; + #[test] fn test_iterator_peekable() { let xs = vec![0, 1, 2, 3, 4, 5]; diff --git a/core/tests/iter/adapters/zip.rs b/core/tests/iter/adapters/zip.rs index ba54de5822bf7..94b49bac45337 100644 --- a/core/tests/iter/adapters/zip.rs +++ b/core/tests/iter/adapters/zip.rs @@ -1,6 +1,7 @@ -use super::*; use core::iter::*; +use super::*; + #[test] fn test_zip_nth() { let xs = [0, 1, 2, 4, 5]; @@ -239,8 +240,7 @@ fn test_zip_trusted_random_access_composition() { #[test] #[cfg(panic = "unwind")] fn test_zip_trusted_random_access_next_back_drop() { - use std::panic::catch_unwind; - use std::panic::AssertUnwindSafe; + use std::panic::{catch_unwind, AssertUnwindSafe}; let mut counter = 0; diff --git a/core/tests/iter/range.rs b/core/tests/iter/range.rs index e31db0732e094..d5d2b8bf2b047 100644 --- a/core/tests/iter/range.rs +++ b/core/tests/iter/range.rs @@ -1,7 +1,8 @@ -use super::*; use core::ascii::Char as AsciiChar; use core::num::NonZero; +use super::*; + #[test] fn test_range() { assert_eq!((0..5).collect::>(), [0, 1, 2, 3, 4]); diff --git a/core/tests/iter/sources.rs b/core/tests/iter/sources.rs index a15f3a5148f0a..eb8c80dd08724 100644 --- a/core/tests/iter/sources.rs +++ b/core/tests/iter/sources.rs @@ -1,6 +1,7 @@ -use super::*; use core::iter::*; +use super::*; + #[test] fn test_repeat() { let mut it = repeat(42); diff --git a/core/tests/lazy.rs b/core/tests/lazy.rs index 7f7f1f0058801..a3b89f15b3f81 100644 --- a/core/tests/lazy.rs +++ b/core/tests/lazy.rs @@ -1,7 +1,6 @@ -use core::{ - cell::{Cell, LazyCell, OnceCell}, - sync::atomic::{AtomicUsize, Ordering::SeqCst}, -}; +use core::cell::{Cell, LazyCell, OnceCell}; +use core::sync::atomic::AtomicUsize; +use core::sync::atomic::Ordering::SeqCst; #[test] fn once_cell() { diff --git a/core/tests/lib.rs b/core/tests/lib.rs index 83a615fcd8be3..1e336bf96b8fa 100644 --- a/core/tests/lib.rs +++ b/core/tests/lib.rs @@ -1,6 +1,11 @@ +// tidy-alphabetical-start +#![cfg_attr(bootstrap, feature(offset_of_nested))] +#![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] +#![cfg_attr(test, feature(cfg_match))] #![feature(alloc_layout_extra)] #![feature(array_chunks)] #![feature(array_ptr_get)] +#![feature(array_try_from_fn)] #![feature(array_windows)] #![feature(ascii_char)] #![feature(ascii_char_variants)] @@ -9,114 +14,109 @@ #![feature(bigint_helper_methods)] #![feature(cell_update)] #![feature(clone_to_uninit)] -#![feature(const_align_offset)] #![feature(const_align_of_val_raw)] +#![feature(const_align_offset)] +#![feature(const_array_from_ref)] #![feature(const_black_box)] #![feature(const_cell_into_inner)] #![feature(const_hash)] #![feature(const_heap)] #![feature(const_intrinsic_copy)] -#![feature(const_int_from_str)] +#![feature(const_ip)] +#![feature(const_ipv4)] +#![feature(const_ipv6)] +#![feature(const_likely)] #![feature(const_maybe_uninit_as_mut_ptr)] +#![feature(const_mut_refs)] #![feature(const_nonnull_new)] +#![feature(const_option)] +#![feature(const_option_ext)] +#![feature(const_pin)] #![feature(const_pointer_is_aligned)] #![feature(const_ptr_as_ref)] #![feature(const_ptr_write)] +#![feature(const_result)] +#![feature(const_slice_from_ref)] #![feature(const_three_way_compare)] #![feature(const_trait_impl)] -#![feature(const_likely)] #![feature(core_intrinsics)] #![feature(core_io_borrowed_buf)] #![feature(core_private_bignum)] #![feature(core_private_diy_float)] #![feature(dec2flt)] -#![feature(duration_consts_float)] #![feature(duration_constants)] #![feature(duration_constructors)] +#![feature(duration_consts_float)] +#![feature(error_generic_member_access)] #![feature(exact_size_is_empty)] #![feature(extern_types)] -#![feature(freeze)] +#![feature(float_minimum_maximum)] #![feature(flt2dec)] #![feature(fmt_internals)] -#![feature(float_minimum_maximum)] +#![feature(freeze)] #![feature(future_join)] #![feature(generic_assert_internals)] -#![feature(array_try_from_fn)] +#![feature(get_many_mut)] #![feature(hasher_prefixfree_extras)] #![feature(hashmap_internals)] -#![feature(try_find)] -#![feature(is_sorted)] -#![feature(layout_for_ptr)] -#![feature(pattern)] -#![feature(slice_take)] -#![feature(slice_from_ptr_range)] -#![feature(slice_split_once)] -#![feature(split_as_slice)] -#![feature(maybe_uninit_fill)] -#![feature(maybe_uninit_write_slice)] -#![feature(maybe_uninit_uninit_array_transpose)] -#![feature(min_specialization)] -#![feature(noop_waker)] -#![feature(numfmt)] -#![feature(num_midpoint)] -#![feature(offset_of_nested)] -#![feature(isqrt)] -#![feature(step_trait)] -#![feature(str_internals)] -#![feature(std_internals)] -#![feature(test)] -#![feature(trusted_len)] -#![feature(try_blocks)] -#![feature(try_trait_v2)] -#![feature(slice_internals)] -#![feature(slice_partition_dedup)] +#![feature(int_roundings)] #![feature(ip)] +#![feature(is_ascii_octdigit)] +#![feature(isqrt)] #![feature(iter_advance_by)] #![feature(iter_array_chunks)] #![feature(iter_chain)] #![feature(iter_collect_into)] -#![feature(iter_partition_in_place)] #![feature(iter_intersperse)] #![feature(iter_is_partitioned)] +#![feature(iter_map_windows)] #![feature(iter_next_chunk)] #![feature(iter_order_by)] +#![feature(iter_partition_in_place)] #![feature(iter_repeat_n)] #![feature(iterator_try_collect)] #![feature(iterator_try_reduce)] -#![feature(const_ip)] -#![feature(const_ipv4)] -#![feature(const_ipv6)] -#![feature(const_mut_refs)] -#![feature(const_pin)] -#![feature(const_waker)] +#![feature(layout_for_ptr)] +#![feature(maybe_uninit_fill)] +#![feature(maybe_uninit_uninit_array_transpose)] +#![feature(maybe_uninit_write_slice)] +#![feature(min_specialization)] #![feature(never_type)] -#![feature(unwrap_infallible)] +#![feature(noop_waker)] +#![feature(num_midpoint)] +#![feature(numfmt)] +#![feature(pattern)] #![feature(pointer_is_aligned_to)] #![feature(portable_simd)] #![feature(ptr_metadata)] -#![feature(unsized_tuple_coercion)] -#![feature(const_option)] -#![feature(const_option_ext)] -#![feature(const_result)] -#![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] -#![cfg_attr(test, feature(cfg_match))] -#![feature(int_roundings)] +#![feature(slice_from_ptr_range)] +#![feature(slice_internals)] +#![feature(slice_partition_dedup)] +#![feature(slice_split_once)] +#![feature(slice_take)] #![feature(split_array)] +#![feature(split_as_slice)] +#![feature(std_internals)] +#![feature(step_trait)] +#![feature(str_internals)] #![feature(strict_provenance)] #![feature(strict_provenance_atomic_ptr)] +#![feature(test)] +#![feature(trait_upcasting)] +#![feature(trusted_len)] #![feature(trusted_random_access)] +#![feature(try_blocks)] +#![feature(try_find)] +#![feature(try_trait_v2)] +#![feature(unsigned_is_multiple_of)] #![feature(unsize)] -#![feature(const_array_from_ref)] -#![feature(const_slice_from_ref)] +#![feature(unsized_tuple_coercion)] +#![feature(unwrap_infallible)] #![feature(waker_getters)] -#![feature(error_generic_member_access)] -#![feature(trait_upcasting)] -#![feature(is_ascii_octdigit)] -#![feature(get_many_mut)] -#![feature(iter_map_windows)] +// tidy-alphabetical-end #![allow(internal_features)] -#![deny(unsafe_op_in_unsafe_fn)] #![deny(fuzzy_provenance_casts)] +#![deny(unsafe_op_in_unsafe_fn)] mod alloc; mod any; @@ -132,6 +132,7 @@ mod clone; mod cmp; mod const_ptr; mod convert; +mod ffi; mod fmt; mod future; mod hash; diff --git a/core/tests/mem.rs b/core/tests/mem.rs index cc73391630760..b7eee10ec3f9c 100644 --- a/core/tests/mem.rs +++ b/core/tests/mem.rs @@ -1,6 +1,5 @@ use core::mem::*; use core::ptr; - #[cfg(panic = "unwind")] use std::rc::Rc; diff --git a/core/tests/net/ip_addr.rs b/core/tests/net/ip_addr.rs index f9b351ef1980b..a10b51c550d5b 100644 --- a/core/tests/net/ip_addr.rs +++ b/core/tests/net/ip_addr.rs @@ -1,9 +1,10 @@ -use super::{sa4, sa6}; use core::net::{ IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope, SocketAddr, SocketAddrV4, SocketAddrV6, }; use core::str::FromStr; +use super::{sa4, sa6}; + #[test] fn test_from_str_ipv4() { assert_eq!(Ok(Ipv4Addr::new(127, 0, 0, 1)), "127.0.0.1".parse()); diff --git a/core/tests/num/flt2dec/mod.rs b/core/tests/num/flt2dec/mod.rs index 83e2707b57e8b..070a53edc2e0f 100644 --- a/core/tests/num/flt2dec/mod.rs +++ b/core/tests/num/flt2dec/mod.rs @@ -1,12 +1,10 @@ -use std::mem::MaybeUninit; -use std::{fmt, str}; - -use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded}; -use core::num::flt2dec::{round_up, Sign, MAX_SIG_DIGITS}; use core::num::flt2dec::{ - to_exact_exp_str, to_exact_fixed_str, to_shortest_exp_str, to_shortest_str, + decode, round_up, to_exact_exp_str, to_exact_fixed_str, to_shortest_exp_str, to_shortest_str, + DecodableFloat, Decoded, FullDecoded, Sign, MAX_SIG_DIGITS, }; use core::num::fmt::{Formatted, Part}; +use std::mem::MaybeUninit; +use std::{fmt, str}; mod estimator; mod strategy { diff --git a/core/tests/num/flt2dec/random.rs b/core/tests/num/flt2dec/random.rs index 0084c1c814e2d..4817a66638391 100644 --- a/core/tests/num/flt2dec/random.rs +++ b/core/tests/num/flt2dec/random.rs @@ -1,13 +1,10 @@ #![cfg(not(target_arch = "wasm32"))] +use core::num::flt2dec::strategy::grisu::{format_exact_opt, format_shortest_opt}; +use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded, MAX_SIG_DIGITS}; use std::mem::MaybeUninit; use std::str; -use core::num::flt2dec::strategy::grisu::format_exact_opt; -use core::num::flt2dec::strategy::grisu::format_shortest_opt; -use core::num::flt2dec::MAX_SIG_DIGITS; -use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded}; - use rand::distributions::{Distribution, Uniform}; pub fn decode_finite(v: T) -> Decoded { diff --git a/core/tests/num/flt2dec/strategy/dragon.rs b/core/tests/num/flt2dec/strategy/dragon.rs index fc2e724a20c7c..be25fee3f6c71 100644 --- a/core/tests/num/flt2dec/strategy/dragon.rs +++ b/core/tests/num/flt2dec/strategy/dragon.rs @@ -1,7 +1,8 @@ -use super::super::*; use core::num::bignum::Big32x40 as Big; use core::num::flt2dec::strategy::dragon::*; +use super::super::*; + #[test] fn test_mul_pow10() { let mut prevpow10 = Big::from_small(1); diff --git a/core/tests/num/flt2dec/strategy/grisu.rs b/core/tests/num/flt2dec/strategy/grisu.rs index b59a3b9b72d3b..9b2f0453de73e 100644 --- a/core/tests/num/flt2dec/strategy/grisu.rs +++ b/core/tests/num/flt2dec/strategy/grisu.rs @@ -1,6 +1,7 @@ -use super::super::*; use core::num::flt2dec::strategy::grisu::*; +use super::super::*; + #[test] #[cfg_attr(miri, ignore)] // Miri is too slow fn test_cached_power() { diff --git a/core/tests/num/uint_macros.rs b/core/tests/num/uint_macros.rs index 955440647eb98..d009ad89d5ce7 100644 --- a/core/tests/num/uint_macros.rs +++ b/core/tests/num/uint_macros.rs @@ -260,6 +260,14 @@ macro_rules! uint_module { assert_eq!(MAX.checked_next_multiple_of(2), None); } + #[test] + fn test_is_next_multiple_of() { + assert!((12 as $T).is_multiple_of(4)); + assert!(!(12 as $T).is_multiple_of(5)); + assert!((0 as $T).is_multiple_of(0)); + assert!(!(12 as $T).is_multiple_of(0)); + } + #[test] fn test_carrying_add() { assert_eq!($T::MAX.carrying_add(1, false), (0, true)); diff --git a/core/tests/ops.rs b/core/tests/ops.rs index 0c81cba35b3df..2ee0abd399bb6 100644 --- a/core/tests/ops.rs +++ b/core/tests/ops.rs @@ -1,7 +1,8 @@ mod control_flow; -use core::ops::{Bound, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive}; -use core::ops::{Deref, DerefMut}; +use core::ops::{ + Bound, Deref, DerefMut, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, +}; // Test the Range structs and syntax. diff --git a/core/tests/pin_macro.rs b/core/tests/pin_macro.rs index 57485ef3974cc..36c6972515a96 100644 --- a/core/tests/pin_macro.rs +++ b/core/tests/pin_macro.rs @@ -1,10 +1,8 @@ // edition:2021 -use core::{ - marker::PhantomPinned, - mem::{drop as stuff, transmute}, - pin::{pin, Pin}, -}; +use core::marker::PhantomPinned; +use core::mem::{drop as stuff, transmute}; +use core::pin::{pin, Pin}; #[test] fn basic() { diff --git a/core/tests/ptr.rs b/core/tests/ptr.rs index e3830165eda61..bc1940ebf32b5 100644 --- a/core/tests/ptr.rs +++ b/core/tests/ptr.rs @@ -1050,7 +1050,7 @@ fn nonnull_tagged_pointer_with_provenance() { /// A mask for the non-data-carrying bits of the address. pub const ADDRESS_MASK: usize = usize::MAX << Self::NUM_BITS; - /// Create a new tagged pointer from a possibly null pointer. + /// Creates a new tagged pointer from a possibly null pointer. pub fn new(pointer: *mut T) -> Option> { Some(TaggedPointer(NonNull::new(pointer)?)) } diff --git a/core/tests/result.rs b/core/tests/result.rs index 00a6fd75b4f46..90ec844bc5771 100644 --- a/core/tests/result.rs +++ b/core/tests/result.rs @@ -410,7 +410,8 @@ fn result_opt_conversions() { #[test] fn result_try_trait_v2_branch() { use core::num::NonZero; - use core::ops::{ControlFlow::*, Try}; + use core::ops::ControlFlow::*; + use core::ops::Try; assert_eq!(Ok::(4).branch(), Continue(4)); assert_eq!(Err::(4).branch(), Break(Err(4))); diff --git a/core/tests/slice.rs b/core/tests/slice.rs index 4cbbabb672ba0..cdefb5d3eb201 100644 --- a/core/tests/slice.rs +++ b/core/tests/slice.rs @@ -69,13 +69,13 @@ fn test_binary_search() { assert_eq!(b.binary_search(&8), Err(5)); let b = [(); usize::MAX]; - assert_eq!(b.binary_search(&()), Ok(usize::MAX / 2)); + assert_eq!(b.binary_search(&()), Ok(usize::MAX - 1)); } #[test] fn test_binary_search_by_overflow() { let b = [(); usize::MAX]; - assert_eq!(b.binary_search_by(|_| Ordering::Equal), Ok(usize::MAX / 2)); + assert_eq!(b.binary_search_by(|_| Ordering::Equal), Ok(usize::MAX - 1)); assert_eq!(b.binary_search_by(|_| Ordering::Greater), Err(0)); assert_eq!(b.binary_search_by(|_| Ordering::Less), Err(usize::MAX)); } @@ -87,13 +87,13 @@ fn test_binary_search_implementation_details() { let b = [1, 1, 2, 2, 3, 3, 3]; assert_eq!(b.binary_search(&1), Ok(1)); assert_eq!(b.binary_search(&2), Ok(3)); - assert_eq!(b.binary_search(&3), Ok(5)); + assert_eq!(b.binary_search(&3), Ok(6)); let b = [1, 1, 1, 1, 1, 3, 3, 3, 3]; assert_eq!(b.binary_search(&1), Ok(4)); - assert_eq!(b.binary_search(&3), Ok(7)); + assert_eq!(b.binary_search(&3), Ok(8)); let b = [1, 1, 1, 1, 3, 3, 3, 3, 3]; - assert_eq!(b.binary_search(&1), Ok(2)); - assert_eq!(b.binary_search(&3), Ok(4)); + assert_eq!(b.binary_search(&1), Ok(3)); + assert_eq!(b.binary_search(&3), Ok(8)); } #[test] @@ -1856,6 +1856,7 @@ fn sort_unstable() { #[cfg_attr(miri, ignore)] // Miri is too slow fn select_nth_unstable() { use core::cmp::Ordering::{Equal, Greater, Less}; + use rand::seq::SliceRandom; use rand::Rng; diff --git a/core/tests/waker.rs b/core/tests/waker.rs index 2c66e0d7ad3a4..361e900e69562 100644 --- a/core/tests/waker.rs +++ b/core/tests/waker.rs @@ -20,3 +20,33 @@ static WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new( |_| {}, |_| {}, ); + +// https://github.com/rust-lang/rust/issues/102012#issuecomment-1915282956 +mod nop_waker { + use core::future::{ready, Future}; + use core::pin::Pin; + use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; + + const NOP_RAWWAKER: RawWaker = { + fn nop(_: *const ()) {} + const VTAB: RawWakerVTable = RawWakerVTable::new(|_| NOP_RAWWAKER, nop, nop, nop); + RawWaker::new(&() as *const (), &VTAB) + }; + + const NOP_WAKER: &Waker = &unsafe { Waker::from_raw(NOP_RAWWAKER) }; + + const NOP_CONTEXT: Context<'static> = Context::from_waker(NOP_WAKER); + + fn poll_once(f: &mut F) -> Poll + where + F: Future + ?Sized + Unpin, + { + let mut cx = NOP_CONTEXT; + Pin::new(f).as_mut().poll(&mut cx) + } + + #[test] + fn test_const_waker() { + assert_eq!(poll_once(&mut ready(1)), Poll::Ready(1)); + } +} diff --git a/panic_abort/src/lib.rs b/panic_abort/src/lib.rs index 14ba4af2bb575..dc2b42bb90ae8 100644 --- a/panic_abort/src/lib.rs +++ b/panic_abort/src/lib.rs @@ -14,7 +14,6 @@ #![feature(std_internals)] #![feature(staged_api)] #![feature(rustc_attrs)] -#![cfg_attr(bootstrap, feature(c_unwind))] #![allow(internal_features)] #[cfg(target_os = "android")] diff --git a/panic_unwind/src/emcc.rs b/panic_unwind/src/emcc.rs index fed4c52e83c5f..86a43184fb529 100644 --- a/panic_unwind/src/emcc.rs +++ b/panic_unwind/src/emcc.rs @@ -8,10 +8,9 @@ use alloc::boxed::Box; use core::any::Any; -use core::intrinsics; -use core::mem; -use core::ptr; use core::sync::atomic::{AtomicBool, Ordering}; +use core::{intrinsics, mem, ptr}; + use unwind as uw; // This matches the layout of std::type_info in C++ diff --git a/panic_unwind/src/lib.rs b/panic_unwind/src/lib.rs index 77abb9125f651..2d174f4b1a4a2 100644 --- a/panic_unwind/src/lib.rs +++ b/panic_unwind/src/lib.rs @@ -24,7 +24,6 @@ #![feature(rustc_attrs)] #![panic_runtime] #![feature(panic_runtime)] -#![cfg_attr(bootstrap, feature(c_unwind))] // `real_imp` is unused with Miri, so silence warnings. #![cfg_attr(miri, allow(dead_code))] #![allow(internal_features)] diff --git a/panic_unwind/src/seh.rs b/panic_unwind/src/seh.rs index 04c3d3bf9c359..82c248c5a7ba1 100644 --- a/panic_unwind/src/seh.rs +++ b/panic_unwind/src/seh.rs @@ -157,7 +157,10 @@ mod imp { // going to be cross-lang LTOed anyway. However, using expose is shorter and // requires less unsafe. let addr: usize = ptr.expose_provenance(); + #[cfg(bootstrap)] let image_base = unsafe { addr_of!(__ImageBase) }.addr(); + #[cfg(not(bootstrap))] + let image_base = addr_of!(__ImageBase).addr(); let offset: usize = addr - image_base; Self(offset as u32) } @@ -250,7 +253,10 @@ extern "C" { // This is fine since the MSVC runtime uses string comparison on the type name // to match TypeDescriptors rather than pointer equality. static mut TYPE_DESCRIPTOR: _TypeDescriptor = _TypeDescriptor { + #[cfg(bootstrap)] pVFTable: unsafe { addr_of!(TYPE_INFO_VTABLE) } as *const _, + #[cfg(not(bootstrap))] + pVFTable: addr_of!(TYPE_INFO_VTABLE) as *const _, spare: core::ptr::null_mut(), name: TYPE_NAME, }; diff --git a/portable-simd/crates/core_simd/src/masks.rs b/portable-simd/crates/core_simd/src/masks.rs index e6e27c76a5e99..04de3a968276d 100644 --- a/portable-simd/crates/core_simd/src/masks.rs +++ b/portable-simd/crates/core_simd/src/masks.rs @@ -137,7 +137,7 @@ where T: MaskElement, LaneCount: SupportedLaneCount, { - /// Construct a mask by setting all elements to the given value. + /// Constructs a mask by setting all elements to the given value. #[inline] pub fn splat(value: bool) -> Self { Self(mask_impl::Mask::splat(value)) @@ -288,7 +288,7 @@ where self.0.all() } - /// Create a bitmask from a mask. + /// Creates a bitmask from a mask. /// /// Each bit is set if the corresponding element in the mask is `true`. /// If the mask contains more than 64 elements, the bitmask is truncated to the first 64. @@ -298,7 +298,7 @@ where self.0.to_bitmask_integer() } - /// Create a mask from a bitmask. + /// Creates a mask from a bitmask. /// /// For each bit, if it is set, the corresponding element in the mask is set to `true`. /// If the mask contains more than 64 elements, the remainder are set to `false`. @@ -308,7 +308,7 @@ where Self(mask_impl::Mask::from_bitmask_integer(bitmask)) } - /// Create a bitmask vector from a mask. + /// Creates a bitmask vector from a mask. /// /// Each bit is set if the corresponding element in the mask is `true`. /// The remaining bits are unset. @@ -328,7 +328,7 @@ where self.0.to_bitmask_vector() } - /// Create a mask from a bitmask vector. + /// Creates a mask from a bitmask vector. /// /// For each bit, if it is set, the corresponding element in the mask is set to `true`. /// @@ -350,7 +350,7 @@ where Self(mask_impl::Mask::from_bitmask_vector(bitmask)) } - /// Find the index of the first set element. + /// Finds the index of the first set element. /// /// ``` /// # #![feature(portable_simd)] diff --git a/portable-simd/crates/core_simd/src/simd/ptr/const_ptr.rs b/portable-simd/crates/core_simd/src/simd/ptr/const_ptr.rs index cbffbc564cfed..be635ea640b86 100644 --- a/portable-simd/crates/core_simd/src/simd/ptr/const_ptr.rs +++ b/portable-simd/crates/core_simd/src/simd/ptr/const_ptr.rs @@ -54,7 +54,7 @@ pub trait SimdConstPtr: Copy + Sealed { /// [`Self::with_exposed_provenance`] and returns the "address" portion. fn expose_provenance(self) -> Self::Usize; - /// Convert an address back to a pointer, picking up a previously "exposed" provenance. + /// Converts an address back to a pointer, picking up a previously "exposed" provenance. /// /// Equivalent to calling [`core::ptr::with_exposed_provenance`] on each element. fn with_exposed_provenance(addr: Self::Usize) -> Self; diff --git a/portable-simd/crates/core_simd/src/simd/ptr/mut_ptr.rs b/portable-simd/crates/core_simd/src/simd/ptr/mut_ptr.rs index 6bc6ca3ac42dc..f6823a949e32a 100644 --- a/portable-simd/crates/core_simd/src/simd/ptr/mut_ptr.rs +++ b/portable-simd/crates/core_simd/src/simd/ptr/mut_ptr.rs @@ -51,7 +51,7 @@ pub trait SimdMutPtr: Copy + Sealed { /// [`Self::with_exposed_provenance`] and returns the "address" portion. fn expose_provenance(self) -> Self::Usize; - /// Convert an address back to a pointer, picking up a previously "exposed" provenance. + /// Converts an address back to a pointer, picking up a previously "exposed" provenance. /// /// Equivalent to calling [`core::ptr::with_exposed_provenance_mut`] on each element. fn with_exposed_provenance(addr: Self::Usize) -> Self; diff --git a/portable-simd/crates/core_simd/src/swizzle.rs b/portable-simd/crates/core_simd/src/swizzle.rs index 71110bb282018..2f4f777b20e29 100644 --- a/portable-simd/crates/core_simd/src/swizzle.rs +++ b/portable-simd/crates/core_simd/src/swizzle.rs @@ -69,12 +69,12 @@ pub macro simd_swizzle { } } -/// Create a vector from the elements of another vector. +/// Creates a vector from the elements of another vector. pub trait Swizzle { /// Map from the elements of the input vector to the output vector. const INDEX: [usize; N]; - /// Create a new vector from the elements of `vector`. + /// Creates a new vector from the elements of `vector`. /// /// Lane `i` of the output is `vector[Self::INDEX[i]]`. #[inline] @@ -109,7 +109,7 @@ pub trait Swizzle { } } - /// Create a new vector from the elements of `first` and `second`. + /// Creates a new vector from the elements of `first` and `second`. /// /// Lane `i` of the output is `concat[Self::INDEX[i]]`, where `concat` is the concatenation of /// `first` and `second`. @@ -145,7 +145,7 @@ pub trait Swizzle { } } - /// Create a new mask from the elements of `mask`. + /// Creates a new mask from the elements of `mask`. /// /// Element `i` of the output is `concat[Self::INDEX[i]]`, where `concat` is the concatenation of /// `first` and `second`. @@ -161,7 +161,7 @@ pub trait Swizzle { unsafe { Mask::from_int_unchecked(Self::swizzle(mask.to_int())) } } - /// Create a new mask from the elements of `first` and `second`. + /// Creates a new mask from the elements of `first` and `second`. /// /// Element `i` of the output is `concat[Self::INDEX[i]]`, where `concat` is the concatenation of /// `first` and `second`. diff --git a/portable-simd/crates/core_simd/src/to_bytes.rs b/portable-simd/crates/core_simd/src/to_bytes.rs index 222526c4ab30a..4833ea9e11362 100644 --- a/portable-simd/crates/core_simd/src/to_bytes.rs +++ b/portable-simd/crates/core_simd/src/to_bytes.rs @@ -10,7 +10,7 @@ mod sealed { } use sealed::Sealed; -/// Convert SIMD vectors to vectors of bytes +/// Converts SIMD vectors to vectors of bytes pub trait ToBytes: Sealed { /// This type, reinterpreted as bytes. type Bytes: Copy @@ -22,26 +22,26 @@ pub trait ToBytes: Sealed { + SimdUint + 'static; - /// Return the memory representation of this integer as a byte array in native byte + /// Returns the memory representation of this integer as a byte array in native byte /// order. fn to_ne_bytes(self) -> Self::Bytes; - /// Return the memory representation of this integer as a byte array in big-endian + /// Returns the memory representation of this integer as a byte array in big-endian /// (network) byte order. fn to_be_bytes(self) -> Self::Bytes; - /// Return the memory representation of this integer as a byte array in little-endian + /// Returns the memory representation of this integer as a byte array in little-endian /// byte order. fn to_le_bytes(self) -> Self::Bytes; - /// Create a native endian integer value from its memory representation as a byte array + /// Creates a native endian integer value from its memory representation as a byte array /// in native endianness. fn from_ne_bytes(bytes: Self::Bytes) -> Self; - /// Create an integer value from its representation as a byte array in big endian. + /// Creates an integer value from its representation as a byte array in big endian. fn from_be_bytes(bytes: Self::Bytes) -> Self; - /// Create an integer value from its representation as a byte array in little endian. + /// Creates an integer value from its representation as a byte array in little endian. fn from_le_bytes(bytes: Self::Bytes) -> Self; } diff --git a/portable-simd/crates/core_simd/src/vector.rs b/portable-simd/crates/core_simd/src/vector.rs index 8dbdfc0e1fe03..3e23916914963 100644 --- a/portable-simd/crates/core_simd/src/vector.rs +++ b/portable-simd/crates/core_simd/src/vector.rs @@ -187,7 +187,7 @@ where unsafe { &mut *(self as *mut Self as *mut [T; N]) } } - /// Load a vector from an array of `T`. + /// Loads a vector from an array of `T`. /// /// This function is necessary since `repr(simd)` has padding for non-power-of-2 vectors (at the time of writing). /// With padding, `read_unaligned` will read past the end of an array of N elements. @@ -567,7 +567,7 @@ where unsafe { Self::gather_select_ptr(ptrs, enable, or) } } - /// Read elementwise from pointers into a SIMD vector. + /// Reads elementwise from pointers into a SIMD vector. /// /// # Safety /// @@ -808,7 +808,7 @@ where } } - /// Write pointers elementwise into a SIMD vector. + /// Writes pointers elementwise into a SIMD vector. /// /// # Safety /// diff --git a/proc_macro/src/bridge/arena.rs b/proc_macro/src/bridge/arena.rs index f81f2152cd046..1d5986093c8a4 100644 --- a/proc_macro/src/bridge/arena.rs +++ b/proc_macro/src/bridge/arena.rs @@ -5,12 +5,9 @@ //! being built at the same time as `std`. use std::cell::{Cell, RefCell}; -use std::cmp; use std::mem::MaybeUninit; use std::ops::Range; -use std::ptr; -use std::slice; -use std::str; +use std::{cmp, ptr, slice, str}; // The arenas start with PAGE-sized chunks, and then each new chunk is twice as // big as its predecessor, up until we reach HUGE_PAGE-sized chunks, whereupon diff --git a/proc_macro/src/bridge/buffer.rs b/proc_macro/src/bridge/buffer.rs index 149767bf70521..78fcd1999b2f3 100644 --- a/proc_macro/src/bridge/buffer.rs +++ b/proc_macro/src/bridge/buffer.rs @@ -1,7 +1,7 @@ //! Buffer management for same-process client<->server communication. use std::io::{self, Write}; -use std::mem; +use std::mem::{self, ManuallyDrop}; use std::ops::{Deref, DerefMut}; use std::slice; @@ -129,17 +129,16 @@ impl Drop for Buffer { } impl From> for Buffer { - fn from(mut v: Vec) -> Self { + fn from(v: Vec) -> Self { + let mut v = ManuallyDrop::new(v); let (data, len, capacity) = (v.as_mut_ptr(), v.len(), v.capacity()); - mem::forget(v); // This utility function is nested in here because it can *only* // be safely called on `Buffer`s created by *this* `proc_macro`. fn to_vec(b: Buffer) -> Vec { unsafe { - let Buffer { data, len, capacity, .. } = b; - mem::forget(b); - Vec::from_raw_parts(data, len, capacity) + let b = ManuallyDrop::new(b); + Vec::from_raw_parts(b.data, b.len, b.capacity) } } diff --git a/proc_macro/src/bridge/client.rs b/proc_macro/src/bridge/client.rs index faca745e56f74..5a1086527a127 100644 --- a/proc_macro/src/bridge/client.rs +++ b/proc_macro/src/bridge/client.rs @@ -1,11 +1,11 @@ //! Client-side types. -use super::*; - use std::cell::RefCell; use std::marker::PhantomData; use std::sync::atomic::AtomicU32; +use super::*; + macro_rules! define_client_handles { ( 'owned: $($oty:ident,)* @@ -51,9 +51,7 @@ macro_rules! define_client_handles { impl Encode for $oty { fn encode(self, w: &mut Writer, s: &mut S) { - let handle = self.handle; - mem::forget(self); - handle.encode(w, s); + mem::ManuallyDrop::new(self).handle.encode(w, s); } } @@ -192,10 +190,11 @@ impl<'a> !Sync for Bridge<'a> {} #[allow(unsafe_code)] mod state { - use super::Bridge; use std::cell::{Cell, RefCell}; use std::ptr; + use super::Bridge; + thread_local! { static BRIDGE_STATE: Cell<*const ()> = const { Cell::new(ptr::null()) }; } diff --git a/proc_macro/src/bridge/fxhash.rs b/proc_macro/src/bridge/fxhash.rs index 9fb79eabd0556..74a41451825ff 100644 --- a/proc_macro/src/bridge/fxhash.rs +++ b/proc_macro/src/bridge/fxhash.rs @@ -5,8 +5,7 @@ //! on the `rustc_hash` crate. use std::collections::HashMap; -use std::hash::BuildHasherDefault; -use std::hash::Hasher; +use std::hash::{BuildHasherDefault, Hasher}; use std::ops::BitXor; /// Type alias for a hashmap using the `fx` hash algorithm. diff --git a/proc_macro/src/bridge/mod.rs b/proc_macro/src/bridge/mod.rs index 8553e8d5e4fd6..03c3e697cfe2b 100644 --- a/proc_macro/src/bridge/mod.rs +++ b/proc_macro/src/bridge/mod.rs @@ -8,16 +8,12 @@ #![deny(unsafe_code)] -use crate::{Delimiter, Level, Spacing}; -use std::fmt; use std::hash::Hash; -use std::marker; -use std::mem; -use std::ops::Bound; -use std::ops::Range; -use std::panic; +use std::ops::{Bound, Range}; use std::sync::Once; -use std::thread; +use std::{fmt, marker, mem, panic, thread}; + +use crate::{Delimiter, Level, Spacing}; /// Higher-order macro describing the server RPC API, allowing automatic /// generation of type-safe Rust APIs, both client-side and server-side. diff --git a/proc_macro/src/bridge/server.rs b/proc_macro/src/bridge/server.rs index 0dbd4bac85c9f..692b6038a3872 100644 --- a/proc_macro/src/bridge/server.rs +++ b/proc_macro/src/bridge/server.rs @@ -1,10 +1,10 @@ //! Server-side traits. -use super::*; - use std::cell::Cell; use std::marker::PhantomData; +use super::*; + macro_rules! define_server_handles { ( 'owned: $($oty:ident,)* @@ -350,7 +350,7 @@ where /// A message pipe used for communicating between server and client threads. pub trait MessagePipe: Sized { - /// Create a new pair of endpoints for the message pipe. + /// Creates a new pair of endpoints for the message pipe. fn new() -> (Self, Self); /// Send a message to the other endpoint of this pipe. diff --git a/proc_macro/src/bridge/symbol.rs b/proc_macro/src/bridge/symbol.rs index 86ce2cc189588..37aaee6b21553 100644 --- a/proc_macro/src/bridge/symbol.rs +++ b/proc_macro/src/bridge/symbol.rs @@ -28,7 +28,7 @@ impl Symbol { INTERNER.with_borrow_mut(|i| i.intern(string)) } - /// Create a new `Symbol` for an identifier. + /// Creates a new `Symbol` for an identifier. /// /// Validates and normalizes before converting it to a symbol. pub(crate) fn new_ident(string: &str, is_raw: bool) -> Self { @@ -63,7 +63,7 @@ impl Symbol { INTERNER.with_borrow_mut(|i| i.clear()); } - /// Check if the ident is a valid ASCII identifier. + /// Checks if the ident is a valid ASCII identifier. /// /// This is a short-circuit which is cheap to implement within the /// proc-macro client to avoid RPC when creating simple idents, but may @@ -177,7 +177,7 @@ impl Interner { name } - /// Read a symbol's value from the store while it is held. + /// Reads a symbol's value from the store while it is held. fn get(&self, symbol: Symbol) -> &str { // NOTE: Subtract out the offset which was added to make the symbol // nonzero and prevent symbol name re-use. diff --git a/proc_macro/src/lib.rs b/proc_macro/src/lib.rs index 581d7e3efe373..c271ac1870624 100644 --- a/proc_macro/src/lib.rs +++ b/proc_macro/src/lib.rs @@ -37,6 +37,7 @@ #![recursion_limit = "256"] #![allow(internal_features)] #![deny(ffi_unwind_calls)] +#![warn(rustdoc::unescaped_backticks)] #[unstable(feature = "proc_macro_internals", issue = "27812")] #[doc(hidden)] @@ -45,16 +46,17 @@ pub mod bridge; mod diagnostic; mod escape; -#[unstable(feature = "proc_macro_diagnostic", issue = "54140")] -pub use diagnostic::{Diagnostic, Level, MultiSpan}; - -use crate::escape::{escape_bytes, EscapeOptions}; use std::ffi::CStr; use std::ops::{Range, RangeBounds}; use std::path::PathBuf; use std::str::FromStr; use std::{error, fmt}; +#[unstable(feature = "proc_macro_diagnostic", issue = "54140")] +pub use diagnostic::{Diagnostic, Level, MultiSpan}; + +use crate::escape::{escape_bytes, EscapeOptions}; + /// Determines whether proc_macro has been made accessible to the currently /// running program. /// @@ -1544,10 +1546,10 @@ impl fmt::Debug for Literal { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Literal") // format the kind on one line even in {:#?} mode - .field("kind", &format_args!("{:?}", &self.0.kind)) + .field("kind", &format_args!("{:?}", self.0.kind)) .field("symbol", &self.0.symbol) // format `Some("...")` on one line even in {:#?} mode - .field("suffix", &format_args!("{:?}", &self.0.suffix)) + .field("suffix", &format_args!("{:?}", self.0.suffix)) .field("span", &self.0.span) .finish() } diff --git a/rtstartup/rsbegin.rs b/rtstartup/rsbegin.rs index 14bce2bbeee2b..9a3d95bd8ddfb 100644 --- a/rtstartup/rsbegin.rs +++ b/rtstartup/rsbegin.rs @@ -29,6 +29,8 @@ trait Copy {} #[lang = "freeze"] auto trait Freeze {} +impl Copy for *mut T {} + #[lang = "drop_in_place"] #[inline] #[allow(unconditional_recursion)] diff --git a/rtstartup/rsend.rs b/rtstartup/rsend.rs index 714643c83866f..2514eb0034402 100644 --- a/rtstartup/rsend.rs +++ b/rtstartup/rsend.rs @@ -17,6 +17,8 @@ trait Copy {} #[lang = "freeze"] auto trait Freeze {} +impl Copy for *mut T {} + #[lang = "drop_in_place"] #[inline] #[allow(unconditional_recursion)] diff --git a/std/Cargo.toml b/std/Cargo.toml index b991b1cf22dd8..fe601855cc1e7 100644 --- a/std/Cargo.toml +++ b/std/Cargo.toml @@ -17,11 +17,15 @@ cfg-if = { version = "1.0", features = ['rustc-dep-of-std'] } panic_unwind = { path = "../panic_unwind", optional = true } panic_abort = { path = "../panic_abort" } core = { path = "../core", public = true } -compiler_builtins = { version = "0.1.105" } +compiler_builtins = { version = "0.1.114" } profiler_builtins = { path = "../profiler_builtins", optional = true } unwind = { path = "../unwind" } -hashbrown = { version = "0.14", default-features = false, features = ['rustc-dep-of-std'] } -std_detect = { path = "../stdarch/crates/std_detect", default-features = false, features = ['rustc-dep-of-std'] } +hashbrown = { version = "0.14", default-features = false, features = [ + 'rustc-dep-of-std', +] } +std_detect = { path = "../stdarch/crates/std_detect", default-features = false, features = [ + 'rustc-dep-of-std', +] } # Dependencies of the `backtrace` crate rustc-demangle = { version = "0.1.24", features = ['rustc-dep-of-std'] } @@ -31,13 +35,27 @@ miniz_oxide = { version = "0.7.0", optional = true, default-features = false } addr2line = { version = "0.22.0", optional = true, default-features = false } [target.'cfg(not(all(windows, target_env = "msvc")))'.dependencies] -libc = { version = "0.2.153", default-features = false, features = ['rustc-dep-of-std'], public = true } +libc = { version = "0.2.153", default-features = false, features = [ + 'rustc-dep-of-std', +], public = true } [target.'cfg(all(not(target_os = "aix"), not(all(windows, target_env = "msvc", not(target_vendor = "uwp")))))'.dependencies] -object = { version = "0.36.0", default-features = false, optional = true, features = ['read_core', 'elf', 'macho', 'pe', 'unaligned', 'archive'] } +object = { version = "0.36.0", default-features = false, optional = true, features = [ + 'read_core', + 'elf', + 'macho', + 'pe', + 'unaligned', + 'archive', +] } [target.'cfg(target_os = "aix")'.dependencies] -object = { version = "0.36.0", default-features = false, optional = true, features = ['read_core', 'xcoff', 'unaligned', 'archive'] } +object = { version = "0.36.0", default-features = false, optional = true, features = [ + 'read_core', + 'xcoff', + 'unaligned', + 'archive', +] } [dev-dependencies] rand = { version = "0.8.5", default-features = false, features = ["alloc"] } @@ -47,23 +65,29 @@ rand_xorshift = "0.3.0" dlmalloc = { version = "0.2.4", features = ['rustc-dep-of-std'] } [target.x86_64-fortanix-unknown-sgx.dependencies] -fortanix-sgx-abi = { version = "0.5.0", features = ['rustc-dep-of-std'], public = true } +fortanix-sgx-abi = { version = "0.5.0", features = [ + 'rustc-dep-of-std', +], public = true } [target.'cfg(target_os = "hermit")'.dependencies] -hermit-abi = { version = "0.4.0", features = ['rustc-dep-of-std'], public = true } +hermit-abi = { version = "0.4.0", features = [ + 'rustc-dep-of-std', +], public = true } [target.'cfg(target_os = "wasi")'.dependencies] -wasi = { version = "0.11.0", features = ['rustc-dep-of-std'], default-features = false } +wasi = { version = "0.11.0", features = [ + 'rustc-dep-of-std', +], default-features = false } [target.'cfg(target_os = "uefi")'.dependencies] -r-efi = { version = "4.2.0", features = ['rustc-dep-of-std'] } +r-efi = { version = "4.5.0", features = ['rustc-dep-of-std'] } r-efi-alloc = { version = "1.0.0", features = ['rustc-dep-of-std'] } [features] backtrace = [ - 'addr2line/rustc-dep-of-std', - 'object/rustc-dep-of-std', - 'miniz_oxide/rustc-dep-of-std', + 'addr2line/rustc-dep-of-std', + 'object/rustc-dep-of-std', + 'miniz_oxide/rustc-dep-of-std', ] panic-unwind = ["panic_unwind"] @@ -71,13 +95,16 @@ profiler = ["profiler_builtins"] compiler-builtins-c = ["alloc/compiler-builtins-c"] compiler-builtins-mem = ["alloc/compiler-builtins-mem"] compiler-builtins-no-asm = ["alloc/compiler-builtins-no-asm"] +compiler-builtins-no-f16-f128 = ["alloc/compiler-builtins-no-f16-f128"] compiler-builtins-mangled-names = ["alloc/compiler-builtins-mangled-names"] -compiler-builtins-weak-intrinsics = ["alloc/compiler-builtins-weak-intrinsics"] llvm-libunwind = ["unwind/llvm-libunwind"] system-llvm-libunwind = ["unwind/system-llvm-libunwind"] # Make panics and failed asserts immediately abort without formatting any message -panic_immediate_abort = ["core/panic_immediate_abort", "alloc/panic_immediate_abort"] +panic_immediate_abort = [ + "core/panic_immediate_abort", + "alloc/panic_immediate_abort", +] # Choose algorithms that are optimized for binary size instead of runtime performance optimize_for_size = ["core/optimize_for_size", "alloc/optimize_for_size"] @@ -97,6 +124,11 @@ threads = 125 # Maximum heap size heap_size = 0x8000000 +[[test]] +name = "pipe-subprocess" +path = "tests/pipe_subprocess.rs" +harness = false + [[bench]] name = "stdbenches" path = "benches/lib.rs" diff --git a/std/benches/hash/map.rs b/std/benches/hash/map.rs index bf646cbae47db..d6023c8212b89 100644 --- a/std/benches/hash/map.rs +++ b/std/benches/hash/map.rs @@ -1,6 +1,7 @@ #![cfg(test)] use std::collections::HashMap; + use test::Bencher; #[bench] diff --git a/std/benches/hash/set_ops.rs b/std/benches/hash/set_ops.rs index 1a4c4a66ee9e0..b97e3b450850e 100644 --- a/std/benches/hash/set_ops.rs +++ b/std/benches/hash/set_ops.rs @@ -1,4 +1,5 @@ use std::collections::HashSet; + use test::Bencher; #[bench] diff --git a/std/build.rs b/std/build.rs index c542ba81eedc1..9b58dd53ba20a 100644 --- a/std/build.rs +++ b/std/build.rs @@ -94,7 +94,7 @@ fn main() { // Unsupported ("arm64ec", _) => false, // MinGW ABI bugs - ("x86", "windows") => false, + ("x86_64", "windows") => false, // x86 has ABI bugs that show up with optimizations. This should be partially fixed with // the compiler-builtins update. ("x86" | "x86_64", _) => false, @@ -122,6 +122,8 @@ fn main() { ("nvptx64", _) => false, // ABI unsupported ("sparc", _) => false, + // MinGW ABI bugs + ("x86_64", "windows") => false, // 64-bit Linux is about the only platform to have f128 symbols by default (_, "linux") if target_pointer_width == 64 => true, // Same as for f16, except MacOS is also missing f128 symbols. diff --git a/std/src/alloc.rs b/std/src/alloc.rs index dc4924cdf581d..5d51d6a0c78a8 100644 --- a/std/src/alloc.rs +++ b/std/src/alloc.rs @@ -56,10 +56,9 @@ #![deny(unsafe_op_in_unsafe_fn)] #![stable(feature = "alloc_module", since = "1.28.0")] -use core::hint; use core::ptr::NonNull; use core::sync::atomic::{AtomicPtr, Ordering}; -use core::{mem, ptr}; +use core::{hint, mem, ptr}; #[stable(feature = "alloc_module", since = "1.28.0")] #[doc(inline)] diff --git a/std/src/ascii.rs b/std/src/ascii.rs index b18ab50de123e..3a2880fd50904 100644 --- a/std/src/ascii.rs +++ b/std/src/ascii.rs @@ -13,11 +13,10 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::ascii::{escape_default, EscapeDefault}; - #[unstable(feature = "ascii_char", issue = "110998")] pub use core::ascii::Char; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::ascii::{escape_default, EscapeDefault}; /// Extension methods for ASCII-subset only operations. /// diff --git a/std/src/backtrace.rs b/std/src/backtrace.rs index 4d376753cb6d2..7df9a8a14b00c 100644 --- a/std/src/backtrace.rs +++ b/std/src/backtrace.rs @@ -89,13 +89,13 @@ mod tests; // a backtrace or actually symbolizing it. use crate::backtrace_rs::{self, BytesOrWideString}; -use crate::env; use crate::ffi::c_void; -use crate::fmt; use crate::panic::UnwindSafe; -use crate::sync::atomic::{AtomicU8, Ordering::Relaxed}; +use crate::sync::atomic::AtomicU8; +use crate::sync::atomic::Ordering::Relaxed; use crate::sync::LazyLock; use crate::sys::backtrace::{lock, output_filename, set_image_base}; +use crate::{env, fmt}; /// A captured OS thread stack backtrace. /// @@ -271,7 +271,7 @@ impl Backtrace { enabled } - /// Capture a stack backtrace of the current thread. + /// Captures a stack backtrace of the current thread. /// /// This function will capture a stack backtrace of the current OS thread of /// execution, returning a `Backtrace` type which can be later used to print diff --git a/std/src/collections/hash/map.rs b/std/src/collections/hash/map.rs index 1f6a3e904795a..822fa5791e300 100644 --- a/std/src/collections/hash/map.rs +++ b/std/src/collections/hash/map.rs @@ -1,13 +1,11 @@ #[cfg(test)] mod tests; -use self::Entry::*; - use hashbrown::hash_map as base; +use self::Entry::*; use crate::borrow::Borrow; -use crate::collections::TryReserveError; -use crate::collections::TryReserveErrorKind; +use crate::collections::{TryReserveError, TryReserveErrorKind}; use crate::error::Error; use crate::fmt::{self, Debug}; use crate::hash::{BuildHasher, Hash, RandomState}; diff --git a/std/src/collections/hash/map/tests.rs b/std/src/collections/hash/map/tests.rs index 8585376abc18b..6641197c3724a 100644 --- a/std/src/collections/hash/map/tests.rs +++ b/std/src/collections/hash/map/tests.rs @@ -1,11 +1,12 @@ +use rand::Rng; +use realstd::collections::TryReserveErrorKind::*; + use super::Entry::{Occupied, Vacant}; use super::HashMap; use crate::assert_matches::assert_matches; use crate::cell::RefCell; use crate::hash::RandomState; use crate::test_helpers::test_rng; -use rand::Rng; -use realstd::collections::TryReserveErrorKind::*; // https://github.com/rust-lang/rust/issues/62301 fn _assert_hashmap_is_unwind_safe() { @@ -946,7 +947,6 @@ fn test_raw_entry() { mod test_extract_if { use super::*; - use crate::panic::{catch_unwind, AssertUnwindSafe}; use crate::sync::atomic::{AtomicUsize, Ordering}; diff --git a/std/src/collections/hash/set.rs b/std/src/collections/hash/set.rs index f0a498fc7bbca..d611353b0d3f2 100644 --- a/std/src/collections/hash/set.rs +++ b/std/src/collections/hash/set.rs @@ -3,6 +3,7 @@ mod tests; use hashbrown::hash_set as base; +use super::map::map_try_reserve_error; use crate::borrow::Borrow; use crate::collections::TryReserveError; use crate::fmt; @@ -10,8 +11,6 @@ use crate::hash::{BuildHasher, Hash, RandomState}; use crate::iter::{Chain, FusedIterator}; use crate::ops::{BitAnd, BitOr, BitXor, Sub}; -use super::map::map_try_reserve_error; - /// A [hash set] implemented as a `HashMap` where the value is `()`. /// /// As with the [`HashMap`] type, a `HashSet` requires that the elements diff --git a/std/src/collections/hash/set/tests.rs b/std/src/collections/hash/set/tests.rs index a188409004305..4e6351652721f 100644 --- a/std/src/collections/hash/set/tests.rs +++ b/std/src/collections/hash/set/tests.rs @@ -1,5 +1,4 @@ use super::HashSet; - use crate::hash::RandomState; use crate::panic::{catch_unwind, AssertUnwindSafe}; use crate::sync::atomic::{AtomicU32, Ordering}; diff --git a/std/src/collections/mod.rs b/std/src/collections/mod.rs index 1389d24a8c519..3b04412e76630 100644 --- a/std/src/collections/mod.rs +++ b/std/src/collections/mod.rs @@ -401,12 +401,14 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[stable(feature = "rust1", since = "1.0.0")] -// FIXME(#82080) The deprecation here is only theoretical, and does not actually produce a warning. -#[deprecated(note = "moved to `std::ops::Bound`", since = "1.26.0")] -#[doc(hidden)] -pub use crate::ops::Bound; - +#[stable(feature = "try_reserve", since = "1.57.0")] +pub use alloc_crate::collections::TryReserveError; +#[unstable( + feature = "try_reserve_kind", + reason = "Uncertain how much info should be exposed", + issue = "48043" +)] +pub use alloc_crate::collections::TryReserveErrorKind; #[stable(feature = "rust1", since = "1.0.0")] pub use alloc_crate::collections::{binary_heap, btree_map, btree_set}; #[stable(feature = "rust1", since = "1.0.0")] @@ -422,15 +424,11 @@ pub use self::hash_map::HashMap; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] pub use self::hash_set::HashSet; - -#[stable(feature = "try_reserve", since = "1.57.0")] -pub use alloc_crate::collections::TryReserveError; -#[unstable( - feature = "try_reserve_kind", - reason = "Uncertain how much info should be exposed", - issue = "48043" -)] -pub use alloc_crate::collections::TryReserveErrorKind; +#[stable(feature = "rust1", since = "1.0.0")] +// FIXME(#82080) The deprecation here is only theoretical, and does not actually produce a warning. +#[deprecated(note = "moved to `std::ops::Bound`", since = "1.26.0")] +#[doc(hidden)] +pub use crate::ops::Bound; mod hash; @@ -439,7 +437,6 @@ pub mod hash_map { //! A hash map implemented with quadratic probing and SIMD lookup. #[stable(feature = "rust1", since = "1.0.0")] pub use super::hash::map::*; - #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] pub use crate::hash::random::DefaultHasher; #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] diff --git a/std/src/env.rs b/std/src/env.rs index fc9b8cfd46d65..50ae83090c7e1 100644 --- a/std/src/env.rs +++ b/std/src/env.rs @@ -15,11 +15,9 @@ mod tests; use crate::error::Error; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::path::{Path, PathBuf}; -use crate::sys; use crate::sys::os as os_imp; +use crate::{fmt, io, sys}; /// Returns the current working directory as a [`PathBuf`]. /// diff --git a/std/src/error.rs b/std/src/error.rs index 87aad8f764bd0..3e17431af45b0 100644 --- a/std/src/error.rs +++ b/std/src/error.rs @@ -4,14 +4,14 @@ #[cfg(test)] mod tests; -use crate::backtrace::Backtrace; -use crate::fmt::{self, Write}; - #[stable(feature = "rust1", since = "1.0.0")] pub use core::error::Error; #[unstable(feature = "error_generic_member_access", issue = "99301")] pub use core::error::{request_ref, request_value, Request}; +use crate::backtrace::Backtrace; +use crate::fmt::{self, Write}; + /// An error reporter that prints an error and its sources. /// /// Report also exposes configuration options for formatting the error sources, either entirely on a @@ -234,7 +234,7 @@ impl Report where Report: From, { - /// Create a new `Report` from an input error. + /// Creates a new `Report` from an input error. #[unstable(feature = "error_reporter", issue = "90172")] pub fn new(error: E) -> Report { Self::from(error) @@ -500,13 +500,8 @@ where } if self.show_backtrace { - let backtrace = self.backtrace(); - - if let Some(backtrace) = backtrace { - let backtrace = backtrace.to_string(); - - f.write_str("\n\nStack backtrace:\n")?; - f.write_str(backtrace.trim_end())?; + if let Some(backtrace) = self.backtrace() { + write!(f, "\n\nStack backtrace:\n{}", backtrace.to_string().trim_end())?; } } diff --git a/std/src/error/tests.rs b/std/src/error/tests.rs index ed070a26b0cf0..88a9f33c07908 100644 --- a/std/src/error/tests.rs +++ b/std/src/error/tests.rs @@ -1,6 +1,7 @@ +use core::error::Request; + use super::Error; use crate::fmt; -use core::error::Request; #[derive(Debug, PartialEq)] struct A; diff --git a/std/src/f128.rs b/std/src/f128.rs index 0591c6f517b44..a5b00d57cefdd 100644 --- a/std/src/f128.rs +++ b/std/src/f128.rs @@ -7,12 +7,12 @@ #[cfg(test)] mod tests; -#[cfg(not(test))] -use crate::intrinsics; - #[unstable(feature = "f128", issue = "116909")] pub use core::f128::consts; +#[cfg(not(test))] +use crate::intrinsics; + #[cfg(not(test))] impl f128 { /// Raises a number to an integer power. @@ -53,7 +53,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[rustc_allow_incoherent_impl] #[unstable(feature = "f128", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] diff --git a/std/src/f128/tests.rs b/std/src/f128/tests.rs index 0b3e485b0e735..162c8dbad81a1 100644 --- a/std/src/f128/tests.rs +++ b/std/src/f128/tests.rs @@ -1,10 +1,8 @@ -#![cfg(not(bootstrap))] // FIXME(f16_f128): only tested on platforms that have symbols and aren't buggy #![cfg(reliable_f128)] use crate::f128::consts; -use crate::num::FpCategory as Fp; -use crate::num::*; +use crate::num::{FpCategory as Fp, *}; /// Smallest number const TINY_BITS: u128 = 0x1; diff --git a/std/src/f16.rs b/std/src/f16.rs index d48518622999a..e3024defed734 100644 --- a/std/src/f16.rs +++ b/std/src/f16.rs @@ -7,12 +7,12 @@ #[cfg(test)] mod tests; -#[cfg(not(test))] -use crate::intrinsics; - #[unstable(feature = "f16", issue = "116909")] pub use core::f16::consts; +#[cfg(not(test))] +use crate::intrinsics; + #[cfg(not(test))] impl f16 { /// Raises a number to an integer power. @@ -53,7 +53,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[rustc_allow_incoherent_impl] #[unstable(feature = "f16", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] diff --git a/std/src/f16/tests.rs b/std/src/f16/tests.rs index 26658a0be87bc..f73bdf68e8295 100644 --- a/std/src/f16/tests.rs +++ b/std/src/f16/tests.rs @@ -1,10 +1,8 @@ -#![cfg(not(bootstrap))] // FIXME(f16_f128): only tested on platforms that have symbols and aren't buggy #![cfg(reliable_f16)] use crate::f16::consts; -use crate::num::FpCategory as Fp; -use crate::num::*; +use crate::num::{FpCategory as Fp, *}; // We run out of precision pretty quickly with f16 // const F16_APPROX_L1: f16 = 0.001; diff --git a/std/src/f32.rs b/std/src/f32.rs index 4fc82fec0adbc..12433d25bfa45 100644 --- a/std/src/f32.rs +++ b/std/src/f32.rs @@ -15,11 +15,6 @@ #[cfg(test)] mod tests; -#[cfg(not(test))] -use crate::intrinsics; -#[cfg(not(test))] -use crate::sys::cmath; - #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::f32::{ @@ -27,6 +22,11 @@ pub use core::f32::{ MIN_EXP, MIN_POSITIVE, NAN, NEG_INFINITY, RADIX, }; +#[cfg(not(test))] +use crate::intrinsics; +#[cfg(not(test))] +use crate::sys::cmath; + #[cfg(not(test))] impl f32 { /// Returns the largest integer less than or equal to `self`. @@ -574,7 +574,7 @@ impl f32 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn log2(self) -> f32 { - crate::sys::log2f32(self) + unsafe { intrinsics::log2f32(self) } } /// Returns the base 10 logarithm of the number. diff --git a/std/src/f32/tests.rs b/std/src/f32/tests.rs index 63e65698374c8..3a4c1c120a495 100644 --- a/std/src/f32/tests.rs +++ b/std/src/f32/tests.rs @@ -1,6 +1,5 @@ use crate::f32::consts; -use crate::num::FpCategory as Fp; -use crate::num::*; +use crate::num::{FpCategory as Fp, *}; /// Smallest number #[allow(dead_code)] // unused on x86 diff --git a/std/src/f64.rs b/std/src/f64.rs index 1ca2b32e241c9..a343e19173e59 100644 --- a/std/src/f64.rs +++ b/std/src/f64.rs @@ -15,11 +15,6 @@ #[cfg(test)] mod tests; -#[cfg(not(test))] -use crate::intrinsics; -#[cfg(not(test))] -use crate::sys::cmath; - #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::f64::{ @@ -27,6 +22,11 @@ pub use core::f64::{ MIN_EXP, MIN_POSITIVE, NAN, NEG_INFINITY, RADIX, }; +#[cfg(not(test))] +use crate::intrinsics; +#[cfg(not(test))] +use crate::sys::cmath; + #[cfg(not(test))] impl f64 { /// Returns the largest integer less than or equal to `self`. @@ -574,7 +574,7 @@ impl f64 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn log2(self) -> f64 { - crate::sys::log2f64(self) + unsafe { intrinsics::log2f64(self) } } /// Returns the base 10 logarithm of the number. diff --git a/std/src/f64/tests.rs b/std/src/f64/tests.rs index d9e17fd601d2d..bac8405f97361 100644 --- a/std/src/f64/tests.rs +++ b/std/src/f64/tests.rs @@ -1,6 +1,5 @@ use crate::f64::consts; -use crate::num::FpCategory as Fp; -use crate::num::*; +use crate::num::{FpCategory as Fp, *}; /// Smallest number #[allow(dead_code)] // unused on x86 diff --git a/std/src/ffi/c_str.rs b/std/src/ffi/c_str.rs index b59b0c5bba65a..cb0ca5d1376ea 100644 --- a/std/src/ffi/c_str.rs +++ b/std/src/ffi/c_str.rs @@ -1,19 +1,14 @@ //! [`CStr`], [`CString`], and related types. -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::ffi::c_str::CStr; - -#[stable(feature = "cstr_from_bytes", since = "1.10.0")] -pub use core::ffi::c_str::FromBytesWithNulError; - -#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")] -pub use core::ffi::c_str::FromBytesUntilNulError; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::ffi::c_str::{CString, NulError}; - #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")] pub use alloc::ffi::c_str::FromVecWithNulError; - #[stable(feature = "cstring_into", since = "1.7.0")] pub use alloc::ffi::c_str::IntoStringError; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc::ffi::c_str::{CString, NulError}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::ffi::c_str::CStr; +#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")] +pub use core::ffi::c_str::FromBytesUntilNulError; +#[stable(feature = "cstr_from_bytes", since = "1.10.0")] +pub use core::ffi::c_str::FromBytesWithNulError; diff --git a/std/src/ffi/mod.rs b/std/src/ffi/mod.rs index f45fd77e8b167..2b67750c2f0a9 100644 --- a/std/src/ffi/mod.rs +++ b/std/src/ffi/mod.rs @@ -164,50 +164,42 @@ #[unstable(feature = "c_str_module", issue = "112134")] pub mod c_str; -#[doc(inline)] -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::c_str::{CStr, CString}; - -#[doc(no_inline)] -#[stable(feature = "cstr_from_bytes", since = "1.10.0")] -pub use self::c_str::FromBytesWithNulError; +#[stable(feature = "core_c_void", since = "1.30.0")] +pub use core::ffi::c_void; +#[stable(feature = "core_ffi_c", since = "1.64.0")] +pub use core::ffi::{ + c_char, c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, + c_ulong, c_ulonglong, c_ushort, +}; +#[unstable( + feature = "c_variadic", + reason = "the `c_variadic` feature has not been properly tested on \ + all supported platforms", + issue = "44930" +)] +pub use core::ffi::{VaList, VaListImpl}; #[doc(no_inline)] #[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")] pub use self::c_str::FromBytesUntilNulError; - #[doc(no_inline)] -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::c_str::NulError; - +#[stable(feature = "cstr_from_bytes", since = "1.10.0")] +pub use self::c_str::FromBytesWithNulError; #[doc(no_inline)] #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")] pub use self::c_str::FromVecWithNulError; - #[doc(no_inline)] #[stable(feature = "cstring_into", since = "1.7.0")] pub use self::c_str::IntoStringError; - +#[doc(no_inline)] +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::c_str::NulError; +#[doc(inline)] +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::c_str::{CStr, CString}; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] pub use self::os_str::{OsStr, OsString}; -#[stable(feature = "core_ffi_c", since = "1.64.0")] -pub use core::ffi::{ - c_char, c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, - c_ulong, c_ulonglong, c_ushort, -}; - -#[stable(feature = "core_c_void", since = "1.30.0")] -pub use core::ffi::c_void; - -#[unstable( - feature = "c_variadic", - reason = "the `c_variadic` feature has not been properly tested on \ - all supported platforms", - issue = "44930" -)] -pub use core::ffi::{VaList, VaListImpl}; - #[unstable(feature = "os_str_display", issue = "120048")] pub mod os_str; diff --git a/std/src/ffi/os_str.rs b/std/src/ffi/os_str.rs index f9dba08da4c3c..a501bcc98cf38 100644 --- a/std/src/ffi/os_str.rs +++ b/std/src/ffi/os_str.rs @@ -4,18 +4,15 @@ mod tests; use crate::borrow::{Borrow, Cow}; -use crate::cmp; use crate::collections::TryReserveError; -use crate::fmt; use crate::hash::{Hash, Hasher}; use crate::ops::{self, Range}; use crate::rc::Rc; -use crate::slice; use crate::str::FromStr; use crate::sync::Arc; - use crate::sys::os_str::{Buf, Slice}; use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::{cmp, fmt, slice}; /// A type that can represent owned, mutable platform-native strings, but is /// cheaply inter-convertible with Rust strings. @@ -115,10 +112,8 @@ impl crate::sealed::Sealed for OsString {} #[stable(feature = "rust1", since = "1.0.0")] // `OsStr::from_inner` current implementation relies // on `OsStr` being layout-compatible with `Slice`. -// However, `OsStr` layout is considered an implementation detail and must not be relied upon. We -// want `repr(transparent)` but we don't want it to show up in rustdoc, so we hide it under -// `cfg(doc)`. This is an ad-hoc implementation of attribute privacy. -#[cfg_attr(not(doc), repr(transparent))] +// However, `OsStr` layout is considered an implementation detail and must not be relied upon. +#[repr(transparent)] pub struct OsStr { inner: Slice, } diff --git a/std/src/fs.rs b/std/src/fs.rs index 6413b3515ecec..c5edb03bb08be 100644 --- a/std/src/fs.rs +++ b/std/src/fs.rs @@ -50,7 +50,7 @@ use crate::time::SystemTime; /// } /// ``` /// -/// Read the contents of a file into a [`String`] (you can also use [`read`]): +/// Reads the contents of a file into a [`String`] (you can also use [`read`]): /// /// ```no_run /// use std::fs::File; @@ -229,7 +229,7 @@ pub struct DirBuilder { recursive: bool, } -/// Read the entire contents of a file into a bytes vector. +/// Reads the entire contents of a file into a bytes vector. /// /// This is a convenience function for using [`File::open`] and [`read_to_end`] /// with fewer imports and without an intermediate variable. @@ -268,7 +268,7 @@ pub fn read>(path: P) -> io::Result> { inner(path.as_ref()) } -/// Read the entire contents of a file into a string. +/// Reads the entire contents of a file into a string. /// /// This is a convenience function for using [`File::open`] and [`read_to_string`] /// with fewer imports and without an intermediate variable. @@ -311,7 +311,7 @@ pub fn read_to_string>(path: P) -> io::Result { inner(path.as_ref()) } -/// Write a slice as the entire contents of a file. +/// Writes a slice as the entire contents of a file. /// /// This function will create a file if it does not exist, /// and will entirely replace its contents if it does. @@ -767,7 +767,7 @@ fn buffer_capacity_required(mut file: &File) -> Option { #[stable(feature = "rust1", since = "1.0.0")] impl Read for &File { - /// Read some bytes from the file. + /// Reads some bytes from the file. /// /// See [`Read::read`] docs for more info. /// @@ -835,7 +835,7 @@ impl Read for &File { } #[stable(feature = "rust1", since = "1.0.0")] impl Write for &File { - /// Write some bytes from the file. + /// Writes some bytes from the file. /// /// See [`Write::write`] docs for more info. /// @@ -1526,7 +1526,7 @@ impl FromInner for Metadata { } impl FileTimes { - /// Create a new `FileTimes` with no times set. + /// Creates a new `FileTimes` with no times set. /// /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps. #[stable(feature = "file_set_times", since = "1.75.0")] @@ -2005,7 +2005,7 @@ pub fn remove_file>(path: P) -> io::Result<()> { fs_imp::unlink(path.as_ref()) } -/// Given a path, query the file system to get information about a file, +/// Given a path, queries the file system to get information about a file, /// directory, etc. /// /// This function will traverse symbolic links to query information about the @@ -2044,7 +2044,7 @@ pub fn metadata>(path: P) -> io::Result { fs_imp::stat(path.as_ref()).map(Metadata) } -/// Query the metadata about a file without following symlinks. +/// Queries the metadata about a file without following symlinks. /// /// # Platform-specific behavior /// @@ -2079,7 +2079,7 @@ pub fn symlink_metadata>(path: P) -> io::Result { fs_imp::lstat(path.as_ref()).map(Metadata) } -/// Rename a file or directory to a new name, replacing the original file if +/// Renames a file or directory to a new name, replacing the original file if /// `to` already exists. /// /// This will not work if the new name is on a different mount point. @@ -2400,13 +2400,8 @@ pub fn create_dir>(path: P) -> io::Result<()> { /// /// # Errors /// -/// This function will return an error in the following situations, but is not -/// limited to just these cases: -/// -/// * If any directory in the path specified by `path` -/// does not already exist and it could not be created otherwise. The specific -/// error conditions for when a directory is being created (after it is -/// determined to not exist) are outlined by [`fs::create_dir`]. +/// The function will return an error if any directory specified in path does not exist and +/// could not be created. There may be other error conditions; see [`fs::create_dir`] for specifics. /// /// Notable exception is made for situations where any of the directories /// specified in the `path` could not be created as it was being created concurrently. @@ -2749,7 +2744,7 @@ impl AsInnerMut for DirBuilder { /// ``` /// /// [`Path::exists`]: crate::path::Path::exists -#[stable(feature = "fs_try_exists", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "fs_try_exists", since = "1.81.0")] #[inline] pub fn exists>(path: P) -> io::Result { fs_imp::exists(path.as_ref()) diff --git a/std/src/fs/tests.rs b/std/src/fs/tests.rs index 5ca631399aa4a..13028c4c3b57e 100644 --- a/std/src/fs/tests.rs +++ b/std/src/fs/tests.rs @@ -1,20 +1,11 @@ -use crate::io::prelude::*; - -use crate::env; -use crate::fs::{self, File, FileTimes, OpenOptions}; -use crate::io::{BorrowedBuf, ErrorKind, SeekFrom}; -use crate::mem::MaybeUninit; -use crate::path::Path; -use crate::str; -use crate::sync::Arc; -use crate::sys_common::io::test::{tmpdir, TempDir}; -use crate::thread; -use crate::time::{Duration, Instant, SystemTime}; - use rand::RngCore; #[cfg(target_os = "macos")] use crate::ffi::{c_char, c_int}; +use crate::fs::{self, File, FileTimes, OpenOptions}; +use crate::io::prelude::*; +use crate::io::{BorrowedBuf, ErrorKind, SeekFrom}; +use crate::mem::MaybeUninit; #[cfg(unix)] use crate::os::unix::fs::symlink as symlink_dir; #[cfg(unix)] @@ -23,8 +14,13 @@ use crate::os::unix::fs::symlink as symlink_file; use crate::os::unix::fs::symlink as junction_point; #[cfg(windows)] use crate::os::windows::fs::{junction_point, symlink_dir, symlink_file, OpenOptionsExt}; +use crate::path::Path; +use crate::sync::Arc; #[cfg(target_os = "macos")] use crate::sys::weak::weak; +use crate::sys_common::io::test::{tmpdir, TempDir}; +use crate::time::{Duration, Instant, SystemTime}; +use crate::{env, str, thread}; macro_rules! check { ($e:expr) => { @@ -683,7 +679,7 @@ fn recursive_rmdir_toctou() { let drop_canary_arc = Arc::new(()); let drop_canary_weak = Arc::downgrade(&drop_canary_arc); - eprintln!("x: {:?}", &victim_del_path); + eprintln!("x: {victim_del_path:?}"); // victim just continuously removes `victim_del` thread::spawn(move || { @@ -1514,7 +1510,9 @@ fn symlink_hard_link() { #[test] #[cfg(windows)] fn create_dir_long_paths() { - use crate::{ffi::OsStr, iter, os::windows::ffi::OsStrExt}; + use crate::ffi::OsStr; + use crate::iter; + use crate::os::windows::ffi::OsStrExt; const PATH_LEN: usize = 247; let tmpdir = tmpdir(); diff --git a/std/src/hash/random.rs b/std/src/hash/random.rs index 0adf91e14ac6e..8ef45172eac40 100644 --- a/std/src/hash/random.rs +++ b/std/src/hash/random.rs @@ -10,8 +10,7 @@ #[allow(deprecated)] use super::{BuildHasher, Hasher, SipHasher13}; use crate::cell::Cell; -use crate::fmt; -use crate::sys; +use crate::{fmt, sys}; /// `RandomState` is the default state for [`HashMap`] types. /// diff --git a/std/src/io/buffered/bufreader.rs b/std/src/io/buffered/bufreader.rs index 0cdc49c87d8fc..f11dd50c5e2b7 100644 --- a/std/src/io/buffered/bufreader.rs +++ b/std/src/io/buffered/bufreader.rs @@ -1,11 +1,12 @@ mod buffer; +use buffer::Buffer; + use crate::fmt; use crate::io::{ self, uninlined_slow_read_byte, BorrowedCursor, BufRead, IoSliceMut, Read, Seek, SeekFrom, SizeHint, SpecReadByte, DEFAULT_BUF_SIZE, }; -use buffer::Buffer; /// The `BufReader` struct adds buffering to any reader. /// diff --git a/std/src/io/buffered/bufwriter.rs b/std/src/io/buffered/bufwriter.rs index a8680e9b6ead1..21650d467446e 100644 --- a/std/src/io/buffered/bufwriter.rs +++ b/std/src/io/buffered/bufwriter.rs @@ -1,10 +1,8 @@ -use crate::error; -use crate::fmt; use crate::io::{ self, ErrorKind, IntoInnerError, IoSlice, Seek, SeekFrom, Write, DEFAULT_BUF_SIZE, }; use crate::mem::{self, ManuallyDrop}; -use crate::ptr; +use crate::{error, fmt, ptr}; /// Wraps a writer and buffers its output. /// diff --git a/std/src/io/buffered/linewriter.rs b/std/src/io/buffered/linewriter.rs index 3d4ae70419322..cc6921b86dd0b 100644 --- a/std/src/io/buffered/linewriter.rs +++ b/std/src/io/buffered/linewriter.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::io::{self, buffered::LineWriterShim, BufWriter, IntoInnerError, IoSlice, Write}; +use crate::io::buffered::LineWriterShim; +use crate::io::{self, BufWriter, IntoInnerError, IoSlice, Write}; /// Wraps a writer and buffers output to it, flushing whenever a newline /// (`0x0a`, `'\n'`) is detected. diff --git a/std/src/io/buffered/linewritershim.rs b/std/src/io/buffered/linewritershim.rs index c3ac7855d4450..3d04ccd1c7d81 100644 --- a/std/src/io/buffered/linewritershim.rs +++ b/std/src/io/buffered/linewritershim.rs @@ -1,7 +1,9 @@ -use crate::io::{self, BufWriter, IoSlice, Write}; use core::slice::memchr; +use crate::io::{self, BufWriter, IoSlice, Write}; + /// Private helper struct for implementing the line-buffered writing logic. +/// /// This shim temporarily wraps a BufWriter, and uses its internals to /// implement a line-buffered writer (specifically by using the internal /// methods like write_to_buf and flush_buf). In this way, a more @@ -20,27 +22,27 @@ impl<'a, W: ?Sized + Write> LineWriterShim<'a, W> { Self { buffer } } - /// Get a reference to the inner writer (that is, the writer + /// Gets a reference to the inner writer (that is, the writer /// wrapped by the BufWriter). fn inner(&self) -> &W { self.buffer.get_ref() } - /// Get a mutable reference to the inner writer (that is, the writer + /// Gets a mutable reference to the inner writer (that is, the writer /// wrapped by the BufWriter). Be careful with this writer, as writes to /// it will bypass the buffer. fn inner_mut(&mut self) -> &mut W { self.buffer.get_mut() } - /// Get the content currently buffered in self.buffer + /// Gets the content currently buffered in self.buffer fn buffered(&self) -> &[u8] { self.buffer.buffer() } - /// Flush the buffer iff the last byte is a newline (indicating that an + /// Flushes the buffer iff the last byte is a newline (indicating that an /// earlier write only succeeded partially, and we want to retry flushing - /// the buffered line before continuing with a subsequent write) + /// the buffered line before continuing with a subsequent write). fn flush_if_completed_line(&mut self) -> io::Result<()> { match self.buffered().last().copied() { Some(b'\n') => self.buffer.flush_buf(), @@ -50,10 +52,11 @@ impl<'a, W: ?Sized + Write> LineWriterShim<'a, W> { } impl<'a, W: ?Sized + Write> Write for LineWriterShim<'a, W> { - /// Write some data into this BufReader with line buffering. This means - /// that, if any newlines are present in the data, the data up to the last - /// newline is sent directly to the underlying writer, and data after it - /// is buffered. Returns the number of bytes written. + /// Writes some data into this BufReader with line buffering. + /// + /// This means that, if any newlines are present in the data, the data up to + /// the last newline is sent directly to the underlying writer, and data + /// after it is buffered. Returns the number of bytes written. /// /// This function operates on a "best effort basis"; in keeping with the /// convention of `Write::write`, it makes at most one attempt to write @@ -136,11 +139,12 @@ impl<'a, W: ?Sized + Write> Write for LineWriterShim<'a, W> { self.buffer.flush() } - /// Write some vectored data into this BufReader with line buffering. This - /// means that, if any newlines are present in the data, the data up to - /// and including the buffer containing the last newline is sent directly - /// to the inner writer, and the data after it is buffered. Returns the - /// number of bytes written. + /// Writes some vectored data into this BufReader with line buffering. + /// + /// This means that, if any newlines are present in the data, the data up to + /// and including the buffer containing the last newline is sent directly to + /// the inner writer, and the data after it is buffered. Returns the number + /// of bytes written. /// /// This function operates on a "best effort basis"; in keeping with the /// convention of `Write::write`, it makes at most one attempt to write @@ -245,10 +249,11 @@ impl<'a, W: ?Sized + Write> Write for LineWriterShim<'a, W> { self.inner().is_write_vectored() } - /// Write some data into this BufReader with line buffering. This means - /// that, if any newlines are present in the data, the data up to the last - /// newline is sent directly to the underlying writer, and data after it - /// is buffered. + /// Writes some data into this BufReader with line buffering. + /// + /// This means that, if any newlines are present in the data, the data up to + /// the last newline is sent directly to the underlying writer, and data + /// after it is buffered. /// /// Because this function attempts to send completed lines to the underlying /// writer, it will also flush the existing buffer if it contains any diff --git a/std/src/io/buffered/mod.rs b/std/src/io/buffered/mod.rs index 100dab1e2493c..475d877528f7f 100644 --- a/std/src/io/buffered/mod.rs +++ b/std/src/io/buffered/mod.rs @@ -8,16 +8,14 @@ mod linewritershim; #[cfg(test)] mod tests; -use crate::error; -use crate::fmt; -use crate::io::Error; +#[stable(feature = "bufwriter_into_parts", since = "1.56.0")] +pub use bufwriter::WriterPanicked; +use linewritershim::LineWriterShim; #[stable(feature = "rust1", since = "1.0.0")] pub use self::{bufreader::BufReader, bufwriter::BufWriter, linewriter::LineWriter}; -use linewritershim::LineWriterShim; - -#[stable(feature = "bufwriter_into_parts", since = "1.56.0")] -pub use bufwriter::WriterPanicked; +use crate::io::Error; +use crate::{error, fmt}; /// An error returned by [`BufWriter::into_inner`] which combines an error that /// happened while writing out the buffer, and the buffered writer object @@ -48,7 +46,7 @@ pub use bufwriter::WriterPanicked; pub struct IntoInnerError(W, Error); impl IntoInnerError { - /// Construct a new IntoInnerError + /// Constructs a new IntoInnerError fn new(writer: W, error: Error) -> Self { Self(writer, error) } diff --git a/std/src/io/buffered/tests.rs b/std/src/io/buffered/tests.rs index ab66deaf31d22..d89ecd317d6ee 100644 --- a/std/src/io/buffered/tests.rs +++ b/std/src/io/buffered/tests.rs @@ -3,9 +3,8 @@ use crate::io::{ self, BorrowedBuf, BufReader, BufWriter, ErrorKind, IoSlice, LineWriter, SeekFrom, }; use crate::mem::MaybeUninit; -use crate::panic; use crate::sync::atomic::{AtomicUsize, Ordering}; -use crate::thread; +use crate::{panic, thread}; /// A dummy reader intended at testing short-reads propagation. pub struct ShortReader { diff --git a/std/src/io/copy/tests.rs b/std/src/io/copy/tests.rs index a1f909a3c5386..7e08826a7e1d8 100644 --- a/std/src/io/copy/tests.rs +++ b/std/src/io/copy/tests.rs @@ -119,13 +119,12 @@ fn copy_specializes_from_slice() { #[cfg(unix)] mod io_benches { - use crate::fs::File; - use crate::fs::OpenOptions; + use test::Bencher; + + use crate::fs::{File, OpenOptions}; use crate::io::prelude::*; use crate::io::BufReader; - use test::Bencher; - #[bench] fn bench_copy_buf_reader(b: &mut Bencher) { let mut file_in = File::open("/dev/zero").expect("opening /dev/zero failed"); diff --git a/std/src/io/cursor.rs b/std/src/io/cursor.rs index 2ed64a40495ef..9f913eae09544 100644 --- a/std/src/io/cursor.rs +++ b/std/src/io/cursor.rs @@ -1,10 +1,9 @@ #[cfg(test)] mod tests; -use crate::io::prelude::*; - use crate::alloc::Allocator; use crate::cmp; +use crate::io::prelude::*; use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut, SeekFrom}; /// A `Cursor` wraps an in-memory buffer and provides it with a @@ -210,55 +209,60 @@ impl Cursor where T: AsRef<[u8]>, { - /// Returns the remaining slice. + /// Splits the underlying slice at the cursor position and returns them. /// /// # Examples /// /// ``` - /// #![feature(cursor_remaining)] + /// #![feature(cursor_split)] /// use std::io::Cursor; /// /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); /// - /// assert_eq!(buff.remaining_slice(), &[1, 2, 3, 4, 5]); + /// assert_eq!(buff.split(), ([].as_slice(), [1, 2, 3, 4, 5].as_slice())); /// /// buff.set_position(2); - /// assert_eq!(buff.remaining_slice(), &[3, 4, 5]); - /// - /// buff.set_position(4); - /// assert_eq!(buff.remaining_slice(), &[5]); + /// assert_eq!(buff.split(), ([1, 2].as_slice(), [3, 4, 5].as_slice())); /// /// buff.set_position(6); - /// assert_eq!(buff.remaining_slice(), &[]); + /// assert_eq!(buff.split(), ([1, 2, 3, 4, 5].as_slice(), [].as_slice())); /// ``` - #[unstable(feature = "cursor_remaining", issue = "86369")] - pub fn remaining_slice(&self) -> &[u8] { - let len = self.pos.min(self.inner.as_ref().len() as u64); - &self.inner.as_ref()[(len as usize)..] + #[unstable(feature = "cursor_split", issue = "86369")] + pub fn split(&self) -> (&[u8], &[u8]) { + let slice = self.inner.as_ref(); + let pos = self.pos.min(slice.len() as u64); + slice.split_at(pos as usize) } +} - /// Returns `true` if the remaining slice is empty. +impl Cursor +where + T: AsMut<[u8]>, +{ + /// Splits the underlying slice at the cursor position and returns them + /// mutably. /// /// # Examples /// /// ``` - /// #![feature(cursor_remaining)] + /// #![feature(cursor_split)] /// use std::io::Cursor; /// /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); /// - /// buff.set_position(2); - /// assert!(!buff.is_empty()); + /// assert_eq!(buff.split_mut(), ([].as_mut_slice(), [1, 2, 3, 4, 5].as_mut_slice())); /// - /// buff.set_position(5); - /// assert!(buff.is_empty()); + /// buff.set_position(2); + /// assert_eq!(buff.split_mut(), ([1, 2].as_mut_slice(), [3, 4, 5].as_mut_slice())); /// - /// buff.set_position(10); - /// assert!(buff.is_empty()); + /// buff.set_position(6); + /// assert_eq!(buff.split_mut(), ([1, 2, 3, 4, 5].as_mut_slice(), [].as_mut_slice())); /// ``` - #[unstable(feature = "cursor_remaining", issue = "86369")] - pub fn is_empty(&self) -> bool { - self.pos >= self.inner.as_ref().len() as u64 + #[unstable(feature = "cursor_split", issue = "86369")] + pub fn split_mut(&mut self) -> (&mut [u8], &mut [u8]) { + let slice = self.inner.as_mut(); + let pos = self.pos.min(slice.len() as u64); + slice.split_at_mut(pos as usize) } } @@ -320,7 +324,7 @@ where T: AsRef<[u8]>, { fn read(&mut self, buf: &mut [u8]) -> io::Result { - let n = Read::read(&mut self.remaining_slice(), buf)?; + let n = Read::read(&mut Cursor::split(self).1, buf)?; self.pos += n as u64; Ok(n) } @@ -328,7 +332,7 @@ where fn read_buf(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> { let prev_written = cursor.written(); - Read::read_buf(&mut self.remaining_slice(), cursor.reborrow())?; + Read::read_buf(&mut Cursor::split(self).1, cursor.reborrow())?; self.pos += (cursor.written() - prev_written) as u64; @@ -352,7 +356,7 @@ where } fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { - let result = Read::read_exact(&mut self.remaining_slice(), buf); + let result = Read::read_exact(&mut Cursor::split(self).1, buf); match result { Ok(_) => self.pos += buf.len() as u64, @@ -366,14 +370,14 @@ where fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> { let prev_written = cursor.written(); - let result = Read::read_buf_exact(&mut self.remaining_slice(), cursor.reborrow()); + let result = Read::read_buf_exact(&mut Cursor::split(self).1, cursor.reborrow()); self.pos += (cursor.written() - prev_written) as u64; result } fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { - let content = self.remaining_slice(); + let content = Cursor::split(self).1; let len = content.len(); buf.try_reserve(len)?; buf.extend_from_slice(content); @@ -384,7 +388,7 @@ where fn read_to_string(&mut self, buf: &mut String) -> io::Result { let content = - crate::str::from_utf8(self.remaining_slice()).map_err(|_| io::Error::INVALID_UTF8)?; + crate::str::from_utf8(Cursor::split(self).1).map_err(|_| io::Error::INVALID_UTF8)?; let len = content.len(); buf.try_reserve(len)?; buf.push_str(content); @@ -400,7 +404,7 @@ where T: AsRef<[u8]>, { fn fill_buf(&mut self) -> io::Result<&[u8]> { - Ok(self.remaining_slice()) + Ok(Cursor::split(self).1) } fn consume(&mut self, amt: usize) { self.pos += amt as u64; diff --git a/std/src/io/error.rs b/std/src/io/error.rs index f366cb8f42baa..e8ae1d99fbf37 100644 --- a/std/src/io/error.rs +++ b/std/src/io/error.rs @@ -11,10 +11,7 @@ mod repr_unpacked; #[cfg(any(not(target_pointer_width = "64"), target_os = "uefi"))] use repr_unpacked::Repr; -use crate::error; -use crate::fmt; -use crate::result; -use crate::sys; +use crate::{error, fmt, result, sys}; /// A specialized [`Result`] type for I/O operations. /// @@ -167,7 +164,7 @@ impl SimpleMessage { } } -/// Create and return an `io::Error` for a given `ErrorKind` and constant +/// Creates and returns an `io::Error` for a given `ErrorKind` and constant /// message. This doesn't allocate. pub(crate) macro const_io_error($kind:expr, $message:expr $(,)?) { $crate::io::error::Error::from_static_message({ @@ -775,7 +772,7 @@ impl Error { /// /// impl Display for MyError { /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - /// write!(f, "MyError: {}", &self.v) + /// write!(f, "MyError: {}", self.v) /// } /// } /// @@ -852,7 +849,7 @@ impl Error { } } - /// Attempt to downcast the custom boxed error to `E`. + /// Attempts to downcast the custom boxed error to `E`. /// /// If this [`Error`] contains a custom boxed error, /// then it would attempt downcasting on the boxed error, diff --git a/std/src/io/error/repr_bitpacked.rs b/std/src/io/error/repr_bitpacked.rs index fbb74967df3f1..9d3ade46bd929 100644 --- a/std/src/io/error/repr_bitpacked.rs +++ b/std/src/io/error/repr_bitpacked.rs @@ -102,10 +102,11 @@ //! to use a pointer type to store something that may hold an integer, some of //! the time. -use super::{Custom, ErrorData, ErrorKind, RawOsError, SimpleMessage}; use core::marker::PhantomData; use core::ptr::{self, NonNull}; +use super::{Custom, ErrorData, ErrorKind, RawOsError, SimpleMessage}; + // The 2 least-significant bits are used as tag. const TAG_MASK: usize = 0b11; const TAG_SIMPLE_MESSAGE: usize = 0b00; diff --git a/std/src/io/error/tests.rs b/std/src/io/error/tests.rs index fc6db2825e811..064e2e36b7a1d 100644 --- a/std/src/io/error/tests.rs +++ b/std/src/io/error/tests.rs @@ -1,10 +1,9 @@ use super::{const_io_error, Custom, Error, ErrorData, ErrorKind, Repr, SimpleMessage}; use crate::assert_matches::assert_matches; -use crate::error; -use crate::fmt; use crate::mem::size_of; use crate::sys::decode_error_kind; use crate::sys::os::error_string; +use crate::{error, fmt}; #[test] fn test_size() { @@ -95,7 +94,8 @@ fn test_errorkind_packing() { #[test] fn test_simple_message_packing() { - use super::{ErrorKind::*, SimpleMessage}; + use super::ErrorKind::*; + use super::SimpleMessage; macro_rules! check_simple_msg { ($err:expr, $kind:ident, $msg:literal) => {{ let e = &$err; diff --git a/std/src/io/impls.rs b/std/src/io/impls.rs index a8a2e9413e11c..85023540a816f 100644 --- a/std/src/io/impls.rs +++ b/std/src/io/impls.rs @@ -2,12 +2,9 @@ mod tests; use crate::alloc::Allocator; -use crate::cmp; use crate::collections::VecDeque; -use crate::fmt; use crate::io::{self, BorrowedCursor, BufRead, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write}; -use crate::mem; -use crate::str; +use crate::{cmp, fmt, mem, str}; // ============================================================================= // Forwarding implementations diff --git a/std/src/io/mod.rs b/std/src/io/mod.rs index 1345a30361e28..644b294db8da1 100644 --- a/std/src/io/mod.rs +++ b/std/src/io/mod.rs @@ -297,15 +297,12 @@ #[cfg(test)] mod tests; -use crate::cmp; -use crate::fmt; -use crate::mem::take; -use crate::ops::{Deref, DerefMut}; -use crate::slice; -use crate::str; -use crate::sys; +#[unstable(feature = "read_buf", issue = "78485")] +pub use core::io::{BorrowedBuf, BorrowedCursor}; use core::slice::memchr; +pub(crate) use error::const_io_error; + #[stable(feature = "bufwriter_into_parts", since = "1.56.0")] pub use self::buffered::WriterPanicked; #[unstable(feature = "raw_os_error_ty", issue = "107792")] @@ -328,10 +325,9 @@ pub use self::{ stdio::{stderr, stdin, stdout, Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock}, util::{empty, repeat, sink, Empty, Repeat, Sink}, }; - -#[unstable(feature = "read_buf", issue = "78485")] -pub use core::io::{BorrowedBuf, BorrowedCursor}; -pub(crate) use error::const_io_error; +use crate::mem::take; +use crate::ops::{Deref, DerefMut}; +use crate::{cmp, fmt, slice, str, sys}; mod buffered; pub(crate) mod copy; @@ -782,7 +778,7 @@ pub trait Read { false } - /// Read all bytes until EOF in this source, placing them into `buf`. + /// Reads all bytes until EOF in this source, placing them into `buf`. /// /// All bytes read from this source will be appended to the specified buffer /// `buf`. This function will continuously call [`read()`] to append more data to @@ -866,7 +862,7 @@ pub trait Read { default_read_to_end(self, buf, None) } - /// Read all bytes until EOF in this source, appending them to `buf`. + /// Reads all bytes until EOF in this source, appending them to `buf`. /// /// If successful, this function returns the number of bytes which were read /// and appended to `buf`. @@ -909,7 +905,7 @@ pub trait Read { default_read_to_string(self, buf, None) } - /// Read the exact number of bytes required to fill `buf`. + /// Reads the exact number of bytes required to fill `buf`. /// /// This function reads as many bytes as necessary to completely fill the /// specified buffer `buf`. @@ -973,7 +969,7 @@ pub trait Read { default_read_buf(|b| self.read(b), buf) } - /// Read the exact number of bytes required to fill `cursor`. + /// Reads the exact number of bytes required to fill `cursor`. /// /// This is similar to the [`read_exact`](Read::read_exact) method, except /// that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use @@ -1159,7 +1155,7 @@ pub trait Read { } } -/// Read all bytes from a [reader][Read] into a new [`String`]. +/// Reads all bytes from a [reader][Read] into a new [`String`]. /// /// This is a convenience function for [`Read::read_to_string`]. Using this /// function avoids having to create a variable first and provides more type @@ -1212,7 +1208,7 @@ pub fn read_to_string(mut reader: R) -> Result { /// A buffer type used with `Read::read_vectored`. /// -/// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be +/// It is semantically a wrapper around a `&mut [u8]`, but is guaranteed to be /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on /// Windows. #[stable(feature = "iovec", since = "1.36.0")] @@ -1266,7 +1262,7 @@ impl<'a> IoSliceMut<'a> { /// buf.advance(3); /// assert_eq!(buf.deref(), [1; 5].as_ref()); /// ``` - #[stable(feature = "io_slice_advance", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "io_slice_advance", since = "1.81.0")] #[inline] pub fn advance(&mut self, n: usize) { self.0.advance(n) @@ -1305,7 +1301,7 @@ impl<'a> IoSliceMut<'a> { /// assert_eq!(bufs[0].deref(), [2; 14].as_ref()); /// assert_eq!(bufs[1].deref(), [3; 8].as_ref()); /// ``` - #[stable(feature = "io_slice_advance", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "io_slice_advance", since = "1.81.0")] #[inline] pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) { // Number of buffers to remove. @@ -1406,7 +1402,7 @@ impl<'a> IoSlice<'a> { /// buf.advance(3); /// assert_eq!(buf.deref(), [1; 5].as_ref()); /// ``` - #[stable(feature = "io_slice_advance", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "io_slice_advance", since = "1.81.0")] #[inline] pub fn advance(&mut self, n: usize) { self.0.advance(n) @@ -1444,7 +1440,7 @@ impl<'a> IoSlice<'a> { /// IoSlice::advance_slices(&mut bufs, 10); /// assert_eq!(bufs[0].deref(), [2; 14].as_ref()); /// assert_eq!(bufs[1].deref(), [3; 8].as_ref()); - #[stable(feature = "io_slice_advance", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "io_slice_advance", since = "1.81.0")] #[inline] pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) { // Number of buffers to remove. @@ -1531,7 +1527,7 @@ impl<'a> Deref for IoSlice<'a> { #[doc(notable_trait)] #[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")] pub trait Write { - /// Write a buffer into this writer, returning how many bytes were written. + /// Writes a buffer into this writer, returning how many bytes were written. /// /// This function will attempt to write the entire contents of `buf`, but /// the entire write might not succeed, or the write may also generate an @@ -1630,7 +1626,7 @@ pub trait Write { false } - /// Flush this output stream, ensuring that all intermediately buffered + /// Flushes this output stream, ensuring that all intermediately buffered /// contents reach their destination. /// /// # Errors @@ -2247,7 +2243,7 @@ pub trait BufRead: Read { #[stable(feature = "rust1", since = "1.0.0")] fn consume(&mut self, amt: usize); - /// Check if the underlying `Read` has any data left to be read. + /// Checks if the underlying `Read` has any data left to be read. /// /// This function may fill the buffer to check for data, /// so this functions returns `Result`, not `bool`. @@ -2278,7 +2274,7 @@ pub trait BufRead: Read { self.fill_buf().map(|b| !b.is_empty()) } - /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached. + /// Reads all bytes into `buf` until the delimiter `byte` or EOF is reached. /// /// This function will read bytes from the underlying stream until the /// delimiter or EOF is found. Once found, all bytes up to, and including, @@ -2337,7 +2333,7 @@ pub trait BufRead: Read { read_until(self, byte, buf) } - /// Skip all bytes until the delimiter `byte` or EOF is reached. + /// Skips all bytes until the delimiter `byte` or EOF is reached. /// /// This function will read (and discard) bytes from the underlying stream until the /// delimiter or EOF is found. @@ -2399,7 +2395,7 @@ pub trait BufRead: Read { skip_until(self, byte) } - /// Read all bytes until a newline (the `0xA` byte) is reached, and append + /// Reads all bytes until a newline (the `0xA` byte) is reached, and append /// them to the provided `String` buffer. /// /// Previous content of the buffer will be preserved. To avoid appending to @@ -3038,7 +3034,7 @@ where } } -/// Read a single byte in a slow, generic way. This is used by the default +/// Reads a single byte in a slow, generic way. This is used by the default /// `spec_read_byte`. #[inline] fn inlined_slow_read_byte(reader: &mut R) -> Option> { diff --git a/std/src/io/stdio.rs b/std/src/io/stdio.rs index 9aee2bb5e1c5c..6de069a518e3d 100644 --- a/std/src/io/stdio.rs +++ b/std/src/io/stdio.rs @@ -3,11 +3,10 @@ #[cfg(test)] mod tests; -use crate::io::prelude::*; - use crate::cell::{Cell, RefCell}; use crate::fmt; use crate::fs::File; +use crate::io::prelude::*; use crate::io::{ self, BorrowedCursor, BufReader, IoSlice, IoSliceMut, LineWriter, Lines, SpecReadByte, }; @@ -1092,7 +1091,7 @@ pub fn try_set_output_capture( OUTPUT_CAPTURE.try_with(move |slot| slot.replace(sink)) } -/// Write `args` to the capture buffer if enabled and possible, or `global_s` +/// Writes `args` to the capture buffer if enabled and possible, or `global_s` /// otherwise. `label` identifies the stream in a panic message. /// /// This function is used to print error messages, so it takes extra diff --git a/std/src/io/tests.rs b/std/src/io/tests.rs index a2c1c430863ab..bb6a53bb290f9 100644 --- a/std/src/io/tests.rs +++ b/std/src/io/tests.rs @@ -1,7 +1,8 @@ use super::{repeat, BorrowedBuf, Cursor, SeekFrom}; use crate::cmp::{self, min}; -use crate::io::{self, IoSlice, IoSliceMut, DEFAULT_BUF_SIZE}; -use crate::io::{BufRead, BufReader, Read, Seek, Write}; +use crate::io::{ + self, BufRead, BufReader, IoSlice, IoSliceMut, Read, Seek, Write, DEFAULT_BUF_SIZE, +}; use crate::mem::MaybeUninit; use crate::ops::Deref; @@ -530,7 +531,7 @@ fn io_slice_advance_slices_beyond_total_length() { assert!(bufs.is_empty()); } -/// Create a new writer that reads from at most `n_bufs` and reads +/// Creates a new writer that reads from at most `n_bufs` and reads /// `per_call` bytes (in total) per call to write. fn test_writer(n_bufs: usize, per_call: usize) -> TestWriter { TestWriter { n_bufs, per_call, written: Vec::new() } @@ -675,13 +676,13 @@ fn cursor_read_exact_eof() { let mut r = slice.clone(); assert!(r.read_exact(&mut [0; 10]).is_err()); - assert!(r.is_empty()); + assert!(Cursor::split(&r).1.is_empty()); let mut r = slice; let buf = &mut [0; 10]; let mut buf = BorrowedBuf::from(buf.as_mut_slice()); assert!(r.read_buf_exact(buf.unfilled()).is_err()); - assert!(r.is_empty()); + assert!(Cursor::split(&r).1.is_empty()); assert_eq!(buf.filled(), b"123456"); } diff --git a/std/src/io/util/tests.rs b/std/src/io/util/tests.rs index 6de91e29c7707..1dff3f3832bd7 100644 --- a/std/src/io/util/tests.rs +++ b/std/src/io/util/tests.rs @@ -1,6 +1,5 @@ use crate::io::prelude::*; use crate::io::{empty, repeat, sink, BorrowedBuf, Empty, Repeat, SeekFrom, Sink}; - use crate::mem::MaybeUninit; #[test] diff --git a/std/src/keyword_docs.rs b/std/src/keyword_docs.rs index 8415f36eba251..c82228fca4bcf 100644 --- a/std/src/keyword_docs.rs +++ b/std/src/keyword_docs.rs @@ -1175,7 +1175,7 @@ mod ref_keyword {} #[doc(keyword = "return")] // -/// Return a value from a function. +/// Returns a value from a function. /// /// A `return` marks the end of an execution path in a function: /// @@ -2310,7 +2310,7 @@ mod where_keyword {} #[doc(alias = "promise")] #[doc(keyword = "async")] // -/// Return a [`Future`] instead of blocking the current thread. +/// Returns a [`Future`] instead of blocking the current thread. /// /// Use `async` in front of `fn`, `closure`, or a `block` to turn the marked code into a `Future`. /// As such the code will not be run immediately, but will only be evaluated when the returned diff --git a/std/src/lib.rs b/std/src/lib.rs index f0a73a308a4a4..05e33d47bac39 100644 --- a/std/src/lib.rs +++ b/std/src/lib.rs @@ -254,6 +254,7 @@ #![deny(fuzzy_provenance_casts)] #![deny(unsafe_op_in_unsafe_fn)] #![allow(rustdoc::redundant_explicit_links)] +#![warn(rustdoc::unescaped_backticks)] // Ensure that std can be linked against panic_abort despite compiled with `-C panic=unwind` #![deny(ffi_unwind_calls)] // std may use features in a platform-specific way @@ -268,14 +269,9 @@ #![cfg_attr(any(windows, target_os = "uefi"), feature(round_char_boundary))] #![cfg_attr(target_family = "wasm", feature(stdarch_wasm_atomic_wait))] #![cfg_attr(target_arch = "wasm64", feature(simd_wasm64))] -#![cfg_attr( - all(any(target_arch = "x86_64", target_arch = "x86"), target_os = "uefi"), - feature(stdarch_x86_has_cpuid) -)] // // Language features: // tidy-alphabetical-start -#![cfg_attr(bootstrap, feature(c_unwind))] #![feature(alloc_error_handler)] #![feature(allocator_internals)] #![feature(allow_internal_unsafe)] @@ -293,6 +289,7 @@ #![feature(doc_masked)] #![feature(doc_notable_trait)] #![feature(dropck_eyepatch)] +#![feature(extended_varargs_abi_support)] #![feature(f128)] #![feature(f16)] #![feature(if_let_guard)] @@ -301,6 +298,7 @@ #![feature(let_chains)] #![feature(link_cfg)] #![feature(linkage)] +#![feature(macro_metavar_expr_concat)] #![feature(min_exhaustive_patterns)] #![feature(min_specialization)] #![feature(must_not_suspend)] @@ -406,7 +404,6 @@ #![feature(const_ip)] #![feature(const_ipv4)] #![feature(const_ipv6)] -#![feature(const_waker)] #![feature(thread_local_internals)] // tidy-alphabetical-end // @@ -470,24 +467,6 @@ pub mod rt; // The Rust prelude pub mod prelude; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::borrow; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::boxed; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::fmt; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::format; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::rc; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::slice; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::str; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::string; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::vec; #[stable(feature = "rust1", since = "1.0.0")] pub use core::any; #[stable(feature = "core_array", since = "1.36.0")] @@ -565,6 +544,25 @@ pub use core::u8; #[allow(deprecated, deprecated_in_future)] pub use core::usize; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::borrow; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::boxed; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::fmt; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::format; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::rc; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::slice; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::str; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::string; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::vec; + #[unstable(feature = "f128", issue = "116909")] pub mod f128; #[unstable(feature = "f16", issue = "116909")] @@ -590,6 +588,8 @@ pub mod panic; #[unstable(feature = "core_pattern_types", issue = "none")] pub mod pat; pub mod path; +#[unstable(feature = "anonymous_pipe", issue = "127154")] +pub mod pipe; pub mod process; pub mod sync; pub mod time; @@ -606,23 +606,23 @@ mod std_float; pub mod simd { #![doc = include_str!("../../portable-simd/crates/core_simd/src/core_simd_docs.md")] - #[doc(inline)] - pub use crate::std_float::StdFloat; #[doc(inline)] pub use core::simd::*; + + #[doc(inline)] + pub use crate::std_float::StdFloat; } #[stable(feature = "futures_api", since = "1.36.0")] pub mod task { //! Types and Traits for working with asynchronous tasks. - #[doc(inline)] - #[stable(feature = "futures_api", since = "1.36.0")] - pub use core::task::*; - #[doc(inline)] #[stable(feature = "wake_trait", since = "1.51.0")] pub use alloc::task::*; + #[doc(inline)] + #[stable(feature = "futures_api", since = "1.36.0")] + pub use core::task::*; } #[doc = include_str!("../../stdarch/crates/core_arch/src/core_arch_docs.md")] @@ -667,35 +667,31 @@ mod panicking; #[allow(dead_code, unused_attributes, fuzzy_provenance_casts, unsafe_op_in_unsafe_fn)] mod backtrace_rs; -// Re-export macros defined in core. -#[stable(feature = "rust1", since = "1.0.0")] -#[allow(deprecated, deprecated_in_future)] -pub use core::{ - assert_eq, assert_ne, debug_assert, debug_assert_eq, debug_assert_ne, matches, todo, r#try, - unimplemented, unreachable, write, writeln, -}; - -// Re-export built-in macros defined through core. -#[stable(feature = "builtin_macro_prelude", since = "1.38.0")] -#[allow(deprecated)] -pub use core::{ - assert, assert_matches, cfg, column, compile_error, concat, concat_idents, const_format_args, - env, file, format_args, format_args_nl, include, include_bytes, include_str, line, log_syntax, - module_path, option_env, stringify, trace_macros, -}; - +#[unstable(feature = "cfg_match", issue = "115585")] +pub use core::cfg_match; #[unstable( feature = "concat_bytes", issue = "87555", reason = "`concat_bytes` is not stable enough for use and is subject to change" )] pub use core::concat_bytes; - -#[unstable(feature = "cfg_match", issue = "115585")] -pub use core::cfg_match; - #[stable(feature = "core_primitive", since = "1.43.0")] pub use core::primitive; +// Re-export built-in macros defined through core. +#[stable(feature = "builtin_macro_prelude", since = "1.38.0")] +#[allow(deprecated)] +pub use core::{ + assert, assert_matches, cfg, column, compile_error, concat, concat_idents, const_format_args, + env, file, format_args, format_args_nl, include, include_bytes, include_str, line, log_syntax, + module_path, option_env, stringify, trace_macros, +}; +// Re-export macros defined in core. +#[stable(feature = "rust1", since = "1.0.0")] +#[allow(deprecated, deprecated_in_future)] +pub use core::{ + assert_eq, assert_ne, debug_assert, debug_assert_eq, debug_assert_ne, matches, todo, r#try, + unimplemented, unreachable, write, writeln, +}; // Include a number of private modules that exist solely to provide // the rustdoc documentation for primitive types. Using `include!` diff --git a/std/src/macros.rs b/std/src/macros.rs index 972b6015932db..ba519afc62b07 100644 --- a/std/src/macros.rs +++ b/std/src/macros.rs @@ -230,7 +230,7 @@ macro_rules! eprintln { /// ```rust /// let a = 2; /// let b = dbg!(a * 2) + 1; -/// // ^-- prints: [src/main.rs:2] a * 2 = 4 +/// // ^-- prints: [src/main.rs:2:9] a * 2 = 4 /// assert_eq!(b, 5); /// ``` /// @@ -281,7 +281,7 @@ macro_rules! eprintln { /// This prints to [stderr]: /// /// ```text,ignore -/// [src/main.rs:4] n.checked_sub(4) = None +/// [src/main.rs:2:22] n.checked_sub(4) = None /// ``` /// /// Naive factorial implementation: @@ -301,15 +301,15 @@ macro_rules! eprintln { /// This prints to [stderr]: /// /// ```text,ignore -/// [src/main.rs:3] n <= 1 = false -/// [src/main.rs:3] n <= 1 = false -/// [src/main.rs:3] n <= 1 = false -/// [src/main.rs:3] n <= 1 = true -/// [src/main.rs:4] 1 = 1 -/// [src/main.rs:5] n * factorial(n - 1) = 2 -/// [src/main.rs:5] n * factorial(n - 1) = 6 -/// [src/main.rs:5] n * factorial(n - 1) = 24 -/// [src/main.rs:11] factorial(4) = 24 +/// [src/main.rs:2:8] n <= 1 = false +/// [src/main.rs:2:8] n <= 1 = false +/// [src/main.rs:2:8] n <= 1 = false +/// [src/main.rs:2:8] n <= 1 = true +/// [src/main.rs:3:9] 1 = 1 +/// [src/main.rs:7:9] n * factorial(n - 1) = 2 +/// [src/main.rs:7:9] n * factorial(n - 1) = 6 +/// [src/main.rs:7:9] n * factorial(n - 1) = 24 +/// [src/main.rs:9:1] factorial(4) = 24 /// ``` /// /// The `dbg!(..)` macro moves the input: diff --git a/std/src/net/ip_addr.rs b/std/src/net/ip_addr.rs index e167fbd1b9cf8..8a9426b61f999 100644 --- a/std/src/net/ip_addr.rs +++ b/std/src/net/ip_addr.rs @@ -2,17 +2,15 @@ #[cfg(all(test, not(target_os = "emscripten")))] mod tests; -use crate::sys::net::netc as c; -use crate::sys_common::{FromInner, IntoInner}; - #[stable(feature = "ip_addr", since = "1.7.0")] pub use core::net::IpAddr; - +#[unstable(feature = "ip", issue = "27709")] +pub use core::net::Ipv6MulticastScope; #[stable(feature = "rust1", since = "1.0.0")] pub use core::net::{Ipv4Addr, Ipv6Addr}; -#[unstable(feature = "ip", issue = "27709")] -pub use core::net::Ipv6MulticastScope; +use crate::sys::net::netc as c; +use crate::sys_common::{FromInner, IntoInner}; impl IntoInner for Ipv4Addr { #[inline] diff --git a/std/src/net/mod.rs b/std/src/net/mod.rs index 858776f14466a..3b19c743b1e24 100644 --- a/std/src/net/mod.rs +++ b/std/src/net/mod.rs @@ -21,7 +21,8 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::io::{self, ErrorKind}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::net::AddrParseError; #[stable(feature = "rust1", since = "1.0.0")] pub use self::ip_addr::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope}; @@ -33,8 +34,7 @@ pub use self::tcp::IntoIncoming; pub use self::tcp::{Incoming, TcpListener, TcpStream}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::udp::UdpSocket; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::net::AddrParseError; +use crate::io::{self, ErrorKind}; mod ip_addr; mod socket_addr; diff --git a/std/src/net/socket_addr.rs b/std/src/net/socket_addr.rs index 421fed9077c5b..84922aabdb569 100644 --- a/std/src/net/socket_addr.rs +++ b/std/src/net/socket_addr.rs @@ -2,19 +2,14 @@ #[cfg(all(test, not(target_os = "emscripten")))] mod tests; -use crate::io; -use crate::iter; -use crate::mem; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::net::{SocketAddr, SocketAddrV4, SocketAddrV6}; + use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -use crate::option; -use crate::slice; use crate::sys::net::netc as c; use crate::sys_common::net::LookupHost; use crate::sys_common::{FromInner, IntoInner}; -use crate::vec; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::net::{SocketAddr, SocketAddrV4, SocketAddrV6}; +use crate::{io, iter, mem, option, slice, vec}; impl FromInner for SocketAddrV4 { fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 { diff --git a/std/src/net/tcp.rs b/std/src/net/tcp.rs index 6336354239b02..22d2dfe65a249 100644 --- a/std/src/net/tcp.rs +++ b/std/src/net/tcp.rs @@ -3,14 +3,12 @@ #[cfg(all(test, not(any(target_os = "emscripten", target_os = "xous"))))] mod tests; -use crate::io::prelude::*; - use crate::fmt; +use crate::io::prelude::*; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; use crate::iter::FusedIterator; use crate::net::{Shutdown, SocketAddr, ToSocketAddrs}; -use crate::sys_common::net as net_imp; -use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::sys_common::{net as net_imp, AsInner, FromInner, IntoInner}; use crate::time::Duration; /// A TCP stream between a local and a remote socket. diff --git a/std/src/net/tcp/tests.rs b/std/src/net/tcp/tests.rs index 3ad046733a634..d26517d74e492 100644 --- a/std/src/net/tcp/tests.rs +++ b/std/src/net/tcp/tests.rs @@ -1,12 +1,11 @@ -use crate::fmt; use crate::io::prelude::*; use crate::io::{BorrowedBuf, IoSlice, IoSliceMut}; use crate::mem::MaybeUninit; use crate::net::test::{next_test_ip4, next_test_ip6}; use crate::net::*; use crate::sync::mpsc::channel; -use crate::thread; use crate::time::{Duration, Instant}; +use crate::{fmt, thread}; fn each_ip(f: &mut dyn FnMut(SocketAddr)) { f(next_test_ip4()); diff --git a/std/src/net/udp.rs b/std/src/net/udp.rs index 60347a11da9c5..32e9086003d6b 100644 --- a/std/src/net/udp.rs +++ b/std/src/net/udp.rs @@ -4,8 +4,7 @@ mod tests; use crate::fmt; use crate::io::{self, ErrorKind}; use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; -use crate::sys_common::net as net_imp; -use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::sys_common::{net as net_imp, AsInner, FromInner, IntoInner}; use crate::time::Duration; /// A UDP socket. diff --git a/std/src/num.rs b/std/src/num.rs index 8910cdea7c0c9..c1e6e7e628c83 100644 --- a/std/src/num.rs +++ b/std/src/num.rs @@ -9,32 +9,27 @@ #[cfg(test)] mod tests; +#[stable(feature = "int_error_matching", since = "1.55.0")] +pub use core::num::IntErrorKind; +#[stable(feature = "generic_nonzero", since = "1.79.0")] +pub use core::num::NonZero; #[stable(feature = "saturating_int_impl", since = "1.74.0")] pub use core::num::Saturating; #[stable(feature = "rust1", since = "1.0.0")] pub use core::num::Wrapping; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::num::{FpCategory, ParseFloatError, ParseIntError, TryFromIntError}; - #[unstable( feature = "nonzero_internals", reason = "implementation detail which may disappear or be replaced at any time", issue = "none" )] pub use core::num::ZeroablePrimitive; - -#[stable(feature = "generic_nonzero", since = "1.79.0")] -pub use core::num::NonZero; - +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::num::{FpCategory, ParseFloatError, ParseIntError, TryFromIntError}; #[stable(feature = "signed_nonzero", since = "1.34.0")] pub use core::num::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize}; - #[stable(feature = "nonzero", since = "1.28.0")] pub use core::num::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize}; -#[stable(feature = "int_error_matching", since = "1.55.0")] -pub use core::num::IntErrorKind; - #[cfg(test)] use crate::fmt; #[cfg(test)] diff --git a/std/src/os/aix/raw.rs b/std/src/os/aix/raw.rs index b4c8dc72cfe5b..13f61fc97226b 100644 --- a/std/src/os/aix/raw.rs +++ b/std/src/os/aix/raw.rs @@ -4,6 +4,5 @@ #[stable(feature = "pthread_t", since = "1.8.0")] pub use libc::pthread_t; - #[stable(feature = "raw_ext", since = "1.1.0")] pub use libc::{blkcnt_t, blksize_t, dev_t, ino_t, mode_t, nlink_t, off_t, stat, time_t}; diff --git a/std/src/os/android/fs.rs b/std/src/os/android/fs.rs index 1beb3cf6e84b5..6b931e3816950 100644 --- a/std/src/os/android/fs.rs +++ b/std/src/os/android/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::android::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/android/net.rs b/std/src/os/android/net.rs index 349e73eaabdaf..960a304fd0c8d 100644 --- a/std/src/os/android/net.rs +++ b/std/src/os/android/net.rs @@ -4,9 +4,7 @@ #[stable(feature = "unix_socket_abstract", since = "1.70.0")] pub use crate::os::net::linux_ext::addr::SocketAddrExt; - #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub use crate::os::net::linux_ext::socket::UnixSocketExt; - #[unstable(feature = "tcp_quickack", issue = "96256")] pub use crate::os::net::linux_ext::tcp::TcpStreamExt; diff --git a/std/src/os/darwin/fs.rs b/std/src/os/darwin/fs.rs index 2032cca311a15..2d154b214b5f0 100644 --- a/std/src/os/darwin/fs.rs +++ b/std/src/os/darwin/fs.rs @@ -1,13 +1,12 @@ #![allow(dead_code)] +#[allow(deprecated)] +use super::raw; use crate::fs::{self, Metadata}; use crate::sealed::Sealed; use crate::sys_common::{AsInner, AsInnerMut, IntoInner}; use crate::time::SystemTime; -#[allow(deprecated)] -use super::raw; - /// OS-specific extensions to [`fs::Metadata`]. /// /// [`fs::Metadata`]: crate::fs::Metadata diff --git a/std/src/os/dragonfly/fs.rs b/std/src/os/dragonfly/fs.rs index 1424fc4c69880..0cd543b2ab97d 100644 --- a/std/src/os/dragonfly/fs.rs +++ b/std/src/os/dragonfly/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::dragonfly::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/emscripten/fs.rs b/std/src/os/emscripten/fs.rs index d5ec8e03c00d1..3282b79ac1c81 100644 --- a/std/src/os/emscripten/fs.rs +++ b/std/src/os/emscripten/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::emscripten::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/espidf/fs.rs b/std/src/os/espidf/fs.rs index 88701dafe20ce..ffff584cda02a 100644 --- a/std/src/os/espidf/fs.rs +++ b/std/src/os/espidf/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::espidf::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/fd/owned.rs b/std/src/os/fd/owned.rs index a1f83029d2727..2d087c03b04b4 100644 --- a/std/src/os/fd/owned.rs +++ b/std/src/os/fd/owned.rs @@ -4,14 +4,12 @@ #![deny(unsafe_op_in_unsafe_fn)] use super::raw::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; -use crate::fmt; -use crate::fs; -use crate::io; use crate::marker::PhantomData; -use crate::mem::forget; +use crate::mem::ManuallyDrop; #[cfg(not(any(target_arch = "wasm32", target_env = "sgx", target_os = "hermit")))] use crate::sys::cvt; use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::{fmt, fs, io}; /// A borrowed file descriptor. /// @@ -24,9 +22,14 @@ use crate::sys_common::{AsInner, FromInner, IntoInner}; /// passed as an argument, it is not captured or consumed, and it never has the /// value `-1`. /// -/// This type's `.to_owned()` implementation returns another `BorrowedFd` -/// rather than an `OwnedFd`. It just makes a trivial copy of the raw file -/// descriptor, which is then borrowed under the same lifetime. +/// This type does not have a [`ToOwned`][crate::borrow::ToOwned] +/// implementation. Calling `.to_owned()` on a variable of this type will call +/// it on `&BorrowedFd` and use `Clone::clone()` like `ToOwned` does for all +/// types implementing `Clone`. The result will be descriptor borrowed under +/// the same lifetime. +/// +/// To obtain an [`OwnedFd`], you can use [`BorrowedFd::try_clone_to_owned`] +/// instead, but this is not supported on all platforms. #[derive(Copy, Clone)] #[repr(transparent)] #[rustc_layout_scalar_valid_range_start(0)] @@ -50,6 +53,8 @@ pub struct BorrowedFd<'fd> { /// descriptor, so it can be used in FFI in places where a file descriptor is /// passed as a consumed argument or returned as an owned value, and it never /// has the value `-1`. +/// +/// You can use [`AsFd::as_fd`] to obtain a [`BorrowedFd`]. #[repr(transparent)] #[rustc_layout_scalar_valid_range_start(0)] // libstd/os/raw/mod.rs assures me that every libstd-supported platform has a @@ -63,7 +68,7 @@ pub struct OwnedFd { } impl BorrowedFd<'_> { - /// Return a `BorrowedFd` holding the given raw file descriptor. + /// Returns a `BorrowedFd` holding the given raw file descriptor. /// /// # Safety /// @@ -141,9 +146,7 @@ impl AsRawFd for OwnedFd { impl IntoRawFd for OwnedFd { #[inline] fn into_raw_fd(self) -> RawFd { - let fd = self.fd; - forget(self); - fd + ManuallyDrop::new(self).fd } } diff --git a/std/src/os/fd/raw.rs b/std/src/os/fd/raw.rs index ef896ea95c9c9..0d99d5492a268 100644 --- a/std/src/os/fd/raw.rs +++ b/std/src/os/fd/raw.rs @@ -2,8 +2,9 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::fs; -use crate::io; +#[cfg(target_os = "hermit")] +use hermit_abi as libc; + #[cfg(target_os = "hermit")] use crate::os::hermit::io::OwnedFd; #[cfg(not(target_os = "hermit"))] @@ -15,8 +16,7 @@ use crate::os::unix::io::OwnedFd; #[cfg(target_os = "wasi")] use crate::os::wasi::io::OwnedFd; use crate::sys_common::{AsInner, IntoInner}; -#[cfg(target_os = "hermit")] -use hermit_abi as libc; +use crate::{fs, io}; /// Raw file descriptors. #[rustc_allowed_through_unstable_modules] @@ -138,6 +138,7 @@ pub trait IntoRawFd { /// let raw_fd: RawFd = f.into_raw_fd(); /// # Ok::<(), io::Error>(()) /// ``` + #[must_use = "losing the raw file descriptor may leak resources"] #[stable(feature = "into_raw_os", since = "1.4.0")] fn into_raw_fd(self) -> RawFd; } diff --git a/std/src/os/fortanix_sgx/arch.rs b/std/src/os/fortanix_sgx/arch.rs index 8358cb9e81b65..4c8048e7152e2 100644 --- a/std/src/os/fortanix_sgx/arch.rs +++ b/std/src/os/fortanix_sgx/arch.rs @@ -4,9 +4,10 @@ //! Software Developer's Manual, Volume 3, Chapter 40. #![unstable(feature = "sgx_platform", issue = "56975")] -use crate::mem::MaybeUninit; use core::arch::asm; +use crate::mem::MaybeUninit; + /// Wrapper struct to force 16-byte alignment. #[repr(align(16))] #[unstable(feature = "sgx_platform", issue = "56975")] diff --git a/std/src/os/fortanix_sgx/mod.rs b/std/src/os/fortanix_sgx/mod.rs index b31dc06f8dfbd..64f4d97ca95e2 100644 --- a/std/src/os/fortanix_sgx/mod.rs +++ b/std/src/os/fortanix_sgx/mod.rs @@ -22,20 +22,12 @@ pub mod usercalls { /// Lowest-level interfaces to usercalls and usercall ABI type definitions. pub mod raw { pub use crate::sys::abi::usercalls::raw::{ - accept_stream, alloc, async_queues, bind_stream, close, connect_stream, exit, flush, - free, insecure_time, launch_thread, read, read_alloc, send, wait, write, - }; - pub use crate::sys::abi::usercalls::raw::{do_usercall, Usercalls as UsercallNrs}; - pub use crate::sys::abi::usercalls::raw::{Register, RegisterArgument, ReturnValue}; - - pub use crate::sys::abi::usercalls::raw::Error; - pub use crate::sys::abi::usercalls::raw::{ - ByteBuffer, Cancel, FifoDescriptor, Return, Usercall, - }; - pub use crate::sys::abi::usercalls::raw::{Fd, Result, Tcs}; - pub use crate::sys::abi::usercalls::raw::{ - EV_RETURNQ_NOT_EMPTY, EV_UNPARK, EV_USERCALLQ_NOT_FULL, FD_STDERR, FD_STDIN, FD_STDOUT, - RESULT_SUCCESS, USERCALL_USER_DEFINED, WAIT_INDEFINITE, WAIT_NO, + accept_stream, alloc, async_queues, bind_stream, close, connect_stream, do_usercall, + exit, flush, free, insecure_time, launch_thread, read, read_alloc, send, wait, write, + ByteBuffer, Cancel, Error, Fd, FifoDescriptor, Register, RegisterArgument, Result, + Return, ReturnValue, Tcs, Usercall, Usercalls as UsercallNrs, EV_RETURNQ_NOT_EMPTY, + EV_UNPARK, EV_USERCALLQ_NOT_FULL, FD_STDERR, FD_STDIN, FD_STDOUT, RESULT_SUCCESS, + USERCALL_USER_DEFINED, WAIT_INDEFINITE, WAIT_NO, }; } } diff --git a/std/src/os/freebsd/fs.rs b/std/src/os/freebsd/fs.rs index 5689a82e00a34..34384a4bcb505 100644 --- a/std/src/os/freebsd/fs.rs +++ b/std/src/os/freebsd/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::freebsd::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/freebsd/net.rs b/std/src/os/freebsd/net.rs index b7e0fdc0a9aab..fcfc5c1c83935 100644 --- a/std/src/os/freebsd/net.rs +++ b/std/src/os/freebsd/net.rs @@ -42,7 +42,7 @@ pub trait UnixSocketExt: Sealed { #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] fn set_local_creds_persistent(&self, local_creds_persistent: bool) -> io::Result<()>; - /// Get a filter name if one had been set previously on the socket. + /// Gets a filter name if one had been set previously on the socket. #[unstable(feature = "acceptfilter", issue = "121891")] fn acceptfilter(&self) -> io::Result<&CStr>; diff --git a/std/src/os/haiku/fs.rs b/std/src/os/haiku/fs.rs index a23a2af8f6e7b..23f6493180b76 100644 --- a/std/src/os/haiku/fs.rs +++ b/std/src/os/haiku/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::haiku::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/hermit/io/net.rs b/std/src/os/hermit/io/net.rs index 8f3802d7873dc..7a774345b231a 100644 --- a/std/src/os/hermit/io/net.rs +++ b/std/src/os/hermit/io/net.rs @@ -1,5 +1,4 @@ -use crate::os::hermit::io::OwnedFd; -use crate::os::hermit::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; +use crate::os::hermit::io::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; use crate::{net, sys}; diff --git a/std/src/os/hermit/mod.rs b/std/src/os/hermit/mod.rs index 02a4b2c3ab5e7..5812206a25759 100644 --- a/std/src/os/hermit/mod.rs +++ b/std/src/os/hermit/mod.rs @@ -1,4 +1,5 @@ #![stable(feature = "rust1", since = "1.0.0")] +#![deny(unsafe_op_in_unsafe_fn)] #[allow(unused_extern_crates)] #[stable(feature = "rust1", since = "1.0.0")] diff --git a/std/src/os/horizon/mod.rs b/std/src/os/horizon/mod.rs index 326d0ae9cb96d..14ce409f42c0b 100644 --- a/std/src/os/horizon/mod.rs +++ b/std/src/os/horizon/mod.rs @@ -1,5 +1,6 @@ //! Definitions for Horizon OS +#![forbid(unsafe_op_in_unsafe_fn)] #![stable(feature = "raw_ext", since = "1.1.0")] pub mod fs; diff --git a/std/src/os/horizon/raw.rs b/std/src/os/horizon/raw.rs index 929fa7db1f964..e5368ea265a13 100644 --- a/std/src/os/horizon/raw.rs +++ b/std/src/os/horizon/raw.rs @@ -38,6 +38,7 @@ pub type time_t = libc::time_t; #[repr(C)] #[derive(Clone)] #[stable(feature = "raw_ext", since = "1.1.0")] +#[allow(dead_code)] // This exists for parity with other `raw` modules, but isn't actually used. pub struct stat { #[stable(feature = "raw_ext", since = "1.1.0")] pub st_dev: dev_t, diff --git a/std/src/os/illumos/fs.rs b/std/src/os/illumos/fs.rs index 63be48b8131b2..75dbe167785db 100644 --- a/std/src/os/illumos/fs.rs +++ b/std/src/os/illumos/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::illumos::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/ios/mod.rs b/std/src/os/ios/mod.rs index 5e130d77b7bfd..52d592ed95afa 100644 --- a/std/src/os/ios/mod.rs +++ b/std/src/os/ios/mod.rs @@ -7,7 +7,6 @@ pub mod fs { #[doc(inline)] #[stable(feature = "file_set_times", since = "1.75.0")] pub use crate::os::darwin::fs::FileTimesExt; - #[doc(inline)] #[stable(feature = "metadata_ext", since = "1.1.0")] pub use crate::os::darwin::fs::MetadataExt; diff --git a/std/src/os/l4re/fs.rs b/std/src/os/l4re/fs.rs index 6d6a535b1e831..0511ddcf19af6 100644 --- a/std/src/os/l4re/fs.rs +++ b/std/src/os/l4re/fs.rs @@ -5,10 +5,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::l4re::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/linux/fs.rs b/std/src/os/linux/fs.rs index ab0b2a3eda3f5..20a7a161a2628 100644 --- a/std/src/os/linux/fs.rs +++ b/std/src/os/linux/fs.rs @@ -5,10 +5,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::linux::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/linux/net.rs b/std/src/os/linux/net.rs index f898e70548706..1de120c8fd366 100644 --- a/std/src/os/linux/net.rs +++ b/std/src/os/linux/net.rs @@ -4,9 +4,7 @@ #[stable(feature = "unix_socket_abstract", since = "1.70.0")] pub use crate::os::net::linux_ext::addr::SocketAddrExt; - #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub use crate::os::net::linux_ext::socket::UnixSocketExt; - #[unstable(feature = "tcp_quickack", issue = "96256")] pub use crate::os::net::linux_ext::tcp::TcpStreamExt; diff --git a/std/src/os/macos/mod.rs b/std/src/os/macos/mod.rs index 3638406b1807d..59fe90834c2b4 100644 --- a/std/src/os/macos/mod.rs +++ b/std/src/os/macos/mod.rs @@ -7,7 +7,6 @@ pub mod fs { #[doc(inline)] #[stable(feature = "file_set_times", since = "1.75.0")] pub use crate::os::darwin::fs::FileTimesExt; - #[doc(inline)] #[stable(feature = "metadata_ext", since = "1.1.0")] pub use crate::os::darwin::fs::MetadataExt; diff --git a/std/src/os/net/linux_ext/tcp.rs b/std/src/os/net/linux_ext/tcp.rs index ff29afe7ed311..c8d012962d45a 100644 --- a/std/src/os/net/linux_ext/tcp.rs +++ b/std/src/os/net/linux_ext/tcp.rs @@ -2,10 +2,9 @@ //! //! [`std::net`]: crate::net -use crate::io; -use crate::net; use crate::sealed::Sealed; use crate::sys_common::AsInner; +use crate::{io, net}; /// Os-specific extensions for [`TcpStream`] /// diff --git a/std/src/os/net/linux_ext/tests.rs b/std/src/os/net/linux_ext/tests.rs index f8dbbfc18e28e..12f35696abc5c 100644 --- a/std/src/os/net/linux_ext/tests.rs +++ b/std/src/os/net/linux_ext/tests.rs @@ -1,9 +1,8 @@ #[test] fn quickack() { - use crate::{ - net::{test::next_test_ip4, TcpListener, TcpStream}, - os::net::linux_ext::tcp::TcpStreamExt, - }; + use crate::net::test::next_test_ip4; + use crate::net::{TcpListener, TcpStream}; + use crate::os::net::linux_ext::tcp::TcpStreamExt; macro_rules! t { ($e:expr) => { @@ -30,10 +29,9 @@ fn quickack() { #[test] #[cfg(target_os = "linux")] fn deferaccept() { - use crate::{ - net::{test::next_test_ip4, TcpListener, TcpStream}, - os::net::linux_ext::tcp::TcpStreamExt, - }; + use crate::net::test::next_test_ip4; + use crate::net::{TcpListener, TcpStream}; + use crate::os::net::linux_ext::tcp::TcpStreamExt; macro_rules! t { ($e:expr) => { diff --git a/std/src/os/netbsd/fs.rs b/std/src/os/netbsd/fs.rs index fe0be069e5e3f..74fbbabb17a5d 100644 --- a/std/src/os/netbsd/fs.rs +++ b/std/src/os/netbsd/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::netbsd::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/netbsd/net.rs b/std/src/os/netbsd/net.rs index b9679c7b3af33..e1950d349bf7d 100644 --- a/std/src/os/netbsd/net.rs +++ b/std/src/os/netbsd/net.rs @@ -42,7 +42,7 @@ pub trait UnixSocketExt: Sealed { #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] fn set_local_creds(&self, local_creds: bool) -> io::Result<()>; - /// Get a filter name if one had been set previously on the socket. + /// Gets a filter name if one had been set previously on the socket. #[unstable(feature = "acceptfilter", issue = "121891")] fn acceptfilter(&self) -> io::Result<&CStr>; diff --git a/std/src/os/openbsd/fs.rs b/std/src/os/openbsd/fs.rs index b8d8d31c5b8cf..e584098476a7b 100644 --- a/std/src/os/openbsd/fs.rs +++ b/std/src/os/openbsd/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::openbsd::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/redox/fs.rs b/std/src/os/redox/fs.rs index 682ca6a2c0309..c6b813f0cc6ce 100644 --- a/std/src/os/redox/fs.rs +++ b/std/src/os/redox/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::redox::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/solaris/fs.rs b/std/src/os/solaris/fs.rs index 0931437370429..9b0527d713891 100644 --- a/std/src/os/solaris/fs.rs +++ b/std/src/os/solaris/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::solaris::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/std/src/os/solid/io.rs b/std/src/os/solid/io.rs index 19b4fe22093c3..2d18f33961506 100644 --- a/std/src/os/solid/io.rs +++ b/std/src/os/solid/io.rs @@ -44,15 +44,12 @@ //! //! [`BorrowedFd<'a>`]: crate::os::solid::io::BorrowedFd -#![deny(unsafe_op_in_unsafe_fn)] #![unstable(feature = "solid_ext", issue = "none")] -use crate::fmt; use crate::marker::PhantomData; -use crate::mem::forget; -use crate::net; -use crate::sys; +use crate::mem::ManuallyDrop; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; +use crate::{fmt, net, sys}; /// Raw file descriptors. pub type RawFd = i32; @@ -99,7 +96,7 @@ pub struct OwnedFd { } impl BorrowedFd<'_> { - /// Return a `BorrowedFd` holding the given raw file descriptor. + /// Returns a `BorrowedFd` holding the given raw file descriptor. /// /// # Safety /// @@ -149,9 +146,7 @@ impl AsRawFd for OwnedFd { impl IntoRawFd for OwnedFd { #[inline] fn into_raw_fd(self) -> RawFd { - let fd = self.fd; - forget(self); - fd + ManuallyDrop::new(self).fd } } @@ -347,6 +342,7 @@ pub trait IntoRawFd { /// This function **transfers ownership** of the underlying file descriptor /// to the caller. Callers are then the unique owners of the file descriptor /// and must close the descriptor once it's no longer needed. + #[must_use = "losing the raw file descriptor may leak resources"] fn into_raw_fd(self) -> RawFd; } diff --git a/std/src/os/solid/mod.rs b/std/src/os/solid/mod.rs index 0bb83c73ddf7c..75824048e2498 100644 --- a/std/src/os/solid/mod.rs +++ b/std/src/os/solid/mod.rs @@ -1,4 +1,5 @@ #![stable(feature = "rust1", since = "1.0.0")] +#![forbid(unsafe_op_in_unsafe_fn)] pub mod ffi; pub mod io; diff --git a/std/src/os/uefi/env.rs b/std/src/os/uefi/env.rs index 5d082e7c11388..cf8ae697e389d 100644 --- a/std/src/os/uefi/env.rs +++ b/std/src/os/uefi/env.rs @@ -2,8 +2,9 @@ #![unstable(feature = "uefi_std", issue = "100499")] +use crate::ffi::c_void; +use crate::ptr::NonNull; use crate::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; -use crate::{ffi::c_void, ptr::NonNull}; static SYSTEM_TABLE: AtomicPtr = AtomicPtr::new(crate::ptr::null_mut()); static IMAGE_HANDLE: AtomicPtr = AtomicPtr::new(crate::ptr::null_mut()); @@ -26,7 +27,7 @@ static BOOT_SERVICES_FLAG: AtomicBool = AtomicBool::new(false); /// standard library is loaded. /// /// # SAFETY -/// Calling this function more than once will panic +/// Calling this function more than once will panic. pub(crate) unsafe fn init_globals(handle: NonNull, system_table: NonNull) { IMAGE_HANDLE .compare_exchange( @@ -47,23 +48,25 @@ pub(crate) unsafe fn init_globals(handle: NonNull, system_table: NonNull BOOT_SERVICES_FLAG.store(true, Ordering::Release) } -/// Get the SystemTable Pointer. +/// Gets the SystemTable Pointer. +/// /// If you want to use `BootServices` then please use [`boot_services`] as it performs some /// additional checks. /// -/// Note: This function panics if the System Table or Image Handle is not initialized +/// Note: This function panics if the System Table or Image Handle is not initialized. pub fn system_table() -> NonNull { try_system_table().unwrap() } -/// Get the ImageHandle Pointer. +/// Gets the ImageHandle Pointer. /// -/// Note: This function panics if the System Table or Image Handle is not initialized +/// Note: This function panics if the System Table or Image Handle is not initialized. pub fn image_handle() -> NonNull { try_image_handle().unwrap() } -/// Get the BootServices Pointer. +/// Gets the BootServices Pointer. +/// /// This function also checks if `ExitBootServices` has already been called. pub fn boot_services() -> Option> { if BOOT_SERVICES_FLAG.load(Ordering::Acquire) { @@ -75,14 +78,16 @@ pub fn boot_services() -> Option> { } } -/// Get the SystemTable Pointer. -/// This function is mostly intended for places where panic is not an option +/// Gets the SystemTable Pointer. +/// +/// This function is mostly intended for places where panic is not an option. pub(crate) fn try_system_table() -> Option> { NonNull::new(SYSTEM_TABLE.load(Ordering::Acquire)) } -/// Get the SystemHandle Pointer. -/// This function is mostly intended for places where panicking is not an option +/// Gets the SystemHandle Pointer. +/// +/// This function is mostly intended for places where panicking is not an option. pub(crate) fn try_image_handle() -> Option> { NonNull::new(IMAGE_HANDLE.load(Ordering::Acquire)) } diff --git a/std/src/os/unix/fs.rs b/std/src/os/unix/fs.rs index 970023d8cf19e..caf6980afd91b 100644 --- a/std/src/os/unix/fs.rs +++ b/std/src/os/unix/fs.rs @@ -4,18 +4,18 @@ #![stable(feature = "rust1", since = "1.0.0")] +#[allow(unused_imports)] +use io::{Read, Write}; + use super::platform::fs::MetadataExt as _; +// Used for `File::read` on intra-doc links +use crate::ffi::OsStr; use crate::fs::{self, OpenOptions, Permissions}; -use crate::io; use crate::os::unix::io::{AsFd, AsRawFd}; use crate::path::Path; -use crate::sys; -use crate::sys_common::{AsInner, AsInnerMut, FromInner}; -// Used for `File::read` on intra-doc links -use crate::ffi::OsStr; use crate::sealed::Sealed; -#[allow(unused_imports)] -use io::{Read, Write}; +use crate::sys_common::{AsInner, AsInnerMut, FromInner}; +use crate::{io, sys}; // Tests for this module #[cfg(test)] @@ -1064,7 +1064,7 @@ pub fn lchown>(dir: P, uid: Option, gid: Option) -> io: /// } /// ``` #[stable(feature = "unix_chroot", since = "1.56.0")] -#[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))] +#[cfg(not(target_os = "fuchsia"))] pub fn chroot>(dir: P) -> io::Result<()> { sys::fs::chroot(dir.as_ref()) } diff --git a/std/src/os/unix/net/ancillary.rs b/std/src/os/unix/net/ancillary.rs index fe8e2be93724e..9b487a6298247 100644 --- a/std/src/os/unix/net/ancillary.rs +++ b/std/src/os/unix/net/ancillary.rs @@ -164,7 +164,7 @@ struct AncillaryDataIter<'a, T> { } impl<'a, T> AncillaryDataIter<'a, T> { - /// Create `AncillaryDataIter` struct to iterate through the data unit in the control message. + /// Creates `AncillaryDataIter` struct to iterate through the data unit in the control message. /// /// # Safety /// @@ -220,7 +220,7 @@ pub struct SocketCred(libc::sockcred2); #[doc(cfg(any(target_os = "android", target_os = "linux")))] #[cfg(any(target_os = "android", target_os = "linux"))] impl SocketCred { - /// Create a Unix credential struct. + /// Creates a Unix credential struct. /// /// PID, UID and GID is set to 0. #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] @@ -235,7 +235,7 @@ impl SocketCred { self.0.pid = pid; } - /// Get the current PID. + /// Gets the current PID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_pid(&self) -> libc::pid_t { @@ -248,7 +248,7 @@ impl SocketCred { self.0.uid = uid; } - /// Get the current UID. + /// Gets the current UID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_uid(&self) -> libc::uid_t { @@ -261,7 +261,7 @@ impl SocketCred { self.0.gid = gid; } - /// Get the current GID. + /// Gets the current GID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_gid(&self) -> libc::gid_t { @@ -271,7 +271,7 @@ impl SocketCred { #[cfg(target_os = "freebsd")] impl SocketCred { - /// Create a Unix credential struct. + /// Creates a Unix credential struct. /// /// PID, UID and GID is set to 0. #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] @@ -295,7 +295,7 @@ impl SocketCred { self.0.sc_pid = pid; } - /// Get the current PID. + /// Gets the current PID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_pid(&self) -> libc::pid_t { @@ -308,7 +308,7 @@ impl SocketCred { self.0.sc_euid = uid; } - /// Get the current UID. + /// Gets the current UID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_uid(&self) -> libc::uid_t { @@ -321,7 +321,7 @@ impl SocketCred { self.0.sc_egid = gid; } - /// Get the current GID. + /// Gets the current GID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_gid(&self) -> libc::gid_t { @@ -331,7 +331,7 @@ impl SocketCred { #[cfg(target_os = "netbsd")] impl SocketCred { - /// Create a Unix credential struct. + /// Creates a Unix credential struct. /// /// PID, UID and GID is set to 0. #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] @@ -353,7 +353,7 @@ impl SocketCred { self.0.sc_pid = pid; } - /// Get the current PID. + /// Gets the current PID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_pid(&self) -> libc::pid_t { @@ -366,7 +366,7 @@ impl SocketCred { self.0.sc_uid = uid; } - /// Get the current UID. + /// Gets the current UID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_uid(&self) -> libc::uid_t { @@ -379,7 +379,7 @@ impl SocketCred { self.0.sc_gid = gid; } - /// Get the current GID. + /// Gets the current GID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_gid(&self) -> libc::gid_t { @@ -466,7 +466,7 @@ pub enum AncillaryData<'a> { } impl<'a> AncillaryData<'a> { - /// Create an `AncillaryData::ScmRights` variant. + /// Creates an `AncillaryData::ScmRights` variant. /// /// # Safety /// @@ -478,7 +478,7 @@ impl<'a> AncillaryData<'a> { AncillaryData::ScmRights(scm_rights) } - /// Create an `AncillaryData::ScmCredentials` variant. + /// Creates an `AncillaryData::ScmCredentials` variant. /// /// # Safety /// @@ -605,7 +605,7 @@ pub struct SocketAncillary<'a> { } impl<'a> SocketAncillary<'a> { - /// Create an ancillary data with the given buffer. + /// Creates an ancillary data with the given buffer. /// /// # Example /// diff --git a/std/src/os/unix/net/datagram.rs b/std/src/os/unix/net/datagram.rs index b29f9099a1111..a605c3d4a2602 100644 --- a/std/src/os/unix/net/datagram.rs +++ b/std/src/os/unix/net/datagram.rs @@ -1,3 +1,17 @@ +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "solaris", + target_os = "illumos", + target_os = "haiku", + target_os = "nto", +))] +use libc::MSG_NOSIGNAL; + #[cfg(any(doc, target_os = "android", target_os = "linux"))] use super::{recv_vectored_with_ancillary_from, send_vectored_with_ancillary_to, SocketAncillary}; use super::{sockaddr_un, SocketAddr}; @@ -12,18 +26,6 @@ use crate::sys::net::Socket; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; use crate::{fmt, io}; - -#[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "openbsd", - target_os = "netbsd", - target_os = "haiku", - target_os = "nto", -))] -use libc::MSG_NOSIGNAL; #[cfg(not(any( target_os = "linux", target_os = "android", @@ -31,6 +33,8 @@ use libc::MSG_NOSIGNAL; target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", + target_os = "solaris", + target_os = "illumos", target_os = "haiku", target_os = "nto", )))] diff --git a/std/src/os/unix/net/tests.rs b/std/src/os/unix/net/tests.rs index e456e41b21c88..21e2176185d25 100644 --- a/std/src/os/unix/net/tests.rs +++ b/std/src/os/unix/net/tests.rs @@ -1,18 +1,16 @@ use super::*; use crate::io::prelude::*; use crate::io::{self, ErrorKind, IoSlice, IoSliceMut}; +#[cfg(target_os = "android")] +use crate::os::android::net::{SocketAddrExt, UnixSocketExt}; +#[cfg(target_os = "linux")] +use crate::os::linux::net::{SocketAddrExt, UnixSocketExt}; #[cfg(any(target_os = "android", target_os = "linux"))] use crate::os::unix::io::AsRawFd; use crate::sys_common::io::test::tmpdir; use crate::thread; use crate::time::Duration; -#[cfg(target_os = "android")] -use crate::os::android::net::{SocketAddrExt, UnixSocketExt}; - -#[cfg(target_os = "linux")] -use crate::os::linux::net::{SocketAddrExt, UnixSocketExt}; - macro_rules! or_panic { ($e:expr) => { match $e { diff --git a/std/src/os/unix/net/ucred.rs b/std/src/os/unix/net/ucred.rs index 1497e730bbf15..b96e373ad0ae3 100644 --- a/std/src/os/unix/net/ucred.rs +++ b/std/src/os/unix/net/ucred.rs @@ -23,9 +23,8 @@ pub struct UCred { pub pid: Option, } -#[cfg(any(target_os = "android", target_os = "linux"))] -pub(super) use self::impl_linux::peer_cred; - +#[cfg(target_vendor = "apple")] +pub(super) use self::impl_apple::peer_cred; #[cfg(any( target_os = "dragonfly", target_os = "freebsd", @@ -34,17 +33,17 @@ pub(super) use self::impl_linux::peer_cred; target_os = "nto" ))] pub(super) use self::impl_bsd::peer_cred; - -#[cfg(target_vendor = "apple")] -pub(super) use self::impl_apple::peer_cred; +#[cfg(any(target_os = "android", target_os = "linux"))] +pub(super) use self::impl_linux::peer_cred; #[cfg(any(target_os = "linux", target_os = "android"))] mod impl_linux { + use libc::{c_void, getsockopt, socklen_t, ucred, SOL_SOCKET, SO_PEERCRED}; + use super::UCred; use crate::os::unix::io::AsRawFd; use crate::os::unix::net::UnixStream; use crate::{io, mem}; - use libc::{c_void, getsockopt, socklen_t, ucred, SOL_SOCKET, SO_PEERCRED}; pub fn peer_cred(socket: &UnixStream) -> io::Result { let ucred_size = mem::size_of::(); @@ -99,11 +98,12 @@ mod impl_bsd { #[cfg(target_vendor = "apple")] mod impl_apple { + use libc::{c_void, getpeereid, getsockopt, pid_t, socklen_t, LOCAL_PEERPID, SOL_LOCAL}; + use super::UCred; use crate::os::unix::io::AsRawFd; use crate::os::unix::net::UnixStream; use crate::{io, mem}; - use libc::{c_void, getpeereid, getsockopt, pid_t, socklen_t, LOCAL_PEERPID, SOL_LOCAL}; pub fn peer_cred(socket: &UnixStream) -> io::Result { let mut cred = UCred { uid: 1, gid: 1, pid: None }; diff --git a/std/src/os/unix/net/ucred/tests.rs b/std/src/os/unix/net/ucred/tests.rs index a6cc81318fc08..59414f4dcae13 100644 --- a/std/src/os/unix/net/ucred/tests.rs +++ b/std/src/os/unix/net/ucred/tests.rs @@ -1,6 +1,7 @@ -use crate::os::unix::net::UnixStream; use libc::{getegid, geteuid, getpid}; +use crate::os::unix::net::UnixStream; + #[test] #[cfg(any( target_os = "android", diff --git a/std/src/os/unix/process.rs b/std/src/os/unix/process.rs index 72ea54bd77203..c53423675bd00 100644 --- a/std/src/os/unix/process.rs +++ b/std/src/os/unix/process.rs @@ -4,15 +4,13 @@ #![stable(feature = "rust1", since = "1.0.0")] +use cfg_if::cfg_if; + use crate::ffi::OsStr; -use crate::io; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; -use crate::process; use crate::sealed::Sealed; -use crate::sys; use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; - -use cfg_if::cfg_if; +use crate::{io, process, sys}; cfg_if! { if #[cfg(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon", target_os = "vita"))] { @@ -444,7 +442,7 @@ impl From for OwnedFd { } } -/// Create a `ChildStdin` from the provided `OwnedFd`. +/// Creates a `ChildStdin` from the provided `OwnedFd`. /// /// The provided file descriptor must point to a pipe /// with the `CLOEXEC` flag set. @@ -475,7 +473,7 @@ impl From for OwnedFd { } } -/// Create a `ChildStdout` from the provided `OwnedFd`. +/// Creates a `ChildStdout` from the provided `OwnedFd`. /// /// The provided file descriptor must point to a pipe /// with the `CLOEXEC` flag set. @@ -506,7 +504,7 @@ impl From for OwnedFd { } } -/// Create a `ChildStderr` from the provided `OwnedFd`. +/// Creates a `ChildStderr` from the provided `OwnedFd`. /// /// The provided file descriptor must point to a pipe /// with the `CLOEXEC` flag set. diff --git a/std/src/os/vita/mod.rs b/std/src/os/vita/mod.rs index da9edd12f7b03..92a2bf0a59ab5 100644 --- a/std/src/os/vita/mod.rs +++ b/std/src/os/vita/mod.rs @@ -1,5 +1,6 @@ //! Definitions for vita +#![forbid(unsafe_op_in_unsafe_fn)] #![stable(feature = "raw_ext", since = "1.1.0")] pub mod fs; diff --git a/std/src/os/vita/raw.rs b/std/src/os/vita/raw.rs index 74cae4d4135d1..e4b65ef1ed767 100644 --- a/std/src/os/vita/raw.rs +++ b/std/src/os/vita/raw.rs @@ -10,9 +10,6 @@ )] #![allow(deprecated)] -use crate::os::raw::c_long; -use crate::os::unix::raw::{gid_t, uid_t}; - #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = libc::pthread_t; @@ -34,37 +31,3 @@ pub type off_t = libc::off_t; #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = libc::time_t; - -#[repr(C)] -#[derive(Clone)] -#[stable(feature = "raw_ext", since = "1.1.0")] -pub struct stat { - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_dev: dev_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_ino: ino_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_mode: mode_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_nlink: nlink_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_uid: uid_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_gid: gid_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_rdev: dev_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_size: off_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_atime: time_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_mtime: time_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_ctime: time_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_blksize: blksize_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_blocks: blkcnt_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_spare4: [c_long; 2usize], -} diff --git a/std/src/os/wasi/fs.rs b/std/src/os/wasi/fs.rs index 46fc2a50de911..a58ca543d6777 100644 --- a/std/src/os/wasi/fs.rs +++ b/std/src/os/wasi/fs.rs @@ -5,14 +5,15 @@ #![deny(unsafe_op_in_unsafe_fn)] #![unstable(feature = "wasi_ext", issue = "71213")] +// Used for `File::read` on intra-doc links +#[allow(unused_imports)] +use io::{Read, Write}; + use crate::ffi::OsStr; use crate::fs::{self, File, Metadata, OpenOptions}; use crate::io::{self, IoSlice, IoSliceMut}; use crate::path::{Path, PathBuf}; use crate::sys_common::{AsInner, AsInnerMut, FromInner}; -// Used for `File::read` on intra-doc links -#[allow(unused_imports)] -use io::{Read, Write}; /// WASI-specific extensions to [`File`]. pub trait FileExt { @@ -169,55 +170,55 @@ pub trait FileExt { #[doc(alias = "fd_tell")] fn tell(&self) -> io::Result; - /// Adjust the flags associated with this file. + /// Adjusts the flags associated with this file. /// /// This corresponds to the `fd_fdstat_set_flags` syscall. #[doc(alias = "fd_fdstat_set_flags")] fn fdstat_set_flags(&self, flags: u16) -> io::Result<()>; - /// Adjust the rights associated with this file. + /// Adjusts the rights associated with this file. /// /// This corresponds to the `fd_fdstat_set_rights` syscall. #[doc(alias = "fd_fdstat_set_rights")] fn fdstat_set_rights(&self, rights: u64, inheriting: u64) -> io::Result<()>; - /// Provide file advisory information on a file descriptor. + /// Provides file advisory information on a file descriptor. /// /// This corresponds to the `fd_advise` syscall. #[doc(alias = "fd_advise")] fn advise(&self, offset: u64, len: u64, advice: u8) -> io::Result<()>; - /// Force the allocation of space in a file. + /// Forces the allocation of space in a file. /// /// This corresponds to the `fd_allocate` syscall. #[doc(alias = "fd_allocate")] fn allocate(&self, offset: u64, len: u64) -> io::Result<()>; - /// Create a directory. + /// Creates a directory. /// /// This corresponds to the `path_create_directory` syscall. #[doc(alias = "path_create_directory")] fn create_directory>(&self, dir: P) -> io::Result<()>; - /// Read the contents of a symbolic link. + /// Reads the contents of a symbolic link. /// /// This corresponds to the `path_readlink` syscall. #[doc(alias = "path_readlink")] fn read_link>(&self, path: P) -> io::Result; - /// Return the attributes of a file or directory. + /// Returns the attributes of a file or directory. /// /// This corresponds to the `path_filestat_get` syscall. #[doc(alias = "path_filestat_get")] fn metadata_at>(&self, lookup_flags: u32, path: P) -> io::Result; - /// Unlink a file. + /// Unlinks a file. /// /// This corresponds to the `path_unlink_file` syscall. #[doc(alias = "path_unlink_file")] fn remove_file>(&self, path: P) -> io::Result<()>; - /// Remove a directory. + /// Removes a directory. /// /// This corresponds to the `path_remove_directory` syscall. #[doc(alias = "path_remove_directory")] @@ -501,7 +502,7 @@ impl DirEntryExt for fs::DirEntry { } } -/// Create a hard link. +/// Creates a hard link. /// /// This corresponds to the `path_link` syscall. #[doc(alias = "path_link")] @@ -520,7 +521,7 @@ pub fn link, U: AsRef>( ) } -/// Rename a file or directory. +/// Renames a file or directory. /// /// This corresponds to the `path_rename` syscall. #[doc(alias = "path_rename")] @@ -537,7 +538,7 @@ pub fn rename, U: AsRef>( ) } -/// Create a symbolic link. +/// Creates a symbolic link. /// /// This corresponds to the `path_symlink` syscall. #[doc(alias = "path_symlink")] @@ -551,7 +552,7 @@ pub fn symlink, U: AsRef>( .symlink(osstr2str(old_path.as_ref().as_ref())?, osstr2str(new_path.as_ref().as_ref())?) } -/// Create a symbolic link. +/// Creates a symbolic link. /// /// This is a convenience API similar to `std::os::unix::fs::symlink` and /// `std::os::windows::fs::symlink_file` and `std::os::windows::fs::symlink_dir`. diff --git a/std/src/os/wasi/net/mod.rs b/std/src/os/wasi/net/mod.rs index 73c097d4a50ab..4704dd574517a 100644 --- a/std/src/os/wasi/net/mod.rs +++ b/std/src/os/wasi/net/mod.rs @@ -2,9 +2,8 @@ #![unstable(feature = "wasi_ext", issue = "71213")] -use crate::io; -use crate::net; use crate::sys_common::AsInner; +use crate::{io, net}; /// WASI-specific extensions to [`std::net::TcpListener`]. /// diff --git a/std/src/os/windows/ffi.rs b/std/src/os/windows/ffi.rs index 96bab59d3f8d7..496443dbbc3ac 100644 --- a/std/src/os/windows/ffi.rs +++ b/std/src/os/windows/ffi.rs @@ -56,11 +56,10 @@ use crate::ffi::{OsStr, OsString}; use crate::sealed::Sealed; use crate::sys::os_str::Buf; -use crate::sys_common::wtf8::Wtf8Buf; -use crate::sys_common::{AsInner, FromInner}; - #[stable(feature = "rust1", since = "1.0.0")] pub use crate::sys_common::wtf8::EncodeWide; +use crate::sys_common::wtf8::Wtf8Buf; +use crate::sys_common::{AsInner, FromInner}; /// Windows-specific extensions to [`OsString`]. /// diff --git a/std/src/os/windows/fs.rs b/std/src/os/windows/fs.rs index 27947d91c99de..3dcde43cfec78 100644 --- a/std/src/os/windows/fs.rs +++ b/std/src/os/windows/fs.rs @@ -5,12 +5,11 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::fs::{self, Metadata, OpenOptions}; -use crate::io; use crate::path::Path; use crate::sealed::Sealed; -use crate::sys; use crate::sys_common::{AsInner, AsInnerMut, IntoInner}; use crate::time::SystemTime; +use crate::{io, sys}; /// Windows-specific extensions to [`fs::File`]. #[stable(feature = "file_offset", since = "1.15.0")] @@ -471,6 +470,13 @@ pub trait MetadataExt { /// `fs::metadata` or `File::metadata`, then this will return `Some`. #[unstable(feature = "windows_by_handle", issue = "63010")] fn file_index(&self) -> Option; + + /// Returns the change time, which is the last time file metadata was changed, such as + /// renames, attributes, etc + /// + /// This will return `None` if the `Metadata` instance was not created using the `FILE_BASIC_INFO` type. + #[unstable(feature = "windows_change_time", issue = "121478")] + fn change_time(&self) -> Option; } #[stable(feature = "metadata_ext", since = "1.1.0")] @@ -499,6 +505,9 @@ impl MetadataExt for Metadata { fn file_index(&self) -> Option { self.as_inner().file_index() } + fn change_time(&self) -> Option { + self.as_inner().changed_u64() + } } /// Windows-specific extensions to [`fs::FileType`]. @@ -621,7 +630,7 @@ pub fn symlink_dir, Q: AsRef>(original: P, link: Q) -> io:: sys::fs::symlink_inner(original.as_ref(), link.as_ref(), true) } -/// Create a junction point. +/// Creates a junction point. /// /// The `link` path will be a directory junction pointing to the original path. /// If `link` is a relative path then it will be made absolute prior to creating the junction point. diff --git a/std/src/os/windows/io/handle.rs b/std/src/os/windows/io/handle.rs index a9d1983dce610..a4fa94e2b96a4 100644 --- a/std/src/os/windows/io/handle.rs +++ b/std/src/os/windows/io/handle.rs @@ -3,15 +3,11 @@ #![stable(feature = "io_safety", since = "1.63.0")] use super::raw::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle}; -use crate::fmt; -use crate::fs; -use crate::io; use crate::marker::PhantomData; -use crate::mem::{forget, ManuallyDrop}; -use crate::ptr; -use crate::sys; +use crate::mem::ManuallyDrop; use crate::sys::cvt; use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::{fmt, fs, io, ptr, sys}; /// A borrowed handle. /// @@ -135,7 +131,7 @@ unsafe impl Sync for HandleOrInvalid {} unsafe impl Sync for BorrowedHandle<'_> {} impl BorrowedHandle<'_> { - /// Return a `BorrowedHandle` holding the given raw handle. + /// Returns a `BorrowedHandle` holding the given raw handle. /// /// # Safety /// @@ -319,9 +315,7 @@ impl AsRawHandle for OwnedHandle { impl IntoRawHandle for OwnedHandle { #[inline] fn into_raw_handle(self) -> RawHandle { - let handle = self.handle; - forget(self); - handle + ManuallyDrop::new(self).handle } } diff --git a/std/src/os/windows/io/raw.rs b/std/src/os/windows/io/raw.rs index 343cc6e4a8a5a..6658248d574c9 100644 --- a/std/src/os/windows/io/raw.rs +++ b/std/src/os/windows/io/raw.rs @@ -2,16 +2,12 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::fs; -use crate::io; -use crate::net; #[cfg(doc)] use crate::os::windows::io::{AsHandle, AsSocket}; use crate::os::windows::io::{OwnedHandle, OwnedSocket}; use crate::os::windows::raw; -use crate::ptr; -use crate::sys; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; +use crate::{fs, io, net, ptr, sys}; /// Raw HANDLEs. #[stable(feature = "rust1", since = "1.0.0")] @@ -44,7 +40,7 @@ pub trait AsRawHandle { fn as_raw_handle(&self) -> RawHandle; } -/// Construct I/O objects from raw handles. +/// Constructs I/O objects from raw handles. #[stable(feature = "from_raw_os", since = "1.1.0")] pub trait FromRawHandle { /// Constructs a new I/O object from the specified raw handle. @@ -89,6 +85,7 @@ pub trait IntoRawHandle { /// However, transferring ownership is not strictly required. Use a /// `Into::into` implementation for an API which strictly /// transfers ownership. + #[must_use = "losing the raw handle may leak resources"] #[stable(feature = "into_raw_os", since = "1.4.0")] fn into_raw_handle(self) -> RawHandle; } @@ -232,6 +229,7 @@ pub trait IntoRawSocket { /// However, transferring ownership is not strictly required. Use a /// `Into::into` implementation for an API which strictly /// transfers ownership. + #[must_use = "losing the raw socket may leak resources"] #[stable(feature = "into_raw_os", since = "1.4.0")] fn into_raw_socket(self) -> RawSocket; } diff --git a/std/src/os/windows/io/socket.rs b/std/src/os/windows/io/socket.rs index 4334d041439d9..1fcfb6e73ad03 100644 --- a/std/src/os/windows/io/socket.rs +++ b/std/src/os/windows/io/socket.rs @@ -3,14 +3,11 @@ #![stable(feature = "io_safety", since = "1.63.0")] use super::raw::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; -use crate::mem; -use crate::mem::forget; -use crate::sys; +use crate::mem::{self, ManuallyDrop}; #[cfg(not(target_vendor = "uwp"))] use crate::sys::cvt; +use crate::{fmt, io, sys}; /// A borrowed socket. /// @@ -64,7 +61,7 @@ pub struct OwnedSocket { } impl BorrowedSocket<'_> { - /// Return a `BorrowedSocket` holding the given raw socket. + /// Returns a `BorrowedSocket` holding the given raw socket. /// /// # Safety /// @@ -191,9 +188,7 @@ impl AsRawSocket for OwnedSocket { impl IntoRawSocket for OwnedSocket { #[inline] fn into_raw_socket(self) -> RawSocket { - let socket = self.socket; - forget(self); - socket + ManuallyDrop::new(self).socket } } diff --git a/std/src/os/windows/process.rs b/std/src/os/windows/process.rs index 3927b2ed9bb5c..c2830d2eb61d1 100644 --- a/std/src/os/windows/process.rs +++ b/std/src/os/windows/process.rs @@ -8,10 +8,9 @@ use crate::ffi::OsStr; use crate::os::windows::io::{ AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle, OwnedHandle, RawHandle, }; -use crate::process; use crate::sealed::Sealed; -use crate::sys; use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; +use crate::{process, sys}; #[stable(feature = "process_extensions", since = "1.2.0")] impl FromRawHandle for process::Stdio { @@ -109,7 +108,7 @@ impl IntoRawHandle for process::ChildStderr { } } -/// Create a `ChildStdin` from the provided `OwnedHandle`. +/// Creates a `ChildStdin` from the provided `OwnedHandle`. /// /// The provided handle must be asynchronous, as reading and /// writing from and to it is implemented using asynchronous APIs. @@ -122,7 +121,7 @@ impl From for process::ChildStdin { } } -/// Create a `ChildStdout` from the provided `OwnedHandle`. +/// Creates a `ChildStdout` from the provided `OwnedHandle`. /// /// The provided handle must be asynchronous, as reading and /// writing from and to it is implemented using asynchronous APIs. @@ -135,7 +134,7 @@ impl From for process::ChildStdout { } } -/// Create a `ChildStderr` from the provided `OwnedHandle`. +/// Creates a `ChildStderr` from the provided `OwnedHandle`. /// /// The provided handle must be asynchronous, as reading and /// writing from and to it is implemented using asynchronous APIs. diff --git a/std/src/os/xous/ffi.rs b/std/src/os/xous/ffi.rs index e9a9f53372026..1a4a940bf358a 100644 --- a/std/src/os/xous/ffi.rs +++ b/std/src/os/xous/ffi.rs @@ -274,7 +274,7 @@ fn connect_impl(address: ServerAddress, blocking: bool) -> Result Result { connect_impl(address, true) } -/// Attempt to connect to a Xous server represented by the specified `address`. +/// Attempts to connect to a Xous server represented by the specified `address`. /// /// If the server does not exist then None is returned. pub(crate) fn try_connect(address: ServerAddress) -> Result, Error> { @@ -293,7 +293,7 @@ pub(crate) fn try_connect(address: ServerAddress) -> Result, } } -/// Terminate the current process and return the specified code to the parent process. +/// Terminates the current process and returns the specified code to the parent process. pub(crate) fn exit(return_code: u32) -> ! { let a0 = Syscall::TerminateProcess as usize; let a1 = return_code as usize; @@ -320,7 +320,7 @@ pub(crate) fn exit(return_code: u32) -> ! { unreachable!(); } -/// Suspend the current thread and allow another thread to run. This thread may +/// Suspends the current thread and allow another thread to run. This thread may /// continue executing again immediately if there are no other threads available /// to run on the system. pub(crate) fn do_yield() { @@ -348,9 +348,11 @@ pub(crate) fn do_yield() { }; } -/// Allocate memory from the system. An optional physical and/or virtual address -/// may be specified in order to ensure memory is allocated at specific offsets, -/// otherwise the kernel will select an address. +/// Allocates memory from the system. +/// +/// An optional physical and/or virtual address may be specified in order to +/// ensure memory is allocated at specific offsets, otherwise the kernel will +/// select an address. /// /// # Safety /// @@ -400,7 +402,7 @@ pub(crate) unsafe fn map_memory( } } -/// Destroy the given memory, returning it to the compiler. +/// Destroys the given memory, returning it to the compiler. /// /// Safety: The memory pointed to by `range` should not be used after this /// function returns, even if this function returns Err(). @@ -439,9 +441,10 @@ pub(crate) unsafe fn unmap_memory(range: *mut [T]) -> Result<(), Error> { } } -/// Adjust the memory flags for the given range. This can be used to remove flags -/// from a given region in order to harden memory access. Note that flags may -/// only be removed and may never be added. +/// Adjusts the memory flags for the given range. +/// +/// This can be used to remove flags from a given region in order to harden +/// memory access. Note that flags may only be removed and may never be added. /// /// Safety: The memory pointed to by `range` may become inaccessible or have its /// mutability removed. It is up to the caller to ensure that the flags specified @@ -484,7 +487,7 @@ pub(crate) unsafe fn update_memory_flags( } } -/// Create a thread with a given stack and up to four arguments +/// Creates a thread with a given stack and up to four arguments. pub(crate) fn create_thread( start: *mut usize, stack: *mut [u8], @@ -527,7 +530,7 @@ pub(crate) fn create_thread( } } -/// Wait for the given thread to terminate and return the exit code from that thread. +/// Waits for the given thread to terminate and returns the exit code from that thread. pub(crate) fn join_thread(thread_id: ThreadId) -> Result { let mut a0 = Syscall::JoinThread as usize; let mut a1 = thread_id.into(); @@ -567,7 +570,7 @@ pub(crate) fn join_thread(thread_id: ThreadId) -> Result { } } -/// Get the current thread's ID +/// Gets the current thread's ID. pub(crate) fn thread_id() -> Result { let mut a0 = Syscall::GetThreadId as usize; let mut a1 = 0; @@ -603,7 +606,7 @@ pub(crate) fn thread_id() -> Result { } } -/// Adjust the given `knob` limit to match the new value `new`. The current value must +/// Adjusts the given `knob` limit to match the new value `new`. The current value must /// match the `current` in order for this to take effect. /// /// The new value is returned as a result of this call. If the call fails, then the old diff --git a/std/src/os/xous/services.rs b/std/src/os/xous/services.rs index a75be1b857003..ddf0236f5ad74 100644 --- a/std/src/os/xous/services.rs +++ b/std/src/os/xous/services.rs @@ -1,6 +1,7 @@ -use crate::os::xous::ffi::Connection; use core::sync::atomic::{AtomicU32, Ordering}; +use crate::os::xous::ffi::Connection; + mod dns; pub(crate) use dns::*; @@ -83,7 +84,7 @@ mod ns { } } -/// Attempt to connect to a server by name. If the server does not exist, this will +/// Attempts to connect to a server by name. If the server does not exist, this will /// block until the server is created. /// /// Note that this is different from connecting to a server by address. Server @@ -94,7 +95,7 @@ pub fn connect(name: &str) -> Option { ns::connect_with_name(name) } -/// Attempt to connect to a server by name. If the server does not exist, this will +/// Attempts to connect to a server by name. If the server does not exist, this will /// immediately return `None`. /// /// Note that this is different from connecting to a server by address. Server @@ -107,7 +108,7 @@ pub fn try_connect(name: &str) -> Option { static NAME_SERVER_CONNECTION: AtomicU32 = AtomicU32::new(0); -/// Return a `Connection` to the name server. If the name server has not been started, +/// Returns a `Connection` to the name server. If the name server has not been started, /// then this call will block until the name server has been started. The `Connection` /// will be shared among all connections in a process, so it is safe to call this /// multiple times. diff --git a/std/src/os/xous/services/dns.rs b/std/src/os/xous/services/dns.rs index a7d88f4892cda..0288164839360 100644 --- a/std/src/os/xous/services/dns.rs +++ b/std/src/os/xous/services/dns.rs @@ -1,6 +1,7 @@ +use core::sync::atomic::{AtomicU32, Ordering}; + use crate::os::xous::ffi::Connection; use crate::os::xous::services::connect; -use core::sync::atomic::{AtomicU32, Ordering}; #[repr(usize)] pub(crate) enum DnsLendMut { @@ -13,7 +14,7 @@ impl Into for DnsLendMut { } } -/// Return a `Connection` to the DNS lookup server. This server is used for +/// Returns a `Connection` to the DNS lookup server. This server is used for /// querying domain name values. pub(crate) fn dns_server() -> Connection { static DNS_CONNECTION: AtomicU32 = AtomicU32::new(0); diff --git a/std/src/os/xous/services/log.rs b/std/src/os/xous/services/log.rs index 55a501dc7d00e..1661011ca64b1 100644 --- a/std/src/os/xous/services/log.rs +++ b/std/src/os/xous/services/log.rs @@ -1,10 +1,11 @@ -use crate::os::xous::ffi::Connection; use core::sync::atomic::{AtomicU32, Ordering}; -/// Group `usize` bytes into a `usize` and return it, beginning -/// from `offset` * sizeof(usize) bytes from the start. For example, -/// `group_or_null([1,2,3,4,5,6,7,8], 1)` on a 32-bit system will -/// return a usize with 5678 packed into it. +use crate::os::xous::ffi::Connection; + +/// Group a `usize` worth of bytes into a `usize` and return it, beginning from +/// `offset` * sizeof(usize) bytes from the start. For example, +/// `group_or_null([1,2,3,4,5,6,7,8], 1)` on a 32-bit system will return a +/// `usize` with 5678 packed into it. fn group_or_null(data: &[u8], offset: usize) -> usize { let start = offset * core::mem::size_of::(); let mut out_array = [0u8; core::mem::size_of::()]; @@ -56,10 +57,12 @@ impl Into for LogLend { } } -/// Return a `Connection` to the log server, which is used for printing messages to -/// the console and reporting panics. If the log server has not yet started, this -/// will block until the server is running. It is safe to call this multiple times, -/// because the address is shared among all threads in a process. +/// Returns a `Connection` to the log server, which is used for printing messages to +/// the console and reporting panics. +/// +/// If the log server has not yet started, this will block until the server is +/// running. It is safe to call this multiple times, because the address is +/// shared among all threads in a process. pub(crate) fn log_server() -> Connection { static LOG_SERVER_CONNECTION: AtomicU32 = AtomicU32::new(0); diff --git a/std/src/os/xous/services/net.rs b/std/src/os/xous/services/net.rs index 26d337dcef168..83acc7961b377 100644 --- a/std/src/os/xous/services/net.rs +++ b/std/src/os/xous/services/net.rs @@ -1,6 +1,7 @@ +use core::sync::atomic::{AtomicU32, Ordering}; + use crate::os::xous::ffi::Connection; use crate::os::xous::services::connect; -use core::sync::atomic::{AtomicU32, Ordering}; pub(crate) enum NetBlockingScalar { StdGetTtlUdp(u16 /* fd */), /* 36 */ @@ -80,7 +81,7 @@ impl<'a> Into<[usize; 5]> for NetBlockingScalar { } } -/// Return a `Connection` to the Network server. This server provides all +/// Returns a `Connection` to the Network server. This server provides all /// OS-level networking functions. pub(crate) fn net_server() -> Connection { static NET_CONNECTION: AtomicU32 = AtomicU32::new(0); diff --git a/std/src/os/xous/services/systime.rs b/std/src/os/xous/services/systime.rs index bbb875c69426e..079ede7aa86c7 100644 --- a/std/src/os/xous/services/systime.rs +++ b/std/src/os/xous/services/systime.rs @@ -1,6 +1,7 @@ -use crate::os::xous::ffi::{connect, Connection}; use core::sync::atomic::{AtomicU32, Ordering}; +use crate::os::xous::ffi::{connect, Connection}; + pub(crate) enum SystimeScalar { GetUtcTimeMs, } @@ -13,7 +14,7 @@ impl Into<[usize; 5]> for SystimeScalar { } } -/// Return a `Connection` to the systime server. This server is used for reporting the +/// Returns a `Connection` to the systime server. This server is used for reporting the /// realtime clock. pub(crate) fn systime_server() -> Connection { static SYSTIME_SERVER_CONNECTION: AtomicU32 = AtomicU32::new(0); diff --git a/std/src/os/xous/services/ticktimer.rs b/std/src/os/xous/services/ticktimer.rs index 7759303fdbe23..66ade6da65cd3 100644 --- a/std/src/os/xous/services/ticktimer.rs +++ b/std/src/os/xous/services/ticktimer.rs @@ -1,6 +1,7 @@ -use crate::os::xous::ffi::Connection; use core::sync::atomic::{AtomicU32, Ordering}; +use crate::os::xous::ffi::Connection; + pub(crate) enum TicktimerScalar { ElapsedMs, SleepMs(usize), @@ -27,7 +28,7 @@ impl Into<[usize; 5]> for TicktimerScalar { } } -/// Return a `Connection` to the ticktimer server. This server is used for synchronization +/// Returns a `Connection` to the ticktimer server. This server is used for synchronization /// primitives such as sleep, Mutex, and Condvar. pub(crate) fn ticktimer_server() -> Connection { static TICKTIMER_SERVER_CONNECTION: AtomicU32 = AtomicU32::new(0); diff --git a/std/src/panic.rs b/std/src/panic.rs index c5d1a893ee809..4c496ade81cda 100644 --- a/std/src/panic.rs +++ b/std/src/panic.rs @@ -3,12 +3,10 @@ #![stable(feature = "std_panic", since = "1.9.0")] use crate::any::Any; -use crate::collections; -use crate::fmt; -use crate::panicking; use crate::sync::atomic::{AtomicU8, Ordering}; use crate::sync::{Condvar, Mutex, RwLock}; use crate::thread::Result; +use crate::{collections, fmt, panicking}; #[stable(feature = "panic_hooks", since = "1.10.0")] #[deprecated( @@ -39,7 +37,7 @@ pub type PanicInfo<'a> = PanicHookInfo<'a>; /// ``` /// /// [`set_hook`]: ../../std/panic/fn.set_hook.html -#[stable(feature = "panic_hook_info", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "panic_hook_info", since = "1.81.0")] #[derive(Debug)] pub struct PanicHookInfo<'a> { payload: &'a (dyn Any + Send), @@ -236,20 +234,17 @@ pub macro panic_2015 { #[doc(hidden)] #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")] pub use core::panic::panic_2021; - #[stable(feature = "panic_hooks", since = "1.10.0")] -pub use crate::panicking::{set_hook, take_hook}; +pub use core::panic::Location; +#[stable(feature = "catch_unwind", since = "1.9.0")] +pub use core::panic::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe}; #[unstable(feature = "panic_update_hook", issue = "92649")] pub use crate::panicking::update_hook; - #[stable(feature = "panic_hooks", since = "1.10.0")] -pub use core::panic::Location; - -#[stable(feature = "catch_unwind", since = "1.9.0")] -pub use core::panic::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe}; +pub use crate::panicking::{set_hook, take_hook}; -/// Panic the current thread with the given message as the panic payload. +/// Panics the current thread with the given message as the panic payload. /// /// The message can be of any (`Any + Send`) type, not just strings. /// @@ -380,7 +375,7 @@ pub fn resume_unwind(payload: Box) -> ! { panicking::rust_panic_without_hook(payload) } -/// Make all future panics abort directly without running the panic hook or unwinding. +/// Makes all future panics abort directly without running the panic hook or unwinding. /// /// There is no way to undo this; the effect lasts until the process exits or /// execs (or the equivalent). @@ -461,18 +456,17 @@ impl BacktraceStyle { // Internally stores equivalent of an Option. static SHOULD_CAPTURE: AtomicU8 = AtomicU8::new(0); -/// Configure whether the default panic hook will capture and display a +/// Configures whether the default panic hook will capture and display a /// backtrace. /// /// The default value for this setting may be set by the `RUST_BACKTRACE` /// environment variable; see the details in [`get_backtrace_style`]. #[unstable(feature = "panic_backtrace_config", issue = "93346")] pub fn set_backtrace_style(style: BacktraceStyle) { - if !cfg!(feature = "backtrace") { - // If the `backtrace` feature of this crate isn't enabled, skip setting. - return; + if cfg!(feature = "backtrace") { + // If the `backtrace` feature of this crate is enabled, set the backtrace style. + SHOULD_CAPTURE.store(style.as_u8(), Ordering::Release); } - SHOULD_CAPTURE.store(style.as_u8(), Ordering::Release); } /// Checks whether the standard library's panic hook will capture and print a @@ -508,21 +502,13 @@ pub fn get_backtrace_style() -> Option { return Some(style); } - let format = crate::env::var_os("RUST_BACKTRACE") - .map(|x| { - if &x == "0" { - BacktraceStyle::Off - } else if &x == "full" { - BacktraceStyle::Full - } else { - BacktraceStyle::Short - } - }) - .unwrap_or(if crate::sys::FULL_BACKTRACE_DEFAULT { - BacktraceStyle::Full - } else { - BacktraceStyle::Off - }); + let format = match crate::env::var_os("RUST_BACKTRACE") { + Some(x) if &x == "0" => BacktraceStyle::Off, + Some(x) if &x == "full" => BacktraceStyle::Full, + Some(_) => BacktraceStyle::Short, + None if crate::sys::FULL_BACKTRACE_DEFAULT => BacktraceStyle::Full, + None => BacktraceStyle::Off, + }; set_backtrace_style(format); Some(format) } diff --git a/std/src/panicking.rs b/std/src/panicking.rs index 418a855fb728e..e818b448270dd 100644 --- a/std/src/panicking.rs +++ b/std/src/panicking.rs @@ -9,26 +9,23 @@ #![deny(unsafe_op_in_unsafe_fn)] -use crate::panic::{BacktraceStyle, PanicHookInfo}; use core::panic::{Location, PanicPayload}; +// make sure to use the stderr output configured +// by libtest in the real copy of std +#[cfg(test)] +use realstd::io::try_set_output_capture; + use crate::any::Any; -use crate::fmt; -use crate::intrinsics; +#[cfg(not(test))] +use crate::io::try_set_output_capture; use crate::mem::{self, ManuallyDrop}; -use crate::process; +use crate::panic::{BacktraceStyle, PanicHookInfo}; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sync::{PoisonError, RwLock}; use crate::sys::backtrace; use crate::sys::stdio::panic_output; -use crate::thread; - -#[cfg(not(test))] -use crate::io::try_set_output_capture; -// make sure to use the stderr output configured -// by libtest in the real copy of std -#[cfg(test)] -use realstd::io::try_set_output_capture; +use crate::{fmt, intrinsics, process, thread}; // Binary interface to the panic runtime that the standard library depends on. // diff --git a/std/src/path.rs b/std/src/path.rs index d5121a554bf6c..80163667636ae 100644 --- a/std/src/path.rs +++ b/std/src/path.rs @@ -71,22 +71,17 @@ mod tests; use crate::borrow::{Borrow, Cow}; -use crate::cmp; use crate::collections::TryReserveError; use crate::error::Error; -use crate::fmt; -use crate::fs; +use crate::ffi::{os_str, OsStr, OsString}; use crate::hash::{Hash, Hasher}; -use crate::io; use crate::iter::FusedIterator; use crate::ops::{self, Deref}; use crate::rc::Rc; use crate::str::FromStr; use crate::sync::Arc; - -use crate::ffi::{os_str, OsStr, OsString}; -use crate::sys; use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR}; +use crate::{cmp, fmt, fs, io, sys}; //////////////////////////////////////////////////////////////////////////////// // GENERAL NOTES @@ -1797,7 +1792,7 @@ impl> From<&T> for PathBuf { #[stable(feature = "rust1", since = "1.0.0")] impl From for PathBuf { - /// Converts an [`OsString`] into a [`PathBuf`] + /// Converts an [`OsString`] into a [`PathBuf`]. /// /// This conversion does not allocate or copy memory. #[inline] @@ -2079,10 +2074,8 @@ impl AsRef for PathBuf { #[stable(feature = "rust1", since = "1.0.0")] // `Path::new` current implementation relies // on `Path` being layout-compatible with `OsStr`. -// However, `Path` layout is considered an implementation detail and must not be relied upon. We -// want `repr(transparent)` but we don't want it to show up in rustdoc, so we hide it under -// `cfg(doc)`. This is an ad-hoc implementation of attribute privacy. -#[cfg_attr(not(doc), repr(transparent))] +// However, `Path` layout is considered an implementation detail and must not be relied upon. +#[repr(transparent)] pub struct Path { inner: OsStr, } diff --git a/std/src/path/tests.rs b/std/src/path/tests.rs index 3ade4fb892f5e..a12e42cba0c5c 100644 --- a/std/src/path/tests.rs +++ b/std/src/path/tests.rs @@ -1,8 +1,8 @@ -use super::*; +use core::hint::black_box; +use super::*; use crate::collections::{BTreeSet, HashSet}; use crate::hash::DefaultHasher; -use core::hint::black_box; #[allow(unknown_lints, unused_macro_rules)] macro_rules! t ( diff --git a/std/src/pipe.rs b/std/src/pipe.rs new file mode 100644 index 0000000000000..aa4c7014fe918 --- /dev/null +++ b/std/src/pipe.rs @@ -0,0 +1,128 @@ +//! Module for anonymous pipe +//! +//! ``` +//! #![feature(anonymous_pipe)] +//! +//! # #[cfg(miri)] fn main() {} +//! # #[cfg(not(miri))] +//! # fn main() -> std::io::Result<()> { +//! let (reader, writer) = std::pipe::pipe()?; +//! # Ok(()) +//! # } +//! ``` + +use crate::io; +use crate::sys::anonymous_pipe::{pipe as pipe_inner, AnonPipe}; + +/// Create anonymous pipe that is close-on-exec and blocking. +#[unstable(feature = "anonymous_pipe", issue = "127154")] +#[inline] +pub fn pipe() -> io::Result<(PipeReader, PipeWriter)> { + pipe_inner().map(|(reader, writer)| (PipeReader(reader), PipeWriter(writer))) +} + +/// Read end of the anonymous pipe. +#[unstable(feature = "anonymous_pipe", issue = "127154")] +#[derive(Debug)] +pub struct PipeReader(pub(crate) AnonPipe); + +/// Write end of the anonymous pipe. +#[unstable(feature = "anonymous_pipe", issue = "127154")] +#[derive(Debug)] +pub struct PipeWriter(pub(crate) AnonPipe); + +impl PipeReader { + /// Create a new [`PipeReader`] instance that shares the same underlying file description. + #[unstable(feature = "anonymous_pipe", issue = "127154")] + pub fn try_clone(&self) -> io::Result { + self.0.try_clone().map(Self) + } +} + +impl PipeWriter { + /// Create a new [`PipeWriter`] instance that shares the same underlying file description. + #[unstable(feature = "anonymous_pipe", issue = "127154")] + pub fn try_clone(&self) -> io::Result { + self.0.try_clone().map(Self) + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl io::Read for &PipeReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.0.read(buf) + } + fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result { + self.0.read_vectored(bufs) + } + #[inline] + fn is_read_vectored(&self) -> bool { + self.0.is_read_vectored() + } + fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { + self.0.read_to_end(buf) + } + fn read_buf(&mut self, buf: io::BorrowedCursor<'_>) -> io::Result<()> { + self.0.read_buf(buf) + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl io::Read for PipeReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.0.read(buf) + } + fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result { + self.0.read_vectored(bufs) + } + #[inline] + fn is_read_vectored(&self) -> bool { + self.0.is_read_vectored() + } + fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { + self.0.read_to_end(buf) + } + fn read_buf(&mut self, buf: io::BorrowedCursor<'_>) -> io::Result<()> { + self.0.read_buf(buf) + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl io::Write for &PipeWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.write(buf) + } + #[inline] + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + + fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result { + self.0.write_vectored(bufs) + } + + #[inline] + fn is_write_vectored(&self) -> bool { + self.0.is_write_vectored() + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl io::Write for PipeWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.write(buf) + } + #[inline] + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + + fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result { + self.0.write_vectored(bufs) + } + + #[inline] + fn is_write_vectored(&self) -> bool { + self.0.is_write_vectored() + } +} diff --git a/std/src/pipe/tests.rs b/std/src/pipe/tests.rs new file mode 100644 index 0000000000000..9c38e10678752 --- /dev/null +++ b/std/src/pipe/tests.rs @@ -0,0 +1,19 @@ +use crate::io::{Read, Write}; +use crate::pipe::pipe; + +#[test] +#[cfg(all(windows, unix, not(miri)))] +fn pipe_creation_clone_and_rw() { + let (rx, tx) = pipe().unwrap(); + + tx.try_clone().unwrap().write_all(b"12345").unwrap(); + drop(tx); + + let mut rx2 = rx.try_clone().unwrap(); + drop(rx); + + let mut s = String::new(); + rx2.read_to_string(&mut s).unwrap(); + drop(rx2); + assert_eq!(s, "12345"); +} diff --git a/std/src/process.rs b/std/src/process.rs index fc86578a5ff2f..9ffdebe1b6ffe 100644 --- a/std/src/process.rs +++ b/std/src/process.rs @@ -151,21 +151,18 @@ #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx", target_os = "xous"))))] mod tests; -use crate::io::prelude::*; - use crate::convert::Infallible; use crate::ffi::OsStr; -use crate::fmt; -use crate::fs; +use crate::io::prelude::*; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; use crate::num::NonZero; use crate::path::Path; -use crate::str; use crate::sys::pipe::{read2, AnonPipe}; use crate::sys::process as imp; #[stable(feature = "command_access", since = "1.57.0")] pub use crate::sys_common::process::CommandEnvs; use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; +use crate::{fmt, fs, str}; /// Representation of a running or exited child process. /// @@ -2056,7 +2053,7 @@ impl ExitCode { // representation of an ExitCode // // More info: https://internals.rust-lang.org/t/mini-pre-rfc-redesigning-process-exitstatus/5426 - /// Convert an `ExitCode` into an i32 + /// Converts an `ExitCode` into an i32 #[unstable( feature = "process_exitcode_internals", reason = "exposed only for libstd", @@ -2079,7 +2076,7 @@ impl Default for ExitCode { #[stable(feature = "process_exitcode", since = "1.61.0")] impl From for ExitCode { - /// Construct an `ExitCode` from an arbitrary u8 value. + /// Constructs an `ExitCode` from an arbitrary u8 value. fn from(code: u8) -> Self { ExitCode(imp::ExitCode::from(code)) } diff --git a/std/src/process/tests.rs b/std/src/process/tests.rs index 055601d030799..f8e8e0dea553b 100644 --- a/std/src/process/tests.rs +++ b/std/src/process/tests.rs @@ -1,6 +1,5 @@ -use crate::io::prelude::*; - use super::{Command, Output, Stdio}; +use crate::io::prelude::*; use crate::io::{BorrowedBuf, ErrorKind}; use crate::mem::MaybeUninit; use crate::str; diff --git a/std/src/rt.rs b/std/src/rt.rs index deb4a8fa7eed0..307a543c9d215 100644 --- a/std/src/rt.rs +++ b/std/src/rt.rs @@ -16,9 +16,11 @@ #![deny(unsafe_op_in_unsafe_fn)] #![allow(unused_macros)] +#[rustfmt::skip] pub use crate::panicking::{begin_panic, panic_count}; pub use core::panicking::{panic_display, panic_fmt}; +#[rustfmt::skip] use crate::sync::Once; use crate::sys; use crate::thread::{self, Thread}; diff --git a/std/src/sync/lazy_lock.rs b/std/src/sync/lazy_lock.rs index 18906aceffa30..953aef40e7b76 100644 --- a/std/src/sync/lazy_lock.rs +++ b/std/src/sync/lazy_lock.rs @@ -1,3 +1,4 @@ +use super::once::ExclusiveState; use crate::cell::UnsafeCell; use crate::mem::ManuallyDrop; use crate::ops::Deref; @@ -5,8 +6,6 @@ use crate::panic::{RefUnwindSafe, UnwindSafe}; use crate::sync::Once; use crate::{fmt, ptr}; -use super::once::ExclusiveState; - // We use the state of a Once as discriminant value. Upon creation, the state is // "incomplete" and `f` contains the initialization closure. In the first call to // `call_once`, `f` is taken and run. If it succeeds, `value` is set and the state @@ -175,7 +174,7 @@ impl T> LazyLock { } impl LazyLock { - /// Get the inner value if it has already been initialized. + /// Gets the inner value if it has already been initialized. fn get(&self) -> Option<&T> { if self.once.is_completed() { // SAFETY: diff --git a/std/src/sync/lazy_lock/tests.rs b/std/src/sync/lazy_lock/tests.rs index a5d4e25c5962a..8a6ab4ac4fd99 100644 --- a/std/src/sync/lazy_lock/tests.rs +++ b/std/src/sync/lazy_lock/tests.rs @@ -1,13 +1,8 @@ -use crate::{ - cell::LazyCell, - panic, - sync::{ - atomic::{AtomicUsize, Ordering::SeqCst}, - Mutex, - }, - sync::{LazyLock, OnceLock}, - thread, -}; +use crate::cell::LazyCell; +use crate::sync::atomic::AtomicUsize; +use crate::sync::atomic::Ordering::SeqCst; +use crate::sync::{LazyLock, Mutex, OnceLock}; +use crate::{panic, thread}; fn spawn_and_wait(f: impl FnOnce() -> R + Send + 'static) -> R { thread::spawn(f).join().unwrap() diff --git a/std/src/sync/mod.rs b/std/src/sync/mod.rs index 9a38c42f43a02..d0ba8cc3b47df 100644 --- a/std/src/sync/mod.rs +++ b/std/src/sync/mod.rs @@ -158,17 +158,20 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::sync::{Arc, Weak}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::sync::atomic; #[unstable(feature = "exclusive_wrapper", issue = "98407")] pub use core::sync::Exclusive; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::sync::{Arc, Weak}; + #[stable(feature = "rust1", since = "1.0.0")] pub use self::barrier::{Barrier, BarrierWaitResult}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::condvar::{Condvar, WaitTimeoutResult}; +#[stable(feature = "lazy_cell", since = "1.80.0")] +pub use self::lazy_lock::LazyLock; #[unstable(feature = "mapped_lock_guards", issue = "117108")] pub use self::mutex::MappedMutexGuard; #[stable(feature = "rust1", since = "1.0.0")] @@ -176,21 +179,17 @@ pub use self::mutex::{Mutex, MutexGuard}; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] pub use self::once::{Once, OnceState, ONCE_INIT}; +#[stable(feature = "once_cell", since = "1.70.0")] +pub use self::once_lock::OnceLock; #[stable(feature = "rust1", since = "1.0.0")] pub use self::poison::{LockResult, PoisonError, TryLockError, TryLockResult}; +#[unstable(feature = "reentrant_lock", issue = "121440")] +pub use self::reentrant_lock::{ReentrantLock, ReentrantLockGuard}; #[unstable(feature = "mapped_lock_guards", issue = "117108")] pub use self::rwlock::{MappedRwLockReadGuard, MappedRwLockWriteGuard}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard}; -#[stable(feature = "lazy_cell", since = "1.80.0")] -pub use self::lazy_lock::LazyLock; -#[stable(feature = "once_cell", since = "1.70.0")] -pub use self::once_lock::OnceLock; - -#[unstable(feature = "reentrant_lock", issue = "121440")] -pub use self::reentrant_lock::{ReentrantLock, ReentrantLockGuard}; - pub mod mpsc; mod barrier; diff --git a/std/src/sync/mpmc/array.rs b/std/src/sync/mpmc/array.rs index 185319add745f..34acd9c9a943b 100644 --- a/std/src/sync/mpmc/array.rs +++ b/std/src/sync/mpmc/array.rs @@ -13,7 +13,6 @@ use super::error::*; use super::select::{Operation, Selected, Token}; use super::utils::{Backoff, CachePadded}; use super::waker::SyncWaker; - use crate::cell::UnsafeCell; use crate::mem::MaybeUninit; use crate::ptr; diff --git a/std/src/sync/mpmc/context.rs b/std/src/sync/mpmc/context.rs index bbfc6ce00ffc2..8db3c9896eb77 100644 --- a/std/src/sync/mpmc/context.rs +++ b/std/src/sync/mpmc/context.rs @@ -2,7 +2,6 @@ use super::select::Selected; use super::waker::current_thread_id; - use crate::cell::Cell; use crate::ptr; use crate::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; diff --git a/std/src/sync/mpmc/counter.rs b/std/src/sync/mpmc/counter.rs index 3478cf41dc9d2..d1bfe612f536f 100644 --- a/std/src/sync/mpmc/counter.rs +++ b/std/src/sync/mpmc/counter.rs @@ -1,6 +1,5 @@ -use crate::ops; -use crate::process; use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use crate::{ops, process}; /// Reference counter internals. struct Counter { diff --git a/std/src/sync/mpmc/error.rs b/std/src/sync/mpmc/error.rs index 33b2bff853498..e3aec7e76232f 100644 --- a/std/src/sync/mpmc/error.rs +++ b/std/src/sync/mpmc/error.rs @@ -1,7 +1,5 @@ -use crate::error; -use crate::fmt; - pub use crate::sync::mpsc::{RecvError, RecvTimeoutError, SendError, TryRecvError, TrySendError}; +use crate::{error, fmt}; /// An error returned from the [`send_timeout`] method. /// diff --git a/std/src/sync/mpmc/list.rs b/std/src/sync/mpmc/list.rs index edac7a0cb1835..bbe205cad04e6 100644 --- a/std/src/sync/mpmc/list.rs +++ b/std/src/sync/mpmc/list.rs @@ -5,7 +5,6 @@ use super::error::*; use super::select::{Operation, Selected, Token}; use super::utils::{Backoff, CachePadded}; use super::waker::SyncWaker; - use crate::cell::UnsafeCell; use crate::marker::PhantomData; use crate::mem::MaybeUninit; diff --git a/std/src/sync/mpmc/mod.rs b/std/src/sync/mpmc/mod.rs index 2068dda393a2b..c640e07348ea0 100644 --- a/std/src/sync/mpmc/mod.rs +++ b/std/src/sync/mpmc/mod.rs @@ -40,10 +40,11 @@ mod utils; mod waker; mod zero; +pub use error::*; + use crate::fmt; use crate::panic::{RefUnwindSafe, UnwindSafe}; use crate::time::{Duration, Instant}; -pub use error::*; /// Creates a channel of unbounded capacity. /// diff --git a/std/src/sync/mpmc/waker.rs b/std/src/sync/mpmc/waker.rs index 9aab1b9417edb..fb877887f9c9d 100644 --- a/std/src/sync/mpmc/waker.rs +++ b/std/src/sync/mpmc/waker.rs @@ -2,7 +2,6 @@ use super::context::Context; use super::select::{Operation, Selected}; - use crate::ptr; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sync::Mutex; diff --git a/std/src/sync/mpmc/zero.rs b/std/src/sync/mpmc/zero.rs index 6d1c9d64e7a7a..2b82eeda3d5fb 100644 --- a/std/src/sync/mpmc/zero.rs +++ b/std/src/sync/mpmc/zero.rs @@ -7,7 +7,6 @@ use super::error::*; use super::select::{Operation, Selected, Token}; use super::utils::Backoff; use super::waker::Waker; - use crate::cell::UnsafeCell; use crate::marker::PhantomData; use crate::sync::atomic::{AtomicBool, Ordering}; diff --git a/std/src/sync/mpsc/mod.rs b/std/src/sync/mpsc/mod.rs index feee6948db4fd..26d5b9515a244 100644 --- a/std/src/sync/mpsc/mod.rs +++ b/std/src/sync/mpsc/mod.rs @@ -148,10 +148,9 @@ mod sync_tests; // not exposed publicly, but if you are curious about the implementation, // that's where everything is. -use crate::error; -use crate::fmt; use crate::sync::mpmc; use crate::time::{Duration, Instant}; +use crate::{error, fmt}; /// The receiving half of Rust's [`channel`] (or [`sync_channel`]) type. /// This half can only be owned by one thread. diff --git a/std/src/sync/mpsc/sync_tests.rs b/std/src/sync/mpsc/sync_tests.rs index 945de280f40d8..49b65c8efe692 100644 --- a/std/src/sync/mpsc/sync_tests.rs +++ b/std/src/sync/mpsc/sync_tests.rs @@ -1,8 +1,7 @@ use super::*; -use crate::env; use crate::rc::Rc; use crate::sync::mpmc::SendTimeoutError; -use crate::thread; +use crate::{env, thread}; pub fn stress_factor() -> usize { match env::var("RUST_TEST_STRESS") { diff --git a/std/src/sync/mpsc/tests.rs b/std/src/sync/mpsc/tests.rs index ac1a804cf9c84..13892fa0d18e4 100644 --- a/std/src/sync/mpsc/tests.rs +++ b/std/src/sync/mpsc/tests.rs @@ -1,6 +1,5 @@ use super::*; -use crate::env; -use crate::thread; +use crate::{env, thread}; pub fn stress_factor() -> usize { match env::var("RUST_TEST_STRESS") { diff --git a/std/src/sync/once.rs b/std/src/sync/once.rs index 9d969af8c6d84..bf595fdea2d25 100644 --- a/std/src/sync/once.rs +++ b/std/src/sync/once.rs @@ -70,7 +70,7 @@ pub(crate) enum ExclusiveState { #[stable(feature = "rust1", since = "1.0.0")] #[deprecated( since = "1.38.0", - note = "the `new` function is now preferred", + note = "the `Once::new()` function is now preferred", suggestion = "Once::new()" )] pub const ONCE_INIT: Once = Once::new(); @@ -264,6 +264,47 @@ impl Once { self.inner.is_completed() } + /// Blocks the current thread until initialization has completed. + /// + /// # Example + /// + /// ```rust + /// #![feature(once_wait)] + /// + /// use std::sync::Once; + /// use std::thread; + /// + /// static READY: Once = Once::new(); + /// + /// let thread = thread::spawn(|| { + /// READY.wait(); + /// println!("everything is ready"); + /// }); + /// + /// READY.call_once(|| println!("performing setup")); + /// ``` + /// + /// # Panics + /// + /// If this [`Once`] has been poisoned because an initialization closure has + /// panicked, this method will also panic. Use [`wait_force`](Self::wait_force) + /// if this behaviour is not desired. + #[unstable(feature = "once_wait", issue = "127527")] + pub fn wait(&self) { + if !self.inner.is_completed() { + self.inner.wait(false); + } + } + + /// Blocks the current thread until initialization has completed, ignoring + /// poisoning. + #[unstable(feature = "once_wait", issue = "127527")] + pub fn wait_force(&self) { + if !self.inner.is_completed() { + self.inner.wait(true); + } + } + /// Returns the current state of the `Once` instance. /// /// Since this takes a mutable reference, no initialization can currently diff --git a/std/src/sync/once/tests.rs b/std/src/sync/once/tests.rs index 0c35597e11c51..ce96468aeb6e1 100644 --- a/std/src/sync/once/tests.rs +++ b/std/src/sync/once/tests.rs @@ -1,7 +1,9 @@ use super::Once; -use crate::panic; +use crate::sync::atomic::AtomicBool; +use crate::sync::atomic::Ordering::Relaxed; use crate::sync::mpsc::channel; -use crate::thread; +use crate::time::Duration; +use crate::{panic, thread}; #[test] fn smoke_once() { @@ -114,3 +116,47 @@ fn wait_for_force_to_finish() { assert!(t1.join().is_ok()); assert!(t2.join().is_ok()); } + +#[test] +fn wait() { + for _ in 0..50 { + let val = AtomicBool::new(false); + let once = Once::new(); + + thread::scope(|s| { + for _ in 0..4 { + s.spawn(|| { + once.wait(); + assert!(val.load(Relaxed)); + }); + } + + once.call_once(|| val.store(true, Relaxed)); + }); + } +} + +#[test] +fn wait_on_poisoned() { + let once = Once::new(); + + panic::catch_unwind(|| once.call_once(|| panic!())).unwrap_err(); + panic::catch_unwind(|| once.wait()).unwrap_err(); +} + +#[test] +fn wait_force_on_poisoned() { + let once = Once::new(); + + thread::scope(|s| { + panic::catch_unwind(|| once.call_once(|| panic!())).unwrap_err(); + + s.spawn(|| { + thread::sleep(Duration::from_millis(100)); + + once.call_once_force(|_| {}); + }); + + once.wait_force(); + }) +} diff --git a/std/src/sync/once_lock.rs b/std/src/sync/once_lock.rs index 94955beaf37b7..56cf877ddc6d5 100644 --- a/std/src/sync/once_lock.rs +++ b/std/src/sync/once_lock.rs @@ -167,6 +167,34 @@ impl OnceLock { } } + /// Blocks the current thread until the cell is initialized. + /// + /// # Example + /// + /// Waiting for a computation on another thread to finish: + /// ```rust + /// #![feature(once_wait)] + /// + /// use std::thread; + /// use std::sync::OnceLock; + /// + /// let value = OnceLock::new(); + /// + /// thread::scope(|s| { + /// s.spawn(|| value.set(1 + 1)); + /// + /// let result = value.wait(); + /// assert_eq!(result, &2); + /// }) + /// ``` + #[inline] + #[unstable(feature = "once_wait", issue = "127527")] + pub fn wait(&self) -> &T { + self.once.wait_force(); + + unsafe { self.get_unchecked() } + } + /// Sets the contents of this cell to `value`. /// /// May block if another thread is currently attempting to initialize the cell. The cell is @@ -281,9 +309,7 @@ impl OnceLock { /// Gets the mutable reference of the contents of the cell, initializing /// it with `f` if the cell was empty. /// - /// Many threads may call `get_mut_or_init` concurrently with different - /// initializing functions, but it is guaranteed that only one function - /// will be executed. + /// This method never blocks. /// /// # Panics /// @@ -373,6 +399,8 @@ impl OnceLock { /// it with `f` if the cell was empty. If the cell was empty and `f` failed, /// an error is returned. /// + /// This method never blocks. + /// /// # Panics /// /// If `f` panics, the panic is propagated to the caller, and @@ -578,7 +606,7 @@ impl Clone for OnceLock { #[stable(feature = "once_cell", since = "1.70.0")] impl From for OnceLock { - /// Create a new cell with its contents set to `value`. + /// Creates a new cell with its contents set to `value`. /// /// # Example /// diff --git a/std/src/sync/once_lock/tests.rs b/std/src/sync/once_lock/tests.rs index d5d32e73d8880..176830c6748b2 100644 --- a/std/src/sync/once_lock/tests.rs +++ b/std/src/sync/once_lock/tests.rs @@ -1,12 +1,8 @@ -use crate::{ - panic, - sync::OnceLock, - sync::{ - atomic::{AtomicUsize, Ordering::SeqCst}, - mpsc::channel, - }, - thread, -}; +use crate::sync::atomic::AtomicUsize; +use crate::sync::atomic::Ordering::SeqCst; +use crate::sync::mpsc::channel; +use crate::sync::OnceLock; +use crate::{panic, thread}; fn spawn_and_wait(f: impl FnOnce() -> R + Send + 'static) -> R { thread::spawn(f).join().unwrap() diff --git a/std/src/sync/poison.rs b/std/src/sync/poison.rs index f4975088b372d..da66a088e51b1 100644 --- a/std/src/sync/poison.rs +++ b/std/src/sync/poison.rs @@ -1,6 +1,5 @@ use crate::error::Error; use crate::fmt; - #[cfg(panic = "unwind")] use crate::sync::atomic::{AtomicBool, Ordering}; #[cfg(panic = "unwind")] @@ -31,13 +30,13 @@ impl Flag { } } - /// Check the flag for an unguarded borrow, where we only care about existing poison. + /// Checks the flag for an unguarded borrow, where we only care about existing poison. #[inline] pub fn borrow(&self) -> LockResult<()> { if self.get() { Err(PoisonError::new(())) } else { Ok(()) } } - /// Check the flag for a guarded borrow, where we may also set poison when `done`. + /// Checks the flag for a guarded borrow, where we may also set poison when `done`. #[inline] pub fn guard(&self) -> LockResult { let ret = Guard { diff --git a/std/src/sync/reentrant_lock.rs b/std/src/sync/reentrant_lock.rs index 042c439394e06..84a0b36db1798 100644 --- a/std/src/sync/reentrant_lock.rs +++ b/std/src/sync/reentrant_lock.rs @@ -1,12 +1,14 @@ #[cfg(all(test, not(target_os = "emscripten")))] mod tests; +use cfg_if::cfg_if; + use crate::cell::UnsafeCell; use crate::fmt; use crate::ops::Deref; use crate::panic::{RefUnwindSafe, UnwindSafe}; -use crate::sync::atomic::{AtomicUsize, Ordering::Relaxed}; use crate::sys::sync as sys; +use crate::thread::{current_id, ThreadId}; /// A re-entrant mutual exclusion lock /// @@ -53,8 +55,8 @@ use crate::sys::sync as sys; // // The 'owner' field tracks which thread has locked the mutex. // -// We use current_thread_unique_ptr() as the thread identifier, -// which is just the address of a thread local variable. +// We use thread::current_id() as the thread identifier, which is just the +// current thread's ThreadId, so it's unique across the process lifetime. // // If `owner` is set to the identifier of the current thread, // we assume the mutex is already locked and instead of locking it again, @@ -72,14 +74,109 @@ use crate::sys::sync as sys; // since we're not dealing with multiple threads. If it's not equal, // synchronization is left to the mutex, making relaxed memory ordering for // the `owner` field fine in all cases. +// +// On systems without 64 bit atomics we also store the address of a TLS variable +// along the 64-bit TID. We then first check that address against the address +// of that variable on the current thread, and only if they compare equal do we +// compare the actual TIDs. Because we only ever read the TID on the same thread +// that it was written on (or a thread sharing the TLS block with that writer thread), +// we don't need to further synchronize the TID accesses, so they can be regular 64-bit +// non-atomic accesses. #[unstable(feature = "reentrant_lock", issue = "121440")] pub struct ReentrantLock { mutex: sys::Mutex, - owner: AtomicUsize, + owner: Tid, lock_count: UnsafeCell, data: T, } +cfg_if!( + if #[cfg(target_has_atomic = "64")] { + use crate::sync::atomic::{AtomicU64, Ordering::Relaxed}; + + struct Tid(AtomicU64); + + impl Tid { + const fn new() -> Self { + Self(AtomicU64::new(0)) + } + + #[inline] + fn contains(&self, owner: ThreadId) -> bool { + owner.as_u64().get() == self.0.load(Relaxed) + } + + #[inline] + // This is just unsafe to match the API of the Tid type below. + unsafe fn set(&self, tid: Option) { + let value = tid.map_or(0, |tid| tid.as_u64().get()); + self.0.store(value, Relaxed); + } + } + } else { + /// Returns the address of a TLS variable. This is guaranteed to + /// be unique across all currently alive threads. + fn tls_addr() -> usize { + thread_local! { static X: u8 = const { 0u8 } }; + + X.with(|p| <*const u8>::addr(p)) + } + + use crate::sync::atomic::{ + AtomicUsize, + Ordering, + }; + + struct Tid { + // When a thread calls `set()`, this value gets updated to + // the address of a thread local on that thread. This is + // used as a first check in `contains()`; if the `tls_addr` + // doesn't match the TLS address of the current thread, then + // the ThreadId also can't match. Only if the TLS addresses do + // match do we read out the actual TID. + // Note also that we can use relaxed atomic operations here, because + // we only ever read from the tid if `tls_addr` matches the current + // TLS address. In that case, either the the tid has been set by + // the current thread, or by a thread that has terminated before + // the current thread was created. In either case, no further + // synchronization is needed (as per ) + tls_addr: AtomicUsize, + tid: UnsafeCell, + } + + unsafe impl Send for Tid {} + unsafe impl Sync for Tid {} + + impl Tid { + const fn new() -> Self { + Self { tls_addr: AtomicUsize::new(0), tid: UnsafeCell::new(0) } + } + + #[inline] + // NOTE: This assumes that `owner` is the ID of the current + // thread, and may spuriously return `false` if that's not the case. + fn contains(&self, owner: ThreadId) -> bool { + // SAFETY: See the comments in the struct definition. + self.tls_addr.load(Ordering::Relaxed) == tls_addr() + && unsafe { *self.tid.get() } == owner.as_u64().get() + } + + #[inline] + // This may only be called by one thread at a time, and can lead to + // race conditions otherwise. + unsafe fn set(&self, tid: Option) { + // It's important that we set `self.tls_addr` to 0 if the tid is + // cleared. Otherwise, there might be race conditions between + // `set()` and `get()`. + let tls_addr = if tid.is_some() { tls_addr() } else { 0 }; + let value = tid.map_or(0, |tid| tid.as_u64().get()); + self.tls_addr.store(tls_addr, Ordering::Relaxed); + unsafe { *self.tid.get() = value }; + } + } + } +); + #[unstable(feature = "reentrant_lock", issue = "121440")] unsafe impl Send for ReentrantLock {} #[unstable(feature = "reentrant_lock", issue = "121440")] @@ -134,7 +231,7 @@ impl ReentrantLock { pub const fn new(t: T) -> ReentrantLock { ReentrantLock { mutex: sys::Mutex::new(), - owner: AtomicUsize::new(0), + owner: Tid::new(), lock_count: UnsafeCell::new(0), data: t, } @@ -184,14 +281,16 @@ impl ReentrantLock { /// assert_eq!(lock.lock().get(), 10); /// ``` pub fn lock(&self) -> ReentrantLockGuard<'_, T> { - let this_thread = current_thread_unique_ptr(); - // Safety: We only touch lock_count when we own the lock. + let this_thread = current_id(); + // Safety: We only touch lock_count when we own the inner mutex. + // Additionally, we only call `self.owner.set()` while holding + // the inner mutex, so no two threads can call it concurrently. unsafe { - if self.owner.load(Relaxed) == this_thread { + if self.owner.contains(this_thread) { self.increment_lock_count().expect("lock count overflow in reentrant mutex"); } else { self.mutex.lock(); - self.owner.store(this_thread, Relaxed); + self.owner.set(Some(this_thread)); debug_assert_eq!(*self.lock_count.get(), 0); *self.lock_count.get() = 1; } @@ -226,14 +325,16 @@ impl ReentrantLock { /// /// This function does not block. pub(crate) fn try_lock(&self) -> Option> { - let this_thread = current_thread_unique_ptr(); - // Safety: We only touch lock_count when we own the lock. + let this_thread = current_id(); + // Safety: We only touch lock_count when we own the inner mutex. + // Additionally, we only call `self.owner.set()` while holding + // the inner mutex, so no two threads can call it concurrently. unsafe { - if self.owner.load(Relaxed) == this_thread { + if self.owner.contains(this_thread) { self.increment_lock_count()?; Some(ReentrantLockGuard { lock: self }) } else if self.mutex.try_lock() { - self.owner.store(this_thread, Relaxed); + self.owner.set(Some(this_thread)); debug_assert_eq!(*self.lock_count.get(), 0); *self.lock_count.get() = 1; Some(ReentrantLockGuard { lock: self }) @@ -308,18 +409,9 @@ impl Drop for ReentrantLockGuard<'_, T> { unsafe { *self.lock.lock_count.get() -= 1; if *self.lock.lock_count.get() == 0 { - self.lock.owner.store(0, Relaxed); + self.lock.owner.set(None); self.lock.mutex.unlock(); } } } } - -/// Get an address that is unique per running thread. -/// -/// This can be used as a non-null usize-sized ID. -pub(crate) fn current_thread_unique_ptr() -> usize { - // Use a non-drop type to make sure it's still available during thread destruction. - thread_local! { static X: u8 = const { 0 } } - X.with(|x| <*const _>::addr(x)) -} diff --git a/std/src/sync/rwlock.rs b/std/src/sync/rwlock.rs index a4ec52a4abe63..d995a16e056d6 100644 --- a/std/src/sync/rwlock.rs +++ b/std/src/sync/rwlock.rs @@ -573,7 +573,7 @@ impl From for RwLock { } impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> { - /// Create a new instance of `RwLockReadGuard` from a `RwLock`. + /// Creates a new instance of `RwLockReadGuard` from a `RwLock`. // SAFETY: if and only if `lock.inner.read()` (or `lock.inner.try_read()`) has been // successfully called from the same thread before instantiating this object. unsafe fn new(lock: &'rwlock RwLock) -> LockResult> { @@ -585,7 +585,7 @@ impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> { } impl<'rwlock, T: ?Sized> RwLockWriteGuard<'rwlock, T> { - /// Create a new instance of `RwLockWriteGuard` from a `RwLock`. + /// Creates a new instance of `RwLockWriteGuard` from a `RwLock`. // SAFETY: if and only if `lock.inner.write()` (or `lock.inner.try_write()`) has been // successfully called from the same thread before instantiating this object. unsafe fn new(lock: &'rwlock RwLock) -> LockResult> { diff --git a/std/src/sync/rwlock/tests.rs b/std/src/sync/rwlock/tests.rs index 9cc5e7a3a60f1..12bb0fbf0503b 100644 --- a/std/src/sync/rwlock/tests.rs +++ b/std/src/sync/rwlock/tests.rs @@ -1,3 +1,5 @@ +use rand::Rng; + use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sync::mpsc::channel; use crate::sync::{ @@ -5,7 +7,6 @@ use crate::sync::{ TryLockError, }; use crate::thread; -use rand::Rng; #[derive(Eq, PartialEq, Debug)] struct NonCopy(i32); diff --git a/std/src/sys/anonymous_pipe/mod.rs b/std/src/sys/anonymous_pipe/mod.rs new file mode 100644 index 0000000000000..aa14c8b650d34 --- /dev/null +++ b/std/src/sys/anonymous_pipe/mod.rs @@ -0,0 +1,14 @@ +#![forbid(unsafe_op_in_unsafe_fn)] + +cfg_if::cfg_if! { + if #[cfg(unix)] { + mod unix; + pub use unix::{AnonPipe, pipe}; + } else if #[cfg(windows)] { + mod windows; + pub use windows::{AnonPipe, pipe}; + } else { + mod unsupported; + pub use unsupported::{AnonPipe, pipe}; + } +} diff --git a/std/src/sys/anonymous_pipe/unix.rs b/std/src/sys/anonymous_pipe/unix.rs new file mode 100644 index 0000000000000..9168024730e67 --- /dev/null +++ b/std/src/sys/anonymous_pipe/unix.rs @@ -0,0 +1,102 @@ +use crate::io; +use crate::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; +use crate::pipe::{PipeReader, PipeWriter}; +use crate::process::Stdio; +use crate::sys::fd::FileDesc; +use crate::sys::pipe::anon_pipe; +use crate::sys_common::{FromInner, IntoInner}; + +pub type AnonPipe = FileDesc; + +#[inline] +pub fn pipe() -> io::Result<(AnonPipe, AnonPipe)> { + anon_pipe().map(|(rx, wx)| (rx.into_inner(), wx.into_inner())) +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl AsFd for PipeReader { + fn as_fd(&self) -> BorrowedFd<'_> { + self.0.as_fd() + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl AsRawFd for PipeReader { + fn as_raw_fd(&self) -> RawFd { + self.0.as_raw_fd() + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for OwnedFd { + fn from(pipe: PipeReader) -> Self { + FileDesc::into_inner(pipe.0) + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl FromRawFd for PipeReader { + unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { + unsafe { Self(FileDesc::from_raw_fd(raw_fd)) } + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl IntoRawFd for PipeReader { + fn into_raw_fd(self) -> RawFd { + self.0.into_raw_fd() + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for Stdio { + fn from(pipe: PipeReader) -> Self { + Self::from(OwnedFd::from(pipe)) + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl AsFd for PipeWriter { + fn as_fd(&self) -> BorrowedFd<'_> { + self.0.as_fd() + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl AsRawFd for PipeWriter { + fn as_raw_fd(&self) -> RawFd { + self.0.as_raw_fd() + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for OwnedFd { + fn from(pipe: PipeWriter) -> Self { + FileDesc::into_inner(pipe.0) + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl FromRawFd for PipeWriter { + unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { + unsafe { Self(FileDesc::from_raw_fd(raw_fd)) } + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl IntoRawFd for PipeWriter { + fn into_raw_fd(self) -> RawFd { + self.0.into_raw_fd() + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for Stdio { + fn from(pipe: PipeWriter) -> Self { + Self::from(OwnedFd::from(pipe)) + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for PipeReader { + fn from(owned_fd: OwnedFd) -> Self { + Self(FileDesc::from_inner(owned_fd)) + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for PipeWriter { + fn from(owned_fd: OwnedFd) -> Self { + Self(FileDesc::from_inner(owned_fd)) + } +} diff --git a/std/src/sys/anonymous_pipe/unsupported.rs b/std/src/sys/anonymous_pipe/unsupported.rs new file mode 100644 index 0000000000000..dd51e70315e96 --- /dev/null +++ b/std/src/sys/anonymous_pipe/unsupported.rs @@ -0,0 +1,23 @@ +use crate::io; +use crate::pipe::{PipeReader, PipeWriter}; +use crate::process::Stdio; +pub use crate::sys::pipe::AnonPipe; + +#[inline] +pub fn pipe() -> io::Result<(AnonPipe, AnonPipe)> { + Err(io::Error::UNSUPPORTED_PLATFORM) +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for Stdio { + fn from(pipe: PipeReader) -> Self { + pipe.0.diverge() + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for Stdio { + fn from(pipe: PipeWriter) -> Self { + pipe.0.diverge() + } +} diff --git a/std/src/sys/anonymous_pipe/windows.rs b/std/src/sys/anonymous_pipe/windows.rs new file mode 100644 index 0000000000000..a48198f8a812b --- /dev/null +++ b/std/src/sys/anonymous_pipe/windows.rs @@ -0,0 +1,116 @@ +use crate::os::windows::io::{ + AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle, OwnedHandle, RawHandle, +}; +use crate::pipe::{PipeReader, PipeWriter}; +use crate::process::Stdio; +use crate::sys::c; +use crate::sys::handle::Handle; +use crate::sys_common::{FromInner, IntoInner}; +use crate::{io, ptr}; + +pub type AnonPipe = Handle; + +pub fn pipe() -> io::Result<(AnonPipe, AnonPipe)> { + let mut read_pipe = c::INVALID_HANDLE_VALUE; + let mut write_pipe = c::INVALID_HANDLE_VALUE; + + let ret = unsafe { c::CreatePipe(&mut read_pipe, &mut write_pipe, ptr::null_mut(), 0) }; + + if ret == 0 { + Err(io::Error::last_os_error()) + } else { + unsafe { Ok((Handle::from_raw_handle(read_pipe), Handle::from_raw_handle(write_pipe))) } + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl AsHandle for PipeReader { + fn as_handle(&self) -> BorrowedHandle<'_> { + self.0.as_handle() + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl AsRawHandle for PipeReader { + fn as_raw_handle(&self) -> RawHandle { + self.0.as_raw_handle() + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl FromRawHandle for PipeReader { + unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self { + unsafe { Self(Handle::from_raw_handle(raw_handle)) } + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl IntoRawHandle for PipeReader { + fn into_raw_handle(self) -> RawHandle { + self.0.into_raw_handle() + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for OwnedHandle { + fn from(pipe: PipeReader) -> Self { + Handle::into_inner(pipe.0) + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for Stdio { + fn from(pipe: PipeReader) -> Self { + Self::from(OwnedHandle::from(pipe)) + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl AsHandle for PipeWriter { + fn as_handle(&self) -> BorrowedHandle<'_> { + self.0.as_handle() + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl AsRawHandle for PipeWriter { + fn as_raw_handle(&self) -> RawHandle { + self.0.as_raw_handle() + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl FromRawHandle for PipeWriter { + unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self { + unsafe { Self(Handle::from_raw_handle(raw_handle)) } + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl IntoRawHandle for PipeWriter { + fn into_raw_handle(self) -> RawHandle { + self.0.into_raw_handle() + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for OwnedHandle { + fn from(pipe: PipeWriter) -> Self { + Handle::into_inner(pipe.0) + } +} +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for Stdio { + fn from(pipe: PipeWriter) -> Self { + Self::from(OwnedHandle::from(pipe)) + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for PipeReader { + fn from(owned_handle: OwnedHandle) -> Self { + Self(Handle::from_inner(owned_handle)) + } +} + +#[unstable(feature = "anonymous_pipe", issue = "127154")] +impl From for PipeWriter { + fn from(owned_handle: OwnedHandle) -> Self { + Self(Handle::from_inner(owned_handle)) + } +} diff --git a/std/src/sys/backtrace.rs b/std/src/sys/backtrace.rs index 7401d8ce32087..4d939e175cf2e 100644 --- a/std/src/sys/backtrace.rs +++ b/std/src/sys/backtrace.rs @@ -1,13 +1,12 @@ //! Common code for printing backtraces. +#![forbid(unsafe_op_in_unsafe_fn)] use crate::backtrace_rs::{self, BacktraceFmt, BytesOrWideString, PrintFmt}; use crate::borrow::Cow; -use crate::env; -use crate::fmt; -use crate::io; use crate::io::prelude::*; use crate::path::{self, Path, PathBuf}; use crate::sync::{Mutex, MutexGuard, PoisonError}; +use crate::{env, fmt, io}; /// Max number of frames to print. const MAX_NB_FRAMES: usize = 100; @@ -62,73 +61,76 @@ unsafe fn _print_fmt(fmt: &mut fmt::Formatter<'_>, print_fmt: PrintFmt) -> fmt:: // Start immediately if we're not using a short backtrace. let mut start = print_fmt != PrintFmt::Short; set_image_base(); - backtrace_rs::trace_unsynchronized(|frame| { - if print_fmt == PrintFmt::Short && idx > MAX_NB_FRAMES { - return false; - } + // SAFETY: we roll our own locking in this town + unsafe { + backtrace_rs::trace_unsynchronized(|frame| { + if print_fmt == PrintFmt::Short && idx > MAX_NB_FRAMES { + return false; + } - let mut hit = false; - backtrace_rs::resolve_frame_unsynchronized(frame, |symbol| { - hit = true; - - // Any frames between `__rust_begin_short_backtrace` and `__rust_end_short_backtrace` - // are omitted from the backtrace in short mode, `__rust_end_short_backtrace` will be - // called before the panic hook, so we won't ignore any frames if there is no - // invoke of `__rust_begin_short_backtrace`. - if print_fmt == PrintFmt::Short { - if let Some(sym) = symbol.name().and_then(|s| s.as_str()) { - if start && sym.contains("__rust_begin_short_backtrace") { - start = false; - return; - } - if sym.contains("__rust_end_short_backtrace") { - start = true; - return; - } - if !start { - omitted_count += 1; + let mut hit = false; + backtrace_rs::resolve_frame_unsynchronized(frame, |symbol| { + hit = true; + + // Any frames between `__rust_begin_short_backtrace` and `__rust_end_short_backtrace` + // are omitted from the backtrace in short mode, `__rust_end_short_backtrace` will be + // called before the panic hook, so we won't ignore any frames if there is no + // invoke of `__rust_begin_short_backtrace`. + if print_fmt == PrintFmt::Short { + if let Some(sym) = symbol.name().and_then(|s| s.as_str()) { + if start && sym.contains("__rust_begin_short_backtrace") { + start = false; + return; + } + if sym.contains("__rust_end_short_backtrace") { + start = true; + return; + } + if !start { + omitted_count += 1; + } } } - } - if start { - if omitted_count > 0 { - debug_assert!(print_fmt == PrintFmt::Short); - // only print the message between the middle of frames - if !first_omit { - let _ = writeln!( - bt_fmt.formatter(), - " [... omitted {} frame{} ...]", - omitted_count, - if omitted_count > 1 { "s" } else { "" } - ); + if start { + if omitted_count > 0 { + debug_assert!(print_fmt == PrintFmt::Short); + // only print the message between the middle of frames + if !first_omit { + let _ = writeln!( + bt_fmt.formatter(), + " [... omitted {} frame{} ...]", + omitted_count, + if omitted_count > 1 { "s" } else { "" } + ); + } + first_omit = false; + omitted_count = 0; } - first_omit = false; - omitted_count = 0; + res = bt_fmt.frame().symbol(frame, symbol); } - res = bt_fmt.frame().symbol(frame, symbol); + }); + #[cfg(target_os = "nto")] + if libc::__my_thread_exit as *mut libc::c_void == frame.ip() { + if !hit && start { + use crate::backtrace_rs::SymbolName; + res = bt_fmt.frame().print_raw( + frame.ip(), + Some(SymbolName::new("__my_thread_exit".as_bytes())), + None, + None, + ); + } + return false; } - }); - #[cfg(target_os = "nto")] - if libc::__my_thread_exit as *mut libc::c_void == frame.ip() { if !hit && start { - use crate::backtrace_rs::SymbolName; - res = bt_fmt.frame().print_raw( - frame.ip(), - Some(SymbolName::new("__my_thread_exit".as_bytes())), - None, - None, - ); + res = bt_fmt.frame().print_raw(frame.ip(), None, None, None); } - return false; - } - if !hit && start { - res = bt_fmt.frame().print_raw(frame.ip(), None, None, None); - } - idx += 1; - res.is_ok() - }); + idx += 1; + res.is_ok() + }) + }; res?; bt_fmt.finish()?; if print_fmt == PrintFmt::Short { diff --git a/std/src/sys/mod.rs b/std/src/sys/mod.rs index e50758ce00d8b..a86b3628f249a 100644 --- a/std/src/sys/mod.rs +++ b/std/src/sys/mod.rs @@ -7,6 +7,7 @@ mod pal; mod personality; +pub mod anonymous_pipe; pub mod backtrace; pub mod cmath; pub mod exit_guard; diff --git a/std/src/sys/os_str/bytes.rs b/std/src/sys/os_str/bytes.rs index 2a7477e3afc20..0f8bd6453528e 100644 --- a/std/src/sys/os_str/bytes.rs +++ b/std/src/sys/os_str/bytes.rs @@ -3,13 +3,11 @@ use crate::borrow::Cow; use crate::collections::TryReserveError; -use crate::fmt; use crate::fmt::Write; -use crate::mem; use crate::rc::Rc; -use crate::str; use crate::sync::Arc; use crate::sys_common::{AsInner, IntoInner}; +use crate::{fmt, mem, str}; #[cfg(test)] mod tests; diff --git a/std/src/sys/os_str/wtf8.rs b/std/src/sys/os_str/wtf8.rs index 806bf033dbc94..ed975ba58b5e2 100644 --- a/std/src/sys/os_str/wtf8.rs +++ b/std/src/sys/os_str/wtf8.rs @@ -2,12 +2,11 @@ //! wrapper around the "WTF-8" encoding; see the `wtf8` module for more. use crate::borrow::Cow; use crate::collections::TryReserveError; -use crate::fmt; -use crate::mem; use crate::rc::Rc; use crate::sync::Arc; use crate::sys_common::wtf8::{check_utf8_boundary, Wtf8, Wtf8Buf}; use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::{fmt, mem}; #[derive(Clone, Hash)] pub struct Buf { diff --git a/std/src/sys/pal/common/alloc.rs b/std/src/sys/pal/common/alloc.rs index 598b6db71f5de..1b465f95d1bc3 100644 --- a/std/src/sys/pal/common/alloc.rs +++ b/std/src/sys/pal/common/alloc.rs @@ -1,6 +1,6 @@ +#![forbid(unsafe_op_in_unsafe_fn)] use crate::alloc::{GlobalAlloc, Layout, System}; -use crate::cmp; -use crate::ptr; +use crate::{cmp, ptr}; // The minimum alignment guaranteed by the architecture. This value is used to // add fast paths for low alignment values. @@ -46,14 +46,16 @@ pub unsafe fn realloc_fallback( old_layout: Layout, new_size: usize, ) -> *mut u8 { - // Docs for GlobalAlloc::realloc require this to be valid: - let new_layout = Layout::from_size_align_unchecked(new_size, old_layout.align()); + // SAFETY: Docs for GlobalAlloc::realloc require this to be valid + unsafe { + let new_layout = Layout::from_size_align_unchecked(new_size, old_layout.align()); - let new_ptr = GlobalAlloc::alloc(alloc, new_layout); - if !new_ptr.is_null() { - let size = cmp::min(old_layout.size(), new_size); - ptr::copy_nonoverlapping(ptr, new_ptr, size); - GlobalAlloc::dealloc(alloc, ptr, old_layout); + let new_ptr = GlobalAlloc::alloc(alloc, new_layout); + if !new_ptr.is_null() { + let size = cmp::min(old_layout.size(), new_size); + ptr::copy_nonoverlapping(ptr, new_ptr, size); + GlobalAlloc::dealloc(alloc, ptr, old_layout); + } + new_ptr } - new_ptr } diff --git a/std/src/sys/pal/common/small_c_string.rs b/std/src/sys/pal/common/small_c_string.rs index 37812fc0659a2..3c96714b5c58c 100644 --- a/std/src/sys/pal/common/small_c_string.rs +++ b/std/src/sys/pal/common/small_c_string.rs @@ -1,8 +1,7 @@ use crate::ffi::{CStr, CString}; use crate::mem::MaybeUninit; use crate::path::Path; -use crate::slice; -use crate::{io, ptr}; +use crate::{io, ptr, slice}; // Make sure to stay under 4096 so the compiler doesn't insert a probe frame: // https://docs.rs/compiler_builtins/latest/compiler_builtins/probestack/index.html diff --git a/std/src/sys/pal/common/tests.rs b/std/src/sys/pal/common/tests.rs index e72d02203da10..b7698907070c7 100644 --- a/std/src/sys/pal/common/tests.rs +++ b/std/src/sys/pal/common/tests.rs @@ -1,8 +1,9 @@ +use core::iter::repeat; + use crate::ffi::CString; use crate::hint::black_box; use crate::path::Path; use crate::sys::common::small_c_string::run_path_with_cstr; -use core::iter::repeat; #[test] fn stack_allocation_works() { diff --git a/std/src/sys/pal/hermit/alloc.rs b/std/src/sys/pal/hermit/alloc.rs index 2cd0db909403b..f10d5f9227e63 100644 --- a/std/src/sys/pal/hermit/alloc.rs +++ b/std/src/sys/pal/hermit/alloc.rs @@ -1,31 +1,28 @@ use super::hermit_abi; use crate::alloc::{GlobalAlloc, Layout, System}; -use crate::ptr; #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - hermit_abi::malloc(layout.size(), layout.align()) - } - - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - let addr = hermit_abi::malloc(layout.size(), layout.align()); - - if !addr.is_null() { - ptr::write_bytes(addr, 0x00, layout.size()); - } - - addr + let size = layout.size(); + let align = layout.align(); + unsafe { hermit_abi::malloc(size, align) } } #[inline] unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - hermit_abi::free(ptr, layout.size(), layout.align()) + let size = layout.size(); + let align = layout.align(); + unsafe { + hermit_abi::free(ptr, size, align); + } } #[inline] unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { - hermit_abi::realloc(ptr, layout.size(), layout.align(), new_size) + let size = layout.size(); + let align = layout.align(); + unsafe { hermit_abi::realloc(ptr, size, align, new_size) } } } diff --git a/std/src/sys/pal/hermit/args.rs b/std/src/sys/pal/hermit/args.rs index 220a76e4b1237..51afe3434aedc 100644 --- a/std/src/sys/pal/hermit/args.rs +++ b/std/src/sys/pal/hermit/args.rs @@ -1,12 +1,8 @@ use crate::ffi::{c_char, CStr, OsString}; -use crate::fmt; use crate::os::hermit::ffi::OsStringExt; -use crate::ptr; -use crate::sync::atomic::{ - AtomicIsize, AtomicPtr, - Ordering::{Acquire, Relaxed, Release}, -}; -use crate::vec; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use crate::sync::atomic::{AtomicIsize, AtomicPtr}; +use crate::{fmt, ptr, vec}; static ARGC: AtomicIsize = AtomicIsize::new(0); static ARGV: AtomicPtr<*const u8> = AtomicPtr::new(ptr::null_mut()); diff --git a/std/src/sys/pal/hermit/fd.rs b/std/src/sys/pal/hermit/fd.rs index 3c52b85de23a2..79fc13bd4a87f 100644 --- a/std/src/sys/pal/hermit/fd.rs +++ b/std/src/sys/pal/hermit/fd.rs @@ -3,13 +3,10 @@ use super::hermit_abi; use crate::cmp; use crate::io::{self, IoSlice, IoSliceMut, Read}; -use crate::os::hermit::io::{FromRawFd, OwnedFd, RawFd}; -use crate::sys::cvt; -use crate::sys::unsupported; +use crate::os::hermit::io::{FromRawFd, OwnedFd, RawFd, *}; +use crate::sys::{cvt, unsupported}; use crate::sys_common::{AsInner, FromInner, IntoInner}; -use crate::os::hermit::io::*; - const fn max_iov() -> usize { hermit_abi::IOV_MAX } @@ -114,7 +111,8 @@ impl FromInner for FileDesc { impl FromRawFd for FileDesc { unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { - Self { fd: FromRawFd::from_raw_fd(raw_fd) } + let fd = unsafe { OwnedFd::from_raw_fd(raw_fd) }; + Self { fd } } } diff --git a/std/src/sys/pal/hermit/fs.rs b/std/src/sys/pal/hermit/fs.rs index e4e9eee044efa..aaf1a044d0613 100644 --- a/std/src/sys/pal/hermit/fs.rs +++ b/std/src/sys/pal/hermit/fs.rs @@ -4,21 +4,17 @@ use super::hermit_abi::{ O_DIRECTORY, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, S_IFDIR, S_IFLNK, S_IFMT, S_IFREG, }; use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; -use crate::io::{self, Error, ErrorKind}; -use crate::io::{BorrowedCursor, IoSlice, IoSliceMut, SeekFrom}; -use crate::mem; +use crate::io::{self, BorrowedCursor, Error, ErrorKind, IoSlice, IoSliceMut, SeekFrom}; use crate::os::hermit::ffi::OsStringExt; use crate::os::hermit::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::path::{Path, PathBuf}; use crate::sync::Arc; use crate::sys::common::small_c_string::run_path_with_cstr; -use crate::sys::cvt; use crate::sys::time::SystemTime; -use crate::sys::unsupported; -use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; - +use crate::sys::{cvt, unsupported}; pub use crate::sys_common::fs::{copy, exists}; +use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; +use crate::{fmt, mem}; #[derive(Debug)] pub struct File(FileDesc); @@ -488,7 +484,8 @@ impl IntoRawFd for File { impl FromRawFd for File { unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { - Self(FromRawFd::from_raw_fd(raw_fd)) + let file_desc = unsafe { FileDesc::from_raw_fd(raw_fd) }; + Self(file_desc) } } diff --git a/std/src/sys/pal/hermit/io.rs b/std/src/sys/pal/hermit/io.rs index 9de7b53e53c03..aad1eef71e9b0 100644 --- a/std/src/sys/pal/hermit/io.rs +++ b/std/src/sys/pal/hermit/io.rs @@ -1,9 +1,9 @@ +use hermit_abi::{c_void, iovec}; + use crate::marker::PhantomData; use crate::os::hermit::io::{AsFd, AsRawFd}; use crate::slice; -use hermit_abi::{c_void, iovec}; - #[derive(Copy, Clone)] #[repr(transparent)] pub struct IoSlice<'a> { diff --git a/std/src/sys/pal/hermit/mod.rs b/std/src/sys/pal/hermit/mod.rs index 55583b89d6714..ef406b9ec7f0d 100644 --- a/std/src/sys/pal/hermit/mod.rs +++ b/std/src/sys/pal/hermit/mod.rs @@ -13,7 +13,8 @@ //! compiling for wasm. That way it's a compile time error for something that's //! guaranteed to be a runtime error! -#![allow(missing_docs, nonstandard_style, unsafe_op_in_unsafe_fn)] +#![deny(unsafe_op_in_unsafe_fn)] +#![allow(missing_docs, nonstandard_style)] use crate::os::raw::c_char; @@ -49,9 +50,7 @@ pub fn unsupported_err() -> crate::io::Error { } pub fn abort_internal() -> ! { - unsafe { - hermit_abi::abort(); - } + unsafe { hermit_abi::abort() } } pub fn hashmap_random_keys() -> (u64, u64) { @@ -80,7 +79,9 @@ pub extern "C" fn __rust_abort() { // SAFETY: must be called only once during runtime initialization. // NOTE: this is not guaranteed to run, for example when Rust code is called externally. pub unsafe fn init(argc: isize, argv: *const *const u8, _sigpipe: u8) { - args::init(argc, argv); + unsafe { + args::init(argc, argv); + } } // SAFETY: must be called only once during runtime cleanup. @@ -101,10 +102,12 @@ pub unsafe extern "C" fn runtime_entry( // initialize environment os::init_environment(env as *const *const i8); - let result = main(argc as isize, argv); + let result = unsafe { main(argc as isize, argv) }; - crate::sys::thread_local::destructors::run(); - hermit_abi::exit(result); + unsafe { + crate::sys::thread_local::destructors::run(); + } + unsafe { hermit_abi::exit(result) } } #[inline] diff --git a/std/src/sys/pal/hermit/net.rs b/std/src/sys/pal/hermit/net.rs index 6016d50eba085..416469c003738 100644 --- a/std/src/sys/pal/hermit/net.rs +++ b/std/src/sys/pal/hermit/net.rs @@ -1,17 +1,16 @@ #![allow(dead_code)] +use core::ffi::c_int; + use super::fd::FileDesc; -use crate::cmp; use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut}; -use crate::mem; use crate::net::{Shutdown, SocketAddr}; use crate::os::hermit::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, RawFd}; use crate::sys::time::Instant; use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr}; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; - -use core::ffi::c_int; +use crate::{cmp, mem}; #[allow(unused_extern_crates)] pub extern crate hermit_abi as netc; diff --git a/std/src/sys/pal/hermit/os.rs b/std/src/sys/pal/hermit/os.rs index a7a73c756f216..f8ea80afa43f1 100644 --- a/std/src/sys/pal/hermit/os.rs +++ b/std/src/sys/pal/hermit/os.rs @@ -1,17 +1,15 @@ +use core::slice::memchr; + use super::hermit_abi; use crate::collections::HashMap; use crate::error::Error as StdError; use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::os::hermit::ffi::OsStringExt; use crate::path::{self, PathBuf}; -use crate::str; use crate::sync::Mutex; use crate::sys::unsupported; -use crate::vec; -use core::slice::memchr; +use crate::{fmt, io, str, vec}; pub fn errno() -> i32 { unsafe { hermit_abi::get_errno() } @@ -70,21 +68,21 @@ pub fn current_exe() -> io::Result { unsupported() } -static mut ENV: Option>> = None; +static ENV: Mutex>> = Mutex::new(None); pub fn init_environment(env: *const *const i8) { - unsafe { - ENV = Some(Mutex::new(HashMap::new())); + let mut guard = ENV.lock().unwrap(); + let map = guard.insert(HashMap::new()); - if env.is_null() { - return; - } + if env.is_null() { + return; + } - let mut guard = ENV.as_ref().unwrap().lock().unwrap(); + unsafe { let mut environ = env; while !(*environ).is_null() { if let Some((key, value)) = parse(CStr::from_ptr(*environ).to_bytes()) { - guard.insert(key, value); + map.insert(key, value); } environ = environ.add(1); } @@ -156,30 +154,26 @@ impl Iterator for Env { /// Returns a vector of (variable, value) byte-vector pairs for all the /// environment variables of the current process. pub fn env() -> Env { - unsafe { - let guard = ENV.as_ref().unwrap().lock().unwrap(); - let mut result = Vec::new(); + let guard = ENV.lock().unwrap(); + let env = guard.as_ref().unwrap(); - for (key, value) in guard.iter() { - result.push((key.clone(), value.clone())); - } + let result = env.iter().map(|(key, value)| (key.clone(), value.clone())).collect::>(); - return Env { iter: result.into_iter() }; - } + Env { iter: result.into_iter() } } pub fn getenv(k: &OsStr) -> Option { - unsafe { ENV.as_ref().unwrap().lock().unwrap().get_mut(k).cloned() } + ENV.lock().unwrap().as_ref().unwrap().get(k).cloned() } pub unsafe fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let (k, v) = (k.to_owned(), v.to_owned()); - ENV.as_ref().unwrap().lock().unwrap().insert(k, v); + ENV.lock().unwrap().as_mut().unwrap().insert(k, v); Ok(()) } pub unsafe fn unsetenv(k: &OsStr) -> io::Result<()> { - ENV.as_ref().unwrap().lock().unwrap().remove(k); + ENV.lock().unwrap().as_mut().unwrap().remove(k); Ok(()) } @@ -192,9 +186,7 @@ pub fn home_dir() -> Option { } pub fn exit(code: i32) -> ! { - unsafe { - hermit_abi::exit(code); - } + unsafe { hermit_abi::exit(code) } } pub fn getpid() -> u32 { diff --git a/std/src/sys/pal/hermit/thread.rs b/std/src/sys/pal/hermit/thread.rs index a244b953d2a49..6321f92e3d9d0 100644 --- a/std/src/sys/pal/hermit/thread.rs +++ b/std/src/sys/pal/hermit/thread.rs @@ -2,11 +2,10 @@ use super::hermit_abi; use crate::ffi::CStr; -use crate::io; -use crate::mem; +use crate::mem::ManuallyDrop; use crate::num::NonZero; -use crate::ptr; use crate::time::Duration; +use crate::{io, ptr}; pub type Tid = hermit_abi::Tid; @@ -26,18 +25,22 @@ impl Thread { core_id: isize, ) -> io::Result { let p = Box::into_raw(Box::new(p)); - let tid = hermit_abi::spawn2( - thread_start, - p.expose_provenance(), - hermit_abi::Priority::into(hermit_abi::NORMAL_PRIO), - stack, - core_id, - ); + let tid = unsafe { + hermit_abi::spawn2( + thread_start, + p.expose_provenance(), + hermit_abi::Priority::into(hermit_abi::NORMAL_PRIO), + stack, + core_id, + ) + }; return if tid == 0 { // The thread failed to start and as a result p was not consumed. Therefore, it is // safe to reconstruct the box so that it gets deallocated. - drop(Box::from_raw(p)); + unsafe { + drop(Box::from_raw(p)); + } Err(io::const_io_error!(io::ErrorKind::Uncategorized, "Unable to create thread!")) } else { Ok(Thread { tid: tid }) @@ -55,7 +58,9 @@ impl Thread { } pub unsafe fn new(stack: usize, p: Box) -> io::Result { - Thread::new_with_coreid(stack, p, -1 /* = no specific core */) + unsafe { + Thread::new_with_coreid(stack, p, -1 /* = no specific core */) + } } #[inline] @@ -90,9 +95,7 @@ impl Thread { #[inline] pub fn into_id(self) -> Tid { - let id = self.tid; - mem::forget(self); - id + ManuallyDrop::new(self).tid } } diff --git a/std/src/sys/pal/hermit/time.rs b/std/src/sys/pal/hermit/time.rs index e0cb7c2aa98a5..2c87c4860a27a 100644 --- a/std/src/sys/pal/hermit/time.rs +++ b/std/src/sys/pal/hermit/time.rs @@ -1,10 +1,11 @@ #![allow(dead_code)] +use core::hash::{Hash, Hasher}; + use super::hermit_abi::{self, timespec, CLOCK_MONOTONIC, CLOCK_REALTIME}; use crate::cmp::Ordering; use crate::ops::{Add, AddAssign, Sub, SubAssign}; use crate::time::Duration; -use core::hash::{Hash, Hasher}; const NSEC_PER_SEC: i32 = 1_000_000_000; diff --git a/std/src/sys/pal/itron/error.rs b/std/src/sys/pal/itron/error.rs index fbc822d4eb6e1..8ff3017c61471 100644 --- a/std/src/sys/pal/itron/error.rs +++ b/std/src/sys/pal/itron/error.rs @@ -1,6 +1,6 @@ -use crate::{fmt, io::ErrorKind}; - use super::abi; +use crate::fmt; +use crate::io::ErrorKind; /// Wraps a μITRON error code. #[derive(Debug, Copy, Clone)] @@ -9,7 +9,7 @@ pub struct ItronError { } impl ItronError { - /// Construct `ItronError` from the specified error code. Returns `None` if the + /// Constructs `ItronError` from the specified error code. Returns `None` if the /// error code does not represent a failure or warning. #[inline] pub fn new(er: abi::ER) -> Option { @@ -22,7 +22,7 @@ impl ItronError { if let Some(error) = Self::new(er) { Err(error) } else { Ok(er) } } - /// Get the raw error code. + /// Gets the raw error code. #[inline] pub fn as_raw(&self) -> abi::ER { self.er diff --git a/std/src/sys/pal/itron/spin.rs b/std/src/sys/pal/itron/spin.rs index 44d409444bca4..6a9a7c72deb7d 100644 --- a/std/src/sys/pal/itron/spin.rs +++ b/std/src/sys/pal/itron/spin.rs @@ -1,9 +1,7 @@ use super::abi; -use crate::{ - cell::UnsafeCell, - mem::MaybeUninit, - sync::atomic::{AtomicBool, AtomicUsize, Ordering}, -}; +use crate::cell::UnsafeCell; +use crate::mem::MaybeUninit; +use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; /// A mutex implemented by `dis_dsp` (for intra-core synchronization) and a /// spinlock (for inter-core synchronization). diff --git a/std/src/sys/pal/itron/task.rs b/std/src/sys/pal/itron/task.rs index 94beb50a2541b..5da0c5917885f 100644 --- a/std/src/sys/pal/itron/task.rs +++ b/std/src/sys/pal/itron/task.rs @@ -1,23 +1,20 @@ -use super::{ - abi, - error::{fail, fail_aborting, ItronError}, -}; - +use super::abi; +use super::error::{fail, fail_aborting, ItronError}; use crate::mem::MaybeUninit; -/// Get the ID of the task in Running state. Panics on failure. +/// Gets the ID of the task in Running state. Panics on failure. #[inline] pub fn current_task_id() -> abi::ID { try_current_task_id().unwrap_or_else(|e| fail(e, &"get_tid")) } -/// Get the ID of the task in Running state. Aborts on failure. +/// Gets the ID of the task in Running state. Aborts on failure. #[inline] pub fn current_task_id_aborting() -> abi::ID { try_current_task_id().unwrap_or_else(|e| fail_aborting(e, &"get_tid")) } -/// Get the ID of the task in Running state. +/// Gets the ID of the task in Running state. #[inline] pub fn try_current_task_id() -> Result { unsafe { @@ -27,13 +24,13 @@ pub fn try_current_task_id() -> Result { } } -/// Get the specified task's priority. Panics on failure. +/// Gets the specified task's priority. Panics on failure. #[inline] pub fn task_priority(task: abi::ID) -> abi::PRI { try_task_priority(task).unwrap_or_else(|e| fail(e, &"get_pri")) } -/// Get the specified task's priority. +/// Gets the specified task's priority. #[inline] pub fn try_task_priority(task: abi::ID) -> Result { unsafe { diff --git a/std/src/sys/pal/itron/thread.rs b/std/src/sys/pal/itron/thread.rs index fd7b5558f7566..01e69afa99e13 100644 --- a/std/src/sys/pal/itron/thread.rs +++ b/std/src/sys/pal/itron/thread.rs @@ -1,22 +1,17 @@ //! Thread implementation backed by μITRON tasks. Assumes `acre_tsk` and //! `exd_tsk` are available. -use super::{ - abi, - error::{expect_success, expect_success_aborting, ItronError}, - task, - time::dur2reltims, -}; -use crate::{ - cell::UnsafeCell, - ffi::CStr, - hint, io, - mem::ManuallyDrop, - num::NonZero, - ptr::NonNull, - sync::atomic::{AtomicUsize, Ordering}, - time::Duration, -}; +use super::error::{expect_success, expect_success_aborting, ItronError}; +use super::time::dur2reltims; +use super::{abi, task}; +use crate::cell::UnsafeCell; +use crate::ffi::CStr; +use crate::mem::ManuallyDrop; +use crate::num::NonZero; +use crate::ptr::NonNull; +use crate::sync::atomic::{AtomicUsize, Ordering}; +use crate::time::Duration; +use crate::{hint, io}; pub struct Thread { p_inner: NonNull, @@ -308,7 +303,7 @@ impl Drop for Thread { } } -/// Terminate and delete the specified task. +/// Terminates and deletes the specified task. /// /// This function will abort if `deleted_task` refers to the calling task. /// @@ -337,7 +332,7 @@ unsafe fn terminate_and_delete_task(deleted_task: abi::ID) { expect_success_aborting(unsafe { abi::del_tsk(deleted_task) }, &"del_tsk"); } -/// Terminate and delete the calling task. +/// Terminates and deletes the calling task. /// /// Atomicity is not required - i.e., it can be assumed that other threads won't /// `ter_tsk` the calling task while this function is still in progress. (This diff --git a/std/src/sys/pal/itron/time.rs b/std/src/sys/pal/itron/time.rs index 427ea0d80e107..7976c27f4952b 100644 --- a/std/src/sys/pal/itron/time.rs +++ b/std/src/sys/pal/itron/time.rs @@ -1,5 +1,7 @@ -use super::{abi, error::expect_success}; -use crate::{mem::MaybeUninit, time::Duration}; +use super::abi; +use super::error::expect_success; +use crate::mem::MaybeUninit; +use crate::time::Duration; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub struct Instant(abi::SYSTIM); diff --git a/std/src/sys/pal/mod.rs b/std/src/sys/pal/mod.rs index df0176244489a..9be018c8a5312 100644 --- a/std/src/sys/pal/mod.rs +++ b/std/src/sys/pal/mod.rs @@ -76,23 +76,5 @@ cfg_if::cfg_if! { } } -#[cfg(not(test))] -cfg_if::cfg_if! { - if #[cfg(target_os = "android")] { - pub use self::android::log2f32; - pub use self::android::log2f64; - } else { - #[inline] - pub fn log2f32(n: f32) -> f32 { - unsafe { crate::intrinsics::log2f32(n) } - } - - #[inline] - pub fn log2f64(n: f64) -> f64 { - unsafe { crate::intrinsics::log2f64(n) } - } - } -} - #[cfg(not(target_os = "uefi"))] pub type RawOsError = i32; diff --git a/std/src/sys/pal/sgx/abi/mod.rs b/std/src/sys/pal/sgx/abi/mod.rs index 9508c38741551..d8836452e7555 100644 --- a/std/src/sys/pal/sgx/abi/mod.rs +++ b/std/src/sys/pal/sgx/abi/mod.rs @@ -1,9 +1,10 @@ #![cfg_attr(test, allow(unused))] // RT initialization logic is not compiled for test -use crate::io::Write; use core::arch::global_asm; use core::sync::atomic::{AtomicUsize, Ordering}; +use crate::io::Write; + // runtime features pub(super) mod panic; mod reloc; diff --git a/std/src/sys/pal/sgx/abi/panic.rs b/std/src/sys/pal/sgx/abi/panic.rs index 229b3b3291f63..c06b97ee3674a 100644 --- a/std/src/sys/pal/sgx/abi/panic.rs +++ b/std/src/sys/pal/sgx/abi/panic.rs @@ -1,7 +1,6 @@ use super::usercalls::alloc::UserRef; -use crate::cmp; use crate::io::{self, Write}; -use crate::mem; +use crate::{cmp, mem}; extern "C" { fn take_debug_panic_buf_ptr() -> *mut u8; diff --git a/std/src/sys/pal/sgx/abi/tls/mod.rs b/std/src/sys/pal/sgx/abi/tls/mod.rs index 8a9ea4ac00df0..34fc2f20d2214 100644 --- a/std/src/sys/pal/sgx/abi/tls/mod.rs +++ b/std/src/sys/pal/sgx/abi/tls/mod.rs @@ -2,10 +2,9 @@ mod sync_bitset; use self::sync_bitset::*; use crate::cell::Cell; -use crate::mem; use crate::num::NonZero; -use crate::ptr; use crate::sync::atomic::{AtomicUsize, Ordering}; +use crate::{mem, ptr}; #[cfg(target_pointer_width = "64")] const USIZE_BITS: usize = 64; @@ -95,8 +94,8 @@ impl Tls { #[allow(unused)] pub unsafe fn activate_persistent(self: Box) { // FIXME: Needs safety information. See entry.S for `set_tls_ptr` definition. - unsafe { set_tls_ptr(core::ptr::addr_of!(*self) as _) }; - mem::forget(self); + let ptr = Box::into_raw(self).cast_const().cast::(); + unsafe { set_tls_ptr(ptr) }; } unsafe fn current<'a>() -> &'a Tls { diff --git a/std/src/sys/pal/sgx/abi/usercalls/alloc.rs b/std/src/sys/pal/sgx/abi/usercalls/alloc.rs index f99cea360f1f4..298095257396a 100644 --- a/std/src/sys/pal/sgx/abi/usercalls/alloc.rs +++ b/std/src/sys/pal/sgx/abi/usercalls/alloc.rs @@ -1,18 +1,16 @@ #![allow(unused)] +use fortanix_sgx_abi::*; + +use super::super::mem::{is_enclave_range, is_user_range}; use crate::arch::asm; use crate::cell::UnsafeCell; -use crate::cmp; use crate::convert::TryInto; -use crate::intrinsics; -use crate::mem; +use crate::mem::{self, ManuallyDrop}; use crate::ops::{CoerceUnsized, Deref, DerefMut, Index, IndexMut}; use crate::ptr::{self, NonNull}; -use crate::slice; use crate::slice::SliceIndex; - -use super::super::mem::{is_enclave_range, is_user_range}; -use fortanix_sgx_abi::*; +use crate::{cmp, intrinsics, slice}; /// A type that can be safely read from or written to userspace. /// @@ -67,7 +65,7 @@ pub unsafe trait UserSafe { /// Equivalent to `mem::align_of::`. fn align_of() -> usize; - /// Construct a pointer to `Self` given a memory range in user space. + /// Constructs a pointer to `Self` given a memory range in user space. /// /// N.B., this takes a size, not a length! /// @@ -77,7 +75,7 @@ pub unsafe trait UserSafe { /// correct size and is correctly aligned and points to the right type. unsafe fn from_raw_sized_unchecked(ptr: *mut u8, size: usize) -> *mut Self; - /// Construct a pointer to `Self` given a memory range. + /// Constructs a pointer to `Self` given a memory range. /// /// N.B., this takes a size, not a length! /// @@ -176,6 +174,7 @@ unsafe impl UserSafe for [T] { /// are used solely to indicate intent: a mutable reference is for writing to /// user memory, an immutable reference for reading from user memory. #[unstable(feature = "sgx_platform", issue = "56975")] +#[repr(transparent)] pub struct UserRef(UnsafeCell); /// An owned type in userspace memory. `User` is equivalent to `Box` in /// enclave memory. Access to the memory is only allowed by copying to avoid @@ -266,9 +265,7 @@ where /// Converts this value into a raw pointer. The value will no longer be /// automatically freed. pub fn into_raw(self) -> *mut T { - let ret = self.0; - mem::forget(self); - ret.as_ptr() as _ + ManuallyDrop::new(self).0.as_ptr() as _ } } @@ -277,7 +274,7 @@ impl User where T: UserSafe, { - /// Allocate space for `T` in user memory. + /// Allocates space for `T` in user memory. pub fn uninitialized() -> Self { Self::new_uninit_bytes(mem::size_of::()) } @@ -288,7 +285,7 @@ impl User<[T]> where [T]: UserSafe, { - /// Allocate space for a `[T]` of `n` elements in user memory. + /// Allocates space for a `[T]` of `n` elements in user memory. pub fn uninitialized(n: usize) -> Self { Self::new_uninit_bytes(n * mem::size_of::()) } diff --git a/std/src/sys/pal/sgx/abi/usercalls/mod.rs b/std/src/sys/pal/sgx/abi/usercalls/mod.rs index e19e843267a90..def1ccdf81ac0 100644 --- a/std/src/sys/pal/sgx/abi/usercalls/mod.rs +++ b/std/src/sys/pal/sgx/abi/usercalls/mod.rs @@ -171,10 +171,12 @@ pub fn wait(event_mask: u64, mut timeout: u64) -> IoResult { unsafe { raw::wait(event_mask, timeout).from_sgx_result() } } -/// This function makes an effort to wait for a non-spurious event at least as -/// long as `duration`. Note that in general there is no guarantee about accuracy -/// of time and timeouts in SGX model. The enclave runner serving usercalls may -/// lie about current time and/or ignore timeout values. +/// Makes an effort to wait for a non-spurious event at least as long as +/// `duration`. +/// +/// Note that in general there is no guarantee about accuracy of time and +/// timeouts in SGX model. The enclave runner serving usercalls may lie about +/// current time and/or ignore timeout values. /// /// Once the event is observed, `should_wake_up` will be used to determine /// whether or not the event was spurious. diff --git a/std/src/sys/pal/sgx/abi/usercalls/tests.rs b/std/src/sys/pal/sgx/abi/usercalls/tests.rs index 58b8eb215d73c..ef824d35f4a16 100644 --- a/std/src/sys/pal/sgx/abi/usercalls/tests.rs +++ b/std/src/sys/pal/sgx/abi/usercalls/tests.rs @@ -1,5 +1,4 @@ -use super::alloc::User; -use super::alloc::{copy_from_userspace, copy_to_userspace}; +use super::alloc::{copy_from_userspace, copy_to_userspace, User}; #[test] fn test_copy_to_userspace_function() { diff --git a/std/src/sys/pal/sgx/alloc.rs b/std/src/sys/pal/sgx/alloc.rs index 0c7bf9a9201f2..f68ede9fcf012 100644 --- a/std/src/sys/pal/sgx/alloc.rs +++ b/std/src/sys/pal/sgx/alloc.rs @@ -1,9 +1,9 @@ -use crate::alloc::{GlobalAlloc, Layout, System}; -use crate::ptr; use core::sync::atomic::{AtomicBool, Ordering}; use super::abi::mem as sgx_mem; use super::waitqueue::SpinMutex; +use crate::alloc::{GlobalAlloc, Layout, System}; +use crate::ptr; // Using a SpinMutex because we never want to exit the enclave waiting for the // allocator. diff --git a/std/src/sys/pal/sgx/args.rs b/std/src/sys/pal/sgx/args.rs index ef4176c4ac0f0..a72a041da6cc9 100644 --- a/std/src/sys/pal/sgx/args.rs +++ b/std/src/sys/pal/sgx/args.rs @@ -1,10 +1,10 @@ -use super::abi::usercalls::{alloc, raw::ByteBuffer}; +use super::abi::usercalls::alloc; +use super::abi::usercalls::raw::ByteBuffer; use crate::ffi::OsString; -use crate::fmt; -use crate::slice; use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sys::os_str::Buf; use crate::sys_common::FromInner; +use crate::{fmt, slice}; #[cfg_attr(test, linkage = "available_externally")] #[export_name = "_ZN16__rust_internals3std3sys3sgx4args4ARGSE"] diff --git a/std/src/sys/pal/sgx/fd.rs b/std/src/sys/pal/sgx/fd.rs index b3686d0e28328..c41b527cff798 100644 --- a/std/src/sys/pal/sgx/fd.rs +++ b/std/src/sys/pal/sgx/fd.rs @@ -2,7 +2,7 @@ use fortanix_sgx_abi::Fd; use super::abi::usercalls; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; -use crate::mem; +use crate::mem::ManuallyDrop; use crate::sys::{AsInner, FromInner, IntoInner}; #[derive(Debug)] @@ -21,9 +21,7 @@ impl FileDesc { /// Extracts the actual file descriptor without closing it. pub fn into_raw(self) -> Fd { - let fd = self.fd; - mem::forget(self); - fd + ManuallyDrop::new(self).fd } pub fn read(&self, buf: &mut [u8]) -> io::Result { @@ -70,9 +68,7 @@ impl AsInner for FileDesc { impl IntoInner for FileDesc { fn into_inner(self) -> Fd { - let fd = self.fd; - mem::forget(self); - fd + ManuallyDrop::new(self).fd } } diff --git a/std/src/sys/pal/sgx/net.rs b/std/src/sys/pal/sgx/net.rs index 68a2d5eded2da..f2e751c51194d 100644 --- a/std/src/sys/pal/sgx/net.rs +++ b/std/src/sys/pal/sgx/net.rs @@ -1,13 +1,11 @@ -use crate::error; -use crate::fmt; +use super::abi::usercalls; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, ToSocketAddrs}; use crate::sync::Arc; use crate::sys::fd::FileDesc; use crate::sys::{sgx_ineffective, unsupported, AsInner, FromInner, IntoInner, TryIntoInner}; use crate::time::Duration; - -use super::abi::usercalls; +use crate::{error, fmt}; const DEFAULT_FAKE_TTL: u32 = 64; diff --git a/std/src/sys/pal/sgx/os.rs b/std/src/sys/pal/sgx/os.rs index c021300d4ae33..46af710aa396c 100644 --- a/std/src/sys/pal/sgx/os.rs +++ b/std/src/sys/pal/sgx/os.rs @@ -3,16 +3,12 @@ use fortanix_sgx_abi::{Error, RESULT_SUCCESS}; use crate::collections::HashMap; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::path::{self, PathBuf}; -use crate::str; use crate::sync::atomic::{AtomicUsize, Ordering}; -use crate::sync::Mutex; -use crate::sync::Once; +use crate::sync::{Mutex, Once}; use crate::sys::{decode_error_kind, sgx_ineffective, unsupported}; -use crate::vec; +use crate::{fmt, io, str, vec}; pub fn errno() -> i32 { RESULT_SUCCESS diff --git a/std/src/sys/pal/sgx/thread.rs b/std/src/sys/pal/sgx/thread.rs index 446cdd18b7e42..cecd53c352c5a 100644 --- a/std/src/sys/pal/sgx/thread.rs +++ b/std/src/sys/pal/sgx/thread.rs @@ -1,12 +1,12 @@ #![cfg_attr(test, allow(dead_code))] // why is this necessary? + +use super::abi::usercalls; use super::unsupported; use crate::ffi::CStr; use crate::io; use crate::num::NonZero; use crate::time::Duration; -use super::abi::usercalls; - pub struct Thread(task_queue::JoinHandle); pub const DEFAULT_MIN_STACK_SIZE: usize = 4096; diff --git a/std/src/sys/pal/sgx/thread_parking.rs b/std/src/sys/pal/sgx/thread_parking.rs index 0006cd4f1be25..660624ea9c3b8 100644 --- a/std/src/sys/pal/sgx/thread_parking.rs +++ b/std/src/sys/pal/sgx/thread_parking.rs @@ -1,7 +1,8 @@ +use fortanix_sgx_abi::{EV_UNPARK, WAIT_INDEFINITE}; + use super::abi::usercalls; use crate::io::ErrorKind; use crate::time::Duration; -use fortanix_sgx_abi::{EV_UNPARK, WAIT_INDEFINITE}; pub type ThreadId = fortanix_sgx_abi::Tcs; diff --git a/std/src/sys/pal/sgx/waitqueue/mod.rs b/std/src/sys/pal/sgx/waitqueue/mod.rs index f5668a9493fb5..bd114523fe80b 100644 --- a/std/src/sys/pal/sgx/waitqueue/mod.rs +++ b/std/src/sys/pal/sgx/waitqueue/mod.rs @@ -16,17 +16,15 @@ mod tests; mod spin_mutex; mod unsafe_list; -use crate::num::NonZero; -use crate::ops::{Deref, DerefMut}; -use crate::panic::{self, AssertUnwindSafe}; -use crate::time::Duration; - -use super::abi::thread; -use super::abi::usercalls; use fortanix_sgx_abi::{Tcs, EV_UNPARK, WAIT_INDEFINITE}; pub use self::spin_mutex::{try_lock_or_false, SpinMutex, SpinMutexGuard}; use self::unsafe_list::{UnsafeList, UnsafeListEntry}; +use super::abi::{thread, usercalls}; +use crate::num::NonZero; +use crate::ops::{Deref, DerefMut}; +use crate::panic::{self, AssertUnwindSafe}; +use crate::time::Duration; /// An queue entry in a `WaitQueue`. struct WaitEntry { diff --git a/std/src/sys/pal/solid/abi/fs.rs b/std/src/sys/pal/solid/abi/fs.rs index 75efaaac2a948..394be15b0064b 100644 --- a/std/src/sys/pal/solid/abi/fs.rs +++ b/std/src/sys/pal/solid/abi/fs.rs @@ -1,11 +1,12 @@ //! `solid_fs.h` -use crate::os::raw::{c_char, c_int, c_uchar}; pub use libc::{ ino_t, off_t, stat, time_t, O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, SEEK_CUR, SEEK_END, SEEK_SET, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFMT, S_IFREG, S_IWRITE, }; +use crate::os::raw::{c_char, c_int, c_uchar}; + pub const O_ACCMODE: c_int = 0x3; pub const SOLID_MAX_PATH: usize = 256; diff --git a/std/src/sys/pal/solid/abi/mod.rs b/std/src/sys/pal/solid/abi/mod.rs index 8440d572cfbd3..62cd86236bbd3 100644 --- a/std/src/sys/pal/solid/abi/mod.rs +++ b/std/src/sys/pal/solid/abi/mod.rs @@ -3,7 +3,6 @@ use crate::os::raw::c_int; mod fs; pub mod sockets; pub use self::fs::*; - // `solid_types.h` pub use super::itron::abi::{ER, ER_ID, E_TMOUT, ID}; diff --git a/std/src/sys/pal/solid/abi/sockets.rs b/std/src/sys/pal/solid/abi/sockets.rs index 11c430360ce88..3c9e3f9ffb95d 100644 --- a/std/src/sys/pal/solid/abi/sockets.rs +++ b/std/src/sys/pal/solid/abi/sockets.rs @@ -1,6 +1,7 @@ -use crate::os::raw::{c_char, c_uint, c_void}; pub use libc::{c_int, c_long, size_t, ssize_t, timeval}; +use crate::os::raw::{c_char, c_uint, c_void}; + pub const SOLID_NET_ERR_BASE: c_int = -2000; pub const EINPROGRESS: c_int = SOLID_NET_ERR_BASE - libc::EINPROGRESS; diff --git a/std/src/sys/pal/solid/alloc.rs b/std/src/sys/pal/solid/alloc.rs index d013bd8761003..4cf60ac9b2e23 100644 --- a/std/src/sys/pal/solid/alloc.rs +++ b/std/src/sys/pal/solid/alloc.rs @@ -1,7 +1,5 @@ -use crate::{ - alloc::{GlobalAlloc, Layout, System}, - sys::common::alloc::{realloc_fallback, MIN_ALIGN}, -}; +use crate::alloc::{GlobalAlloc, Layout, System}; +use crate::sys::common::alloc::{realloc_fallback, MIN_ALIGN}; #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { diff --git a/std/src/sys/pal/solid/error.rs b/std/src/sys/pal/solid/error.rs index 547b4f3a9840e..66c4d8a0ea27a 100644 --- a/std/src/sys/pal/solid/error.rs +++ b/std/src/sys/pal/solid/error.rs @@ -1,8 +1,7 @@ +pub use self::itron::error::{expect_success, ItronError as SolidError}; use super::{abi, itron, net}; use crate::io::ErrorKind; -pub use self::itron::error::{expect_success, ItronError as SolidError}; - /// Describe the specified SOLID error code. Returns `None` if it's an /// undefined error code. /// diff --git a/std/src/sys/pal/solid/fs.rs b/std/src/sys/pal/solid/fs.rs index dc83e4f4b4999..8179ec8821a38 100644 --- a/std/src/sys/pal/solid/fs.rs +++ b/std/src/sys/pal/solid/fs.rs @@ -1,17 +1,14 @@ use super::{abi, error}; -use crate::{ - ffi::{CStr, CString, OsStr, OsString}, - fmt, - io::{self, BorrowedCursor, IoSlice, IoSliceMut, SeekFrom}, - mem::MaybeUninit, - os::raw::{c_int, c_short}, - os::solid::ffi::OsStrExt, - path::{Path, PathBuf}, - sync::Arc, - sys::time::SystemTime, - sys::unsupported, -}; - +use crate::ffi::{CStr, CString, OsStr, OsString}; +use crate::fmt; +use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, SeekFrom}; +use crate::mem::MaybeUninit; +use crate::os::raw::{c_int, c_short}; +use crate::os::solid::ffi::OsStrExt; +use crate::path::{Path, PathBuf}; +use crate::sync::Arc; +use crate::sys::time::SystemTime; +use crate::sys::unsupported; pub use crate::sys_common::fs::exists; /// A file descriptor. diff --git a/std/src/sys/pal/solid/io.rs b/std/src/sys/pal/solid/io.rs index a862bb7870264..4b1f788a492c5 100644 --- a/std/src/sys/pal/solid/io.rs +++ b/std/src/sys/pal/solid/io.rs @@ -1,8 +1,8 @@ -use crate::marker::PhantomData; -use crate::slice; +use libc::c_void; use super::abi::sockets::iovec; -use libc::c_void; +use crate::marker::PhantomData; +use crate::slice; #[derive(Copy, Clone)] #[repr(transparent)] diff --git a/std/src/sys/pal/solid/mod.rs b/std/src/sys/pal/solid/mod.rs index 9a7741ddda71e..cbf34286878fe 100644 --- a/std/src/sys/pal/solid/mod.rs +++ b/std/src/sys/pal/solid/mod.rs @@ -1,6 +1,6 @@ #![allow(dead_code)] #![allow(missing_docs, nonstandard_style)] -#![deny(unsafe_op_in_unsafe_fn)] +#![forbid(unsafe_op_in_unsafe_fn)] pub mod abi; @@ -32,8 +32,7 @@ pub mod pipe; #[path = "../unsupported/process.rs"] pub mod process; pub mod stdio; -pub use self::itron::thread; -pub use self::itron::thread_parking; +pub use self::itron::{thread, thread_parking}; pub mod time; // SAFETY: must be called only once during runtime initialization. diff --git a/std/src/sys/pal/solid/net.rs b/std/src/sys/pal/solid/net.rs index 5bd339849e9dc..b6a31395095d9 100644 --- a/std/src/sys/pal/solid/net.rs +++ b/std/src/sys/pal/solid/net.rs @@ -1,19 +1,15 @@ -use super::abi; -use crate::{ - cmp, - ffi::CStr, - io::{self, BorrowedBuf, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}, - mem, - net::{Shutdown, SocketAddr}, - os::solid::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}, - ptr, str, - sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr}, - sys_common::{FromInner, IntoInner}, - time::Duration, -}; +use libc::{c_int, c_void, size_t}; use self::netc::{sockaddr, socklen_t, MSG_PEEK}; -use libc::{c_int, c_void, size_t}; +use super::abi; +use crate::ffi::CStr; +use crate::io::{self, BorrowedBuf, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}; +use crate::net::{Shutdown, SocketAddr}; +use crate::os::solid::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}; +use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr}; +use crate::sys_common::{FromInner, IntoInner}; +use crate::time::Duration; +use crate::{cmp, mem, ptr, str}; pub mod netc { pub use super::super::abi::sockets::*; diff --git a/std/src/sys/pal/solid/os.rs b/std/src/sys/pal/solid/os.rs index ac90aae4ebe46..d8afcb91f67f2 100644 --- a/std/src/sys/pal/solid/os.rs +++ b/std/src/sys/pal/solid/os.rs @@ -1,20 +1,14 @@ -use super::unsupported; +use core::slice::memchr; + +use super::{error, itron, unsupported}; use crate::error::Error as StdError; use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; -use crate::io; -use crate::os::{ - raw::{c_char, c_int}, - solid::ffi::{OsStrExt, OsStringExt}, -}; +use crate::os::raw::{c_char, c_int}; +use crate::os::solid::ffi::{OsStrExt, OsStringExt}; use crate::path::{self, PathBuf}; use crate::sync::{PoisonError, RwLock}; use crate::sys::common::small_c_string::run_with_cstr; -use crate::vec; - -use super::{error, itron}; - -use core::slice::memchr; +use crate::{fmt, io, vec}; // `solid` directly maps `errno`s to μITRON error codes. impl itron::error::ItronError { diff --git a/std/src/sys/pal/solid/time.rs b/std/src/sys/pal/solid/time.rs index f83f1644fe854..3f9bbb0b63cdb 100644 --- a/std/src/sys/pal/solid/time.rs +++ b/std/src/sys/pal/solid/time.rs @@ -1,7 +1,8 @@ -use super::{abi, error::expect_success}; -use crate::{mem::MaybeUninit, time::Duration}; - +use super::abi; +use super::error::expect_success; pub use super::itron::time::Instant; +use crate::mem::MaybeUninit; +use crate::time::Duration; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub struct SystemTime(abi::time_t); diff --git a/std/src/sys/pal/teeos/os.rs b/std/src/sys/pal/teeos/os.rs index 3be0846a6dd4d..82cade771b513 100644 --- a/std/src/sys/pal/teeos/os.rs +++ b/std/src/sys/pal/teeos/os.rs @@ -2,14 +2,11 @@ use core::marker::PhantomData; +use super::unsupported; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; -use crate::path; use crate::path::PathBuf; - -use super::unsupported; +use crate::{fmt, io, path}; pub fn errno() -> i32 { unsafe { (*libc::__errno_location()) as i32 } diff --git a/std/src/sys/pal/teeos/stdio.rs b/std/src/sys/pal/teeos/stdio.rs index 9ca04f2927323..67e251812da7f 100644 --- a/std/src/sys/pal/teeos/stdio.rs +++ b/std/src/sys/pal/teeos/stdio.rs @@ -1,8 +1,9 @@ #![deny(unsafe_op_in_unsafe_fn)] -use crate::io; use core::arch::asm; +use crate::io; + pub struct Stdin; pub struct Stdout; pub struct Stderr; diff --git a/std/src/sys/pal/teeos/thread.rs b/std/src/sys/pal/teeos/thread.rs index 7a27d749f1c9c..15c65240ddd2a 100644 --- a/std/src/sys/pal/teeos/thread.rs +++ b/std/src/sys/pal/teeos/thread.rs @@ -1,13 +1,9 @@ -use core::convert::TryInto; - -use crate::cmp; use crate::ffi::CStr; -use crate::io; -use crate::mem; +use crate::mem::{self, ManuallyDrop}; use crate::num::NonZero; -use crate::ptr; use crate::sys::os; use crate::time::Duration; +use crate::{cmp, io, ptr}; pub const DEFAULT_MIN_STACK_SIZE: usize = 8 * 1024; @@ -115,11 +111,9 @@ impl Thread { /// must join, because no pthread_detach supported pub fn join(self) { - unsafe { - let ret = libc::pthread_join(self.id, ptr::null_mut()); - mem::forget(self); - assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret)); - } + let id = self.into_id(); + let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) }; + assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret)); } pub fn id(&self) -> libc::pthread_t { @@ -127,9 +121,7 @@ impl Thread { } pub fn into_id(self) -> libc::pthread_t { - let id = self.id; - mem::forget(self); - id + ManuallyDrop::new(self).id } } diff --git a/std/src/sys/pal/uefi/args.rs b/std/src/sys/pal/uefi/args.rs index 18a69afa7d91b..bdf6f5a0c1c34 100644 --- a/std/src/sys/pal/uefi/args.rs +++ b/std/src/sys/pal/uefi/args.rs @@ -3,10 +3,9 @@ use r_efi::protocols::loaded_image; use super::helpers; use crate::env::current_exe; use crate::ffi::OsString; -use crate::fmt; use crate::iter::Iterator; use crate::mem::size_of; -use crate::vec; +use crate::{fmt, vec}; pub struct Args { parsed_args_list: vec::IntoIter, @@ -76,7 +75,7 @@ impl DoubleEndedIterator for Args { /// This implementation is based on what is defined in Section 3.4 of /// [UEFI Shell Specification](https://uefi.org/sites/default/files/resources/UEFI_Shell_Spec_2_0.pdf) /// -/// Return None in the following cases: +/// Returns None in the following cases: /// - Invalid UTF-16 (unpaired surrogate) /// - Empty/improper arguments fn parse_lp_cmd_line(code_units: &[u16]) -> Option> { diff --git a/std/src/sys/pal/uefi/helpers.rs b/std/src/sys/pal/uefi/helpers.rs index 23aa4da14a763..4031d33ba8066 100644 --- a/std/src/sys/pal/uefi/helpers.rs +++ b/std/src/sys/pal/uefi/helpers.rs @@ -12,20 +12,29 @@ use r_efi::efi::{self, Guid}; use r_efi::protocols::{device_path, device_path_to_text}; -use crate::ffi::OsString; +use crate::ffi::{OsStr, OsString}; use crate::io::{self, const_io_error}; use crate::mem::{size_of, MaybeUninit}; -use crate::os::uefi::{self, env::boot_services, ffi::OsStringExt}; +use crate::os::uefi::env::boot_services; +use crate::os::uefi::ffi::{OsStrExt, OsStringExt}; +use crate::os::uefi::{self}; use crate::ptr::NonNull; use crate::slice; use crate::sync::atomic::{AtomicPtr, Ordering}; use crate::sys_common::wstr::WStrUnits; +type BootInstallMultipleProtocolInterfaces = + unsafe extern "efiapi" fn(_: *mut r_efi::efi::Handle, _: ...) -> r_efi::efi::Status; + +type BootUninstallMultipleProtocolInterfaces = + unsafe extern "efiapi" fn(_: r_efi::efi::Handle, _: ...) -> r_efi::efi::Status; + const BOOT_SERVICES_UNAVAILABLE: io::Error = const_io_error!(io::ErrorKind::Other, "Boot Services are no longer available"); -/// Locate Handles with a particular Protocol GUID -/// Implemented using `EFI_BOOT_SERVICES.LocateHandles()` +/// Locates Handles with a particular Protocol GUID. +/// +/// Implemented using `EFI_BOOT_SERVICES.LocateHandles()`. /// /// Returns an array of [Handles](r_efi::efi::Handle) that support a specified protocol. pub(crate) fn locate_handles(mut guid: Guid) -> io::Result>> { @@ -142,8 +151,9 @@ pub(crate) unsafe fn close_event(evt: NonNull) -> io::Result if r.is_error() { Err(crate::io::Error::from_raw_os_error(r.as_usize())) } else { Ok(()) } } -/// Get the Protocol for current system handle. -/// Note: Some protocols need to be manually freed. It is the callers responsibility to do so. +/// Gets the Protocol for current system handle. +/// +/// Note: Some protocols need to be manually freed. It is the caller's responsibility to do so. pub(crate) fn image_handle_protocol(protocol_guid: Guid) -> io::Result> { let system_handle = uefi::env::try_image_handle().ok_or(io::const_io_error!( io::ErrorKind::NotFound, @@ -214,10 +224,199 @@ pub(crate) fn device_path_to_text(path: NonNull) -> io::R Err(io::const_io_error!(io::ErrorKind::NotFound, "No device path to text protocol found")) } -/// Get RuntimeServices +/// Gets RuntimeServices. pub(crate) fn runtime_services() -> Option> { let system_table: NonNull = crate::os::uefi::env::try_system_table()?.cast(); let runtime_services = unsafe { (*system_table.as_ptr()).runtime_services }; NonNull::new(runtime_services) } + +pub(crate) struct DevicePath(NonNull); + +impl DevicePath { + pub(crate) fn from_text(p: &OsStr) -> io::Result { + fn inner( + p: &OsStr, + protocol: NonNull, + ) -> io::Result { + let path_vec = p.encode_wide().chain(Some(0)).collect::>(); + if path_vec[..path_vec.len() - 1].contains(&0) { + return Err(const_io_error!( + io::ErrorKind::InvalidInput, + "strings passed to UEFI cannot contain NULs", + )); + } + + let path = + unsafe { ((*protocol.as_ptr()).convert_text_to_device_path)(path_vec.as_ptr()) }; + + NonNull::new(path).map(DevicePath).ok_or_else(|| { + const_io_error!(io::ErrorKind::InvalidFilename, "Invalid Device Path") + }) + } + + static LAST_VALID_HANDLE: AtomicPtr = + AtomicPtr::new(crate::ptr::null_mut()); + + if let Some(handle) = NonNull::new(LAST_VALID_HANDLE.load(Ordering::Acquire)) { + if let Ok(protocol) = open_protocol::( + handle, + r_efi::protocols::device_path_from_text::PROTOCOL_GUID, + ) { + return inner(p, protocol); + } + } + + let handles = locate_handles(r_efi::protocols::device_path_from_text::PROTOCOL_GUID)?; + for handle in handles { + if let Ok(protocol) = open_protocol::( + handle, + r_efi::protocols::device_path_from_text::PROTOCOL_GUID, + ) { + LAST_VALID_HANDLE.store(handle.as_ptr(), Ordering::Release); + return inner(p, protocol); + } + } + + io::Result::Err(const_io_error!( + io::ErrorKind::NotFound, + "DevicePathFromText Protocol not found" + )) + } + + pub(crate) fn as_ptr(&self) -> *mut r_efi::protocols::device_path::Protocol { + self.0.as_ptr() + } +} + +impl Drop for DevicePath { + fn drop(&mut self) { + if let Some(bt) = boot_services() { + let bt: NonNull = bt.cast(); + unsafe { + ((*bt.as_ptr()).free_pool)(self.0.as_ptr() as *mut crate::ffi::c_void); + } + } + } +} + +pub(crate) struct OwnedProtocol { + guid: r_efi::efi::Guid, + handle: NonNull, + protocol: *mut T, +} + +impl OwnedProtocol { + // FIXME: Consider using unsafe trait for matching protocol with guid + pub(crate) unsafe fn create(protocol: T, mut guid: r_efi::efi::Guid) -> io::Result { + let bt: NonNull = + boot_services().ok_or(BOOT_SERVICES_UNAVAILABLE)?.cast(); + let protocol: *mut T = Box::into_raw(Box::new(protocol)); + let mut handle: r_efi::efi::Handle = crate::ptr::null_mut(); + + // FIXME: Move into r-efi once extended_varargs_abi_support is stablized + let func: BootInstallMultipleProtocolInterfaces = + unsafe { crate::mem::transmute((*bt.as_ptr()).install_multiple_protocol_interfaces) }; + + let r = unsafe { + func( + &mut handle, + &mut guid as *mut _ as *mut crate::ffi::c_void, + protocol as *mut crate::ffi::c_void, + crate::ptr::null_mut() as *mut crate::ffi::c_void, + ) + }; + + if r.is_error() { + drop(unsafe { Box::from_raw(protocol) }); + return Err(crate::io::Error::from_raw_os_error(r.as_usize())); + }; + + let handle = NonNull::new(handle) + .ok_or(io::const_io_error!(io::ErrorKind::Uncategorized, "found null handle"))?; + + Ok(Self { guid, handle, protocol }) + } + + pub(crate) fn handle(&self) -> NonNull { + self.handle + } +} + +impl Drop for OwnedProtocol { + fn drop(&mut self) { + // Do not deallocate a runtime protocol + if let Some(bt) = boot_services() { + let bt: NonNull = bt.cast(); + // FIXME: Move into r-efi once extended_varargs_abi_support is stablized + let func: BootUninstallMultipleProtocolInterfaces = unsafe { + crate::mem::transmute((*bt.as_ptr()).uninstall_multiple_protocol_interfaces) + }; + let status = unsafe { + func( + self.handle.as_ptr(), + &mut self.guid as *mut _ as *mut crate::ffi::c_void, + self.protocol as *mut crate::ffi::c_void, + crate::ptr::null_mut() as *mut crate::ffi::c_void, + ) + }; + + // Leak the protocol in case uninstall fails + if status == r_efi::efi::Status::SUCCESS { + let _ = unsafe { Box::from_raw(self.protocol) }; + } + } + } +} + +impl AsRef for OwnedProtocol { + fn as_ref(&self) -> &T { + unsafe { self.protocol.as_ref().unwrap() } + } +} + +pub(crate) struct OwnedTable { + layout: crate::alloc::Layout, + ptr: *mut T, +} + +impl OwnedTable { + pub(crate) fn from_table_header(hdr: &r_efi::efi::TableHeader) -> Self { + let header_size = hdr.header_size as usize; + let layout = crate::alloc::Layout::from_size_align(header_size, 8).unwrap(); + let ptr = unsafe { crate::alloc::alloc(layout) as *mut T }; + Self { layout, ptr } + } + + pub(crate) const fn as_ptr(&self) -> *const T { + self.ptr + } + + pub(crate) const fn as_mut_ptr(&self) -> *mut T { + self.ptr + } +} + +impl OwnedTable { + pub(crate) fn from_table(tbl: *const r_efi::efi::SystemTable) -> Self { + let hdr = unsafe { (*tbl).hdr }; + + let owned_tbl = Self::from_table_header(&hdr); + unsafe { + crate::ptr::copy_nonoverlapping( + tbl as *const u8, + owned_tbl.as_mut_ptr() as *mut u8, + hdr.header_size as usize, + ) + }; + + owned_tbl + } +} + +impl Drop for OwnedTable { + fn drop(&mut self) { + unsafe { crate::alloc::dealloc(self.ptr as *mut u8, self.layout) }; + } +} diff --git a/std/src/sys/pal/uefi/mod.rs b/std/src/sys/pal/uefi/mod.rs index 4d50d9e8c3d9c..851bcea4c1e43 100644 --- a/std/src/sys/pal/uefi/mod.rs +++ b/std/src/sys/pal/uefi/mod.rs @@ -25,7 +25,6 @@ pub mod net; pub mod os; #[path = "../unsupported/pipe.rs"] pub mod pipe; -#[path = "../unsupported/process.rs"] pub mod process; pub mod stdio; pub mod thread; @@ -102,9 +101,10 @@ pub const fn unsupported_err() -> std_io::Error { } pub fn decode_error_kind(code: RawOsError) -> crate::io::ErrorKind { - use crate::io::ErrorKind; use r_efi::efi::Status; + use crate::io::ErrorKind; + match r_efi::efi::Status::from_usize(code) { Status::ALREADY_STARTED | Status::COMPROMISED_DATA diff --git a/std/src/sys/pal/uefi/os.rs b/std/src/sys/pal/uefi/os.rs index 0b27977df2fde..4d2d7264704b2 100644 --- a/std/src/sys/pal/uefi/os.rs +++ b/std/src/sys/pal/uefi/os.rs @@ -1,14 +1,14 @@ +use r_efi::efi::protocols::{device_path, loaded_image_device_path}; +use r_efi::efi::Status; + use super::{helpers, unsupported, RawOsError}; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::os::uefi; use crate::path::{self, PathBuf}; use crate::ptr::NonNull; -use r_efi::efi::protocols::{device_path, loaded_image_device_path}; -use r_efi::efi::Status; +use crate::{fmt, io}; pub fn errno() -> RawOsError { 0 diff --git a/std/src/sys/pal/uefi/process.rs b/std/src/sys/pal/uefi/process.rs new file mode 100644 index 0000000000000..fdc5f5d7e4fea --- /dev/null +++ b/std/src/sys/pal/uefi/process.rs @@ -0,0 +1,684 @@ +use r_efi::protocols::simple_text_output; + +use super::helpers; +pub use crate::ffi::OsString as EnvKey; +use crate::ffi::{OsStr, OsString}; +use crate::num::{NonZero, NonZeroI32}; +use crate::path::Path; +use crate::sys::fs::File; +use crate::sys::pipe::AnonPipe; +use crate::sys::unsupported; +use crate::sys_common::process::{CommandEnv, CommandEnvs}; +use crate::{fmt, io}; + +//////////////////////////////////////////////////////////////////////////////// +// Command +//////////////////////////////////////////////////////////////////////////////// + +#[derive(Debug)] +pub struct Command { + prog: OsString, + stdout: Option, + stderr: Option, +} + +// passed back to std::process with the pipes connected to the child, if any +// were requested +pub struct StdioPipes { + pub stdin: Option, + pub stdout: Option, + pub stderr: Option, +} + +#[derive(Copy, Clone, Debug)] +pub enum Stdio { + Inherit, + Null, + MakePipe, +} + +impl Command { + pub fn new(program: &OsStr) -> Command { + Command { prog: program.to_os_string(), stdout: None, stderr: None } + } + + // FIXME: Implement arguments as reverse of parsing algorithm + pub fn arg(&mut self, _arg: &OsStr) { + panic!("unsupported") + } + + pub fn env_mut(&mut self) -> &mut CommandEnv { + panic!("unsupported") + } + + pub fn cwd(&mut self, _dir: &OsStr) { + panic!("unsupported") + } + + pub fn stdin(&mut self, _stdin: Stdio) { + panic!("unsupported") + } + + pub fn stdout(&mut self, stdout: Stdio) { + self.stdout = Some(stdout); + } + + pub fn stderr(&mut self, stderr: Stdio) { + self.stderr = Some(stderr); + } + + pub fn get_program(&self) -> &OsStr { + self.prog.as_ref() + } + + pub fn get_args(&self) -> CommandArgs<'_> { + panic!("unsupported") + } + + pub fn get_envs(&self) -> CommandEnvs<'_> { + panic!("unsupported") + } + + pub fn get_current_dir(&self) -> Option<&Path> { + None + } + + pub fn spawn( + &mut self, + _default: Stdio, + _needs_stdin: bool, + ) -> io::Result<(Process, StdioPipes)> { + unsupported() + } + + fn create_pipe( + s: Stdio, + ) -> io::Result>> { + match s { + Stdio::MakePipe => unsafe { + helpers::OwnedProtocol::create( + uefi_command_internal::PipeProtocol::new(), + simple_text_output::PROTOCOL_GUID, + ) + } + .map(Some), + Stdio::Null => unsafe { + helpers::OwnedProtocol::create( + uefi_command_internal::PipeProtocol::null(), + simple_text_output::PROTOCOL_GUID, + ) + } + .map(Some), + Stdio::Inherit => Ok(None), + } + } + + pub fn output(&mut self) -> io::Result<(ExitStatus, Vec, Vec)> { + let mut cmd = uefi_command_internal::Image::load_image(&self.prog)?; + + // Setup Stdout + let stdout = self.stdout.unwrap_or(Stdio::MakePipe); + let stdout = Self::create_pipe(stdout)?; + if let Some(con) = stdout { + cmd.stdout_init(con) + } else { + cmd.stdout_inherit() + }; + + // Setup Stderr + let stderr = self.stderr.unwrap_or(Stdio::MakePipe); + let stderr = Self::create_pipe(stderr)?; + if let Some(con) = stderr { + cmd.stderr_init(con) + } else { + cmd.stderr_inherit() + }; + + let stat = cmd.start_image()?; + + let stdout = cmd.stdout()?; + let stderr = cmd.stderr()?; + + Ok((ExitStatus(stat), stdout, stderr)) + } +} + +impl From for Stdio { + fn from(pipe: AnonPipe) -> Stdio { + pipe.diverge() + } +} + +impl From for Stdio { + fn from(_: io::Stdout) -> Stdio { + // FIXME: This is wrong. + // Instead, the Stdio we have here should be a unit struct. + panic!("unsupported") + } +} + +impl From for Stdio { + fn from(_: io::Stderr) -> Stdio { + // FIXME: This is wrong. + // Instead, the Stdio we have here should be a unit struct. + panic!("unsupported") + } +} + +impl From for Stdio { + fn from(_file: File) -> Stdio { + // FIXME: This is wrong. + // Instead, the Stdio we have here should be a unit struct. + panic!("unsupported") + } +} + +#[derive(PartialEq, Eq, Clone, Copy, Debug)] +#[non_exhaustive] +pub struct ExitStatus(r_efi::efi::Status); + +impl ExitStatus { + pub fn exit_ok(&self) -> Result<(), ExitStatusError> { + if self.0 == r_efi::efi::Status::SUCCESS { Ok(()) } else { Err(ExitStatusError(self.0)) } + } + + pub fn code(&self) -> Option { + Some(self.0.as_usize() as i32) + } +} + +impl fmt::Display for ExitStatus { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let err_str = super::os::error_string(self.0.as_usize()); + write!(f, "{}", err_str) + } +} + +impl Default for ExitStatus { + fn default() -> Self { + ExitStatus(r_efi::efi::Status::SUCCESS) + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct ExitStatusError(r_efi::efi::Status); + +impl fmt::Debug for ExitStatusError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let err_str = super::os::error_string(self.0.as_usize()); + write!(f, "{}", err_str) + } +} + +impl Into for ExitStatusError { + fn into(self) -> ExitStatus { + ExitStatus(self.0) + } +} + +impl ExitStatusError { + pub fn code(self) -> Option> { + NonZeroI32::new(self.0.as_usize() as i32) + } +} + +#[derive(PartialEq, Eq, Clone, Copy, Debug)] +pub struct ExitCode(bool); + +impl ExitCode { + pub const SUCCESS: ExitCode = ExitCode(false); + pub const FAILURE: ExitCode = ExitCode(true); + + pub fn as_i32(&self) -> i32 { + self.0 as i32 + } +} + +impl From for ExitCode { + fn from(code: u8) -> Self { + match code { + 0 => Self::SUCCESS, + 1..=255 => Self::FAILURE, + } + } +} + +pub struct Process(!); + +impl Process { + pub fn id(&self) -> u32 { + self.0 + } + + pub fn kill(&mut self) -> io::Result<()> { + self.0 + } + + pub fn wait(&mut self) -> io::Result { + self.0 + } + + pub fn try_wait(&mut self) -> io::Result> { + self.0 + } +} + +pub struct CommandArgs<'a> { + iter: crate::slice::Iter<'a, OsString>, +} + +impl<'a> Iterator for CommandArgs<'a> { + type Item = &'a OsStr; + + fn next(&mut self) -> Option<&'a OsStr> { + self.iter.next().map(|x| x.as_ref()) + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a> ExactSizeIterator for CommandArgs<'a> { + fn len(&self) -> usize { + self.iter.len() + } + + fn is_empty(&self) -> bool { + self.iter.is_empty() + } +} + +impl<'a> fmt::Debug for CommandArgs<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter.clone()).finish() + } +} + +#[allow(dead_code)] +mod uefi_command_internal { + use r_efi::protocols::{loaded_image, simple_text_output}; + + use super::super::helpers; + use crate::ffi::{OsStr, OsString}; + use crate::io::{self, const_io_error}; + use crate::mem::MaybeUninit; + use crate::os::uefi::env::{boot_services, image_handle, system_table}; + use crate::os::uefi::ffi::{OsStrExt, OsStringExt}; + use crate::ptr::NonNull; + use crate::slice; + use crate::sys::pal::uefi::helpers::OwnedTable; + use crate::sys_common::wstr::WStrUnits; + + pub struct Image { + handle: NonNull, + stdout: Option>, + stderr: Option>, + st: OwnedTable, + args: Option>, + } + + impl Image { + pub fn load_image(p: &OsStr) -> io::Result { + let path = helpers::DevicePath::from_text(p)?; + let boot_services: NonNull = boot_services() + .ok_or_else(|| const_io_error!(io::ErrorKind::NotFound, "Boot Services not found"))? + .cast(); + let mut child_handle: MaybeUninit = MaybeUninit::uninit(); + let image_handle = image_handle(); + + let r = unsafe { + ((*boot_services.as_ptr()).load_image)( + r_efi::efi::Boolean::FALSE, + image_handle.as_ptr(), + path.as_ptr(), + crate::ptr::null_mut(), + 0, + child_handle.as_mut_ptr(), + ) + }; + + if r.is_error() { + Err(io::Error::from_raw_os_error(r.as_usize())) + } else { + let child_handle = unsafe { child_handle.assume_init() }; + let child_handle = NonNull::new(child_handle).unwrap(); + + let loaded_image: NonNull = + helpers::open_protocol(child_handle, loaded_image::PROTOCOL_GUID).unwrap(); + let st = OwnedTable::from_table(unsafe { (*loaded_image.as_ptr()).system_table }); + + Ok(Self { handle: child_handle, stdout: None, stderr: None, st, args: None }) + } + } + + pub fn start_image(&mut self) -> io::Result { + self.update_st_crc32()?; + + // Use our system table instead of the default one + let loaded_image: NonNull = + helpers::open_protocol(self.handle, loaded_image::PROTOCOL_GUID).unwrap(); + unsafe { + (*loaded_image.as_ptr()).system_table = self.st.as_mut_ptr(); + } + + let boot_services: NonNull = boot_services() + .ok_or_else(|| const_io_error!(io::ErrorKind::NotFound, "Boot Services not found"))? + .cast(); + let mut exit_data_size: usize = 0; + let mut exit_data: MaybeUninit<*mut u16> = MaybeUninit::uninit(); + + let r = unsafe { + ((*boot_services.as_ptr()).start_image)( + self.handle.as_ptr(), + &mut exit_data_size, + exit_data.as_mut_ptr(), + ) + }; + + // Drop exitdata + if exit_data_size != 0 { + unsafe { + let exit_data = exit_data.assume_init(); + ((*boot_services.as_ptr()).free_pool)(exit_data as *mut crate::ffi::c_void); + } + } + + Ok(r) + } + + fn set_stdout( + &mut self, + handle: r_efi::efi::Handle, + protocol: *mut simple_text_output::Protocol, + ) { + unsafe { + (*self.st.as_mut_ptr()).console_out_handle = handle; + (*self.st.as_mut_ptr()).con_out = protocol; + } + } + + fn set_stderr( + &mut self, + handle: r_efi::efi::Handle, + protocol: *mut simple_text_output::Protocol, + ) { + unsafe { + (*self.st.as_mut_ptr()).standard_error_handle = handle; + (*self.st.as_mut_ptr()).std_err = protocol; + } + } + + pub fn stdout_init(&mut self, protocol: helpers::OwnedProtocol) { + self.set_stdout( + protocol.handle().as_ptr(), + protocol.as_ref() as *const PipeProtocol as *mut simple_text_output::Protocol, + ); + self.stdout = Some(protocol); + } + + pub fn stdout_inherit(&mut self) { + let st: NonNull = system_table().cast(); + unsafe { self.set_stdout((*st.as_ptr()).console_out_handle, (*st.as_ptr()).con_out) } + } + + pub fn stderr_init(&mut self, protocol: helpers::OwnedProtocol) { + self.set_stderr( + protocol.handle().as_ptr(), + protocol.as_ref() as *const PipeProtocol as *mut simple_text_output::Protocol, + ); + self.stderr = Some(protocol); + } + + pub fn stderr_inherit(&mut self) { + let st: NonNull = system_table().cast(); + unsafe { self.set_stderr((*st.as_ptr()).standard_error_handle, (*st.as_ptr()).std_err) } + } + + pub fn stderr(&self) -> io::Result> { + match &self.stderr { + Some(stderr) => stderr.as_ref().utf8(), + None => Ok(Vec::new()), + } + } + + pub fn stdout(&self) -> io::Result> { + match &self.stdout { + Some(stdout) => stdout.as_ref().utf8(), + None => Ok(Vec::new()), + } + } + + pub fn set_args(&mut self, args: &OsStr) { + let loaded_image: NonNull = + helpers::open_protocol(self.handle, loaded_image::PROTOCOL_GUID).unwrap(); + + let mut args = args.encode_wide().collect::>(); + let args_size = (crate::mem::size_of::() * args.len()) as u32; + + unsafe { + (*loaded_image.as_ptr()).load_options = + args.as_mut_ptr() as *mut crate::ffi::c_void; + (*loaded_image.as_ptr()).load_options_size = args_size; + } + + self.args = Some(args); + } + + fn update_st_crc32(&mut self) -> io::Result<()> { + let bt: NonNull = boot_services().unwrap().cast(); + let st_size = unsafe { (*self.st.as_ptr()).hdr.header_size as usize }; + let mut crc32: u32 = 0; + + // Set crc to 0 before calcuation + unsafe { + (*self.st.as_mut_ptr()).hdr.crc32 = 0; + } + + let r = unsafe { + ((*bt.as_ptr()).calculate_crc32)( + self.st.as_mut_ptr() as *mut crate::ffi::c_void, + st_size, + &mut crc32, + ) + }; + + if r.is_error() { + Err(io::Error::from_raw_os_error(r.as_usize())) + } else { + unsafe { + (*self.st.as_mut_ptr()).hdr.crc32 = crc32; + } + Ok(()) + } + } + } + + impl Drop for Image { + fn drop(&mut self) { + if let Some(bt) = boot_services() { + let bt: NonNull = bt.cast(); + unsafe { + ((*bt.as_ptr()).unload_image)(self.handle.as_ptr()); + } + } + } + } + + #[repr(C)] + pub struct PipeProtocol { + reset: simple_text_output::ProtocolReset, + output_string: simple_text_output::ProtocolOutputString, + test_string: simple_text_output::ProtocolTestString, + query_mode: simple_text_output::ProtocolQueryMode, + set_mode: simple_text_output::ProtocolSetMode, + set_attribute: simple_text_output::ProtocolSetAttribute, + clear_screen: simple_text_output::ProtocolClearScreen, + set_cursor_position: simple_text_output::ProtocolSetCursorPosition, + enable_cursor: simple_text_output::ProtocolEnableCursor, + mode: *mut simple_text_output::Mode, + _buffer: Vec, + } + + impl PipeProtocol { + pub fn new() -> Self { + let mode = Box::new(simple_text_output::Mode { + max_mode: 0, + mode: 0, + attribute: 0, + cursor_column: 0, + cursor_row: 0, + cursor_visible: r_efi::efi::Boolean::FALSE, + }); + Self { + reset: Self::reset, + output_string: Self::output_string, + test_string: Self::test_string, + query_mode: Self::query_mode, + set_mode: Self::set_mode, + set_attribute: Self::set_attribute, + clear_screen: Self::clear_screen, + set_cursor_position: Self::set_cursor_position, + enable_cursor: Self::enable_cursor, + mode: Box::into_raw(mode), + _buffer: Vec::new(), + } + } + + pub fn null() -> Self { + let mode = Box::new(simple_text_output::Mode { + max_mode: 0, + mode: 0, + attribute: 0, + cursor_column: 0, + cursor_row: 0, + cursor_visible: r_efi::efi::Boolean::FALSE, + }); + Self { + reset: Self::reset_null, + output_string: Self::output_string_null, + test_string: Self::test_string, + query_mode: Self::query_mode, + set_mode: Self::set_mode, + set_attribute: Self::set_attribute, + clear_screen: Self::clear_screen, + set_cursor_position: Self::set_cursor_position, + enable_cursor: Self::enable_cursor, + mode: Box::into_raw(mode), + _buffer: Vec::new(), + } + } + + pub fn utf8(&self) -> io::Result> { + OsString::from_wide(&self._buffer) + .into_string() + .map(Into::into) + .map_err(|_| const_io_error!(io::ErrorKind::Other, "utf8 conversion failed")) + } + + extern "efiapi" fn reset( + proto: *mut simple_text_output::Protocol, + _: r_efi::efi::Boolean, + ) -> r_efi::efi::Status { + let proto: *mut PipeProtocol = proto.cast(); + unsafe { + (*proto)._buffer.clear(); + } + r_efi::efi::Status::SUCCESS + } + + extern "efiapi" fn reset_null( + _: *mut simple_text_output::Protocol, + _: r_efi::efi::Boolean, + ) -> r_efi::efi::Status { + r_efi::efi::Status::SUCCESS + } + + extern "efiapi" fn output_string( + proto: *mut simple_text_output::Protocol, + buf: *mut r_efi::efi::Char16, + ) -> r_efi::efi::Status { + let proto: *mut PipeProtocol = proto.cast(); + let buf_len = unsafe { + if let Some(x) = WStrUnits::new(buf) { + x.count() + } else { + return r_efi::efi::Status::INVALID_PARAMETER; + } + }; + let buf_slice = unsafe { slice::from_raw_parts(buf, buf_len) }; + + unsafe { + (*proto)._buffer.extend_from_slice(buf_slice); + }; + + r_efi::efi::Status::SUCCESS + } + + extern "efiapi" fn output_string_null( + _: *mut simple_text_output::Protocol, + _: *mut r_efi::efi::Char16, + ) -> r_efi::efi::Status { + r_efi::efi::Status::SUCCESS + } + + extern "efiapi" fn test_string( + _: *mut simple_text_output::Protocol, + _: *mut r_efi::efi::Char16, + ) -> r_efi::efi::Status { + r_efi::efi::Status::SUCCESS + } + + extern "efiapi" fn query_mode( + _: *mut simple_text_output::Protocol, + _: usize, + _: *mut usize, + _: *mut usize, + ) -> r_efi::efi::Status { + r_efi::efi::Status::UNSUPPORTED + } + + extern "efiapi" fn set_mode( + _: *mut simple_text_output::Protocol, + _: usize, + ) -> r_efi::efi::Status { + r_efi::efi::Status::UNSUPPORTED + } + + extern "efiapi" fn set_attribute( + _: *mut simple_text_output::Protocol, + _: usize, + ) -> r_efi::efi::Status { + r_efi::efi::Status::UNSUPPORTED + } + + extern "efiapi" fn clear_screen( + _: *mut simple_text_output::Protocol, + ) -> r_efi::efi::Status { + r_efi::efi::Status::UNSUPPORTED + } + + extern "efiapi" fn set_cursor_position( + _: *mut simple_text_output::Protocol, + _: usize, + _: usize, + ) -> r_efi::efi::Status { + r_efi::efi::Status::UNSUPPORTED + } + + extern "efiapi" fn enable_cursor( + _: *mut simple_text_output::Protocol, + _: r_efi::efi::Boolean, + ) -> r_efi::efi::Status { + r_efi::efi::Status::UNSUPPORTED + } + } + + impl Drop for PipeProtocol { + fn drop(&mut self) { + unsafe { + let _ = Box::from_raw(self.mode); + } + } + } +} diff --git a/std/src/sys/pal/uefi/time.rs b/std/src/sys/pal/uefi/time.rs index 76562cf9f51c0..495ff2dc930ed 100644 --- a/std/src/sys/pal/uefi/time.rs +++ b/std/src/sys/pal/uefi/time.rs @@ -59,11 +59,12 @@ impl SystemTime { } pub(crate) mod system_time_internal { + use r_efi::efi::{RuntimeServices, Time}; + use super::super::helpers; use super::*; use crate::mem::MaybeUninit; use crate::ptr::NonNull; - use r_efi::efi::{RuntimeServices, Time}; pub fn now() -> Option { let runtime_services: NonNull = helpers::runtime_services()?; @@ -114,13 +115,14 @@ pub(crate) mod system_time_internal { } pub(crate) mod instant_internal { + use r_efi::protocols::timestamp; + use super::super::helpers; use super::*; use crate::mem::MaybeUninit; use crate::ptr::NonNull; use crate::sync::atomic::{AtomicPtr, Ordering}; use crate::sys_common::mul_div_u64; - use r_efi::protocols::timestamp; const NS_PER_SEC: u64 = 1_000_000_000; @@ -173,10 +175,6 @@ pub(crate) mod instant_internal { #[cfg(target_arch = "x86_64")] fn timestamp_rdtsc() -> Option { - if !crate::arch::x86_64::has_cpuid() { - return None; - } - static FREQUENCY: crate::sync::OnceLock = crate::sync::OnceLock::new(); // Get Frequency in Mhz @@ -198,10 +196,6 @@ pub(crate) mod instant_internal { #[cfg(target_arch = "x86")] fn timestamp_rdtsc() -> Option { - if !crate::arch::x86::has_cpuid() { - return None; - } - static FREQUENCY: crate::sync::OnceLock = crate::sync::OnceLock::new(); let freq = FREQUENCY diff --git a/std/src/sys/pal/unix/alloc.rs b/std/src/sys/pal/unix/alloc.rs index eb3a57c212b4a..625ba5247f111 100644 --- a/std/src/sys/pal/unix/alloc.rs +++ b/std/src/sys/pal/unix/alloc.rs @@ -67,7 +67,7 @@ cfg_if::cfg_if! { ))] { #[inline] unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { - libc::memalign(layout.align(), layout.size()) as *mut u8 + unsafe { libc::memalign(layout.align(), layout.size()) as *mut u8 } } } else { #[inline] diff --git a/std/src/sys/pal/unix/android.rs b/std/src/sys/pal/unix/android.rs deleted file mode 100644 index 0f704994f550a..0000000000000 --- a/std/src/sys/pal/unix/android.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! Android ABI-compatibility module -//! -//! The ABI of Android has changed quite a bit over time, and std attempts to be -//! both forwards and backwards compatible as much as possible. We want to -//! always work with the most recent version of Android, but we also want to -//! work with older versions of Android for whenever projects need to. -//! -//! Our current minimum supported Android version is `android-9`, e.g., Android -//! with API level 9. We then in theory want to work on that and all future -//! versions of Android! -//! -//! Some of the detection here is done at runtime via `dlopen` and -//! introspection. Other times no detection is performed at all and we just -//! provide a fallback implementation as some versions of Android we support -//! don't have the function. -//! -//! You'll find more details below about why each compatibility shim is needed. - -#![cfg(target_os = "android")] - -use libc::{c_int, sighandler_t}; - -use super::weak::weak; - -// The `log2` and `log2f` functions apparently appeared in android-18, or at -// least you can see they're not present in the android-17 header [1] and they -// are present in android-18 [2]. -// -// [1]: https://chromium.googlesource.com/android_tools/+/20ee6d20/ndk/platforms -// /android-17/arch-arm/usr/include/math.h -// [2]: https://chromium.googlesource.com/android_tools/+/20ee6d20/ndk/platforms -// /android-18/arch-arm/usr/include/math.h -// -// Note that these shims are likely less precise than directly calling `log2`, -// but hopefully that should be enough for now... -// -// Note that mathematically, for any arbitrary `y`: -// -// log_2(x) = log_y(x) / log_y(2) -// = log_y(x) / (1 / log_2(y)) -// = log_y(x) * log_2(y) -// -// Hence because `ln` (log_e) is available on all Android we just choose `y = e` -// and get: -// -// log_2(x) = ln(x) * log_2(e) - -#[cfg(not(test))] -pub fn log2f32(f: f32) -> f32 { - f.ln() * crate::f32::consts::LOG2_E -} - -#[cfg(not(test))] -pub fn log2f64(f: f64) -> f64 { - f.ln() * crate::f64::consts::LOG2_E -} - -// Back in the day [1] the `signal` function was just an inline wrapper -// around `bsd_signal`, but starting in API level android-20 the `signal` -// symbols was introduced [2]. Finally, in android-21 the API `bsd_signal` was -// removed [3]. -// -// Basically this means that if we want to be binary compatible with multiple -// Android releases (oldest being 9 and newest being 21) then we need to check -// for both symbols and not actually link against either. -// -// [1]: https://chromium.googlesource.com/android_tools/+/20ee6d20/ndk/platforms -// /android-18/arch-arm/usr/include/signal.h -// [2]: https://chromium.googlesource.com/android_tools/+/fbd420/ndk_experimental -// /platforms/android-20/arch-arm -// /usr/include/signal.h -// [3]: https://chromium.googlesource.com/android_tools/+/20ee6d/ndk/platforms -// /android-21/arch-arm/usr/include/signal.h -pub unsafe fn signal(signum: c_int, handler: sighandler_t) -> sighandler_t { - weak!(fn signal(c_int, sighandler_t) -> sighandler_t); - weak!(fn bsd_signal(c_int, sighandler_t) -> sighandler_t); - - let f = signal.get().or_else(|| bsd_signal.get()); - let f = f.expect("neither `signal` nor `bsd_signal` symbols found"); - f(signum, handler) -} diff --git a/std/src/sys/pal/unix/args.rs b/std/src/sys/pal/unix/args.rs index e2ec838b740cb..9a37e1a0346d7 100644 --- a/std/src/sys/pal/unix/args.rs +++ b/std/src/sys/pal/unix/args.rs @@ -6,9 +6,8 @@ #![allow(dead_code)] // runtime init functions not used during testing use crate::ffi::{CStr, OsString}; -use crate::fmt; use crate::os::unix::ffi::OsStringExt; -use crate::vec; +use crate::{fmt, vec}; /// One-time global initialization. pub unsafe fn init(argc: isize, argv: *const *const u8) { diff --git a/std/src/sys/pal/unix/fd.rs b/std/src/sys/pal/unix/fd.rs index 1701717db597c..d8e239ee23ed5 100644 --- a/std/src/sys/pal/unix/fd.rs +++ b/std/src/sys/pal/unix/fd.rs @@ -3,12 +3,6 @@ #[cfg(test)] mod tests; -use crate::cmp; -use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read}; -use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; -use crate::sys::cvt; -use crate::sys_common::{AsInner, FromInner, IntoInner}; - #[cfg(any( target_os = "android", target_os = "linux", @@ -26,6 +20,12 @@ use libc::off64_t; )))] use libc::off_t as off64_t; +use crate::cmp; +use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read}; +use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; +use crate::sys::cvt; +use crate::sys_common::{AsInner, FromInner, IntoInner}; + #[derive(Debug)] pub struct FileDesc(OwnedFd); @@ -82,6 +82,11 @@ const fn max_iov() -> usize { } impl FileDesc { + #[inline] + pub fn try_clone(&self) -> io::Result { + self.duplicate() + } + pub fn read(&self, buf: &mut [u8]) -> io::Result { let ret = cvt(unsafe { libc::read( @@ -120,6 +125,7 @@ impl FileDesc { (&mut me).read_to_end(buf) } + #[cfg_attr(target_os = "vxworks", allow(unused_unsafe))] pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result { #[cfg(not(any( all(target_os = "linux", not(target_env = "musl")), @@ -313,6 +319,7 @@ impl FileDesc { cfg!(not(any(target_os = "espidf", target_os = "horizon", target_os = "vita"))) } + #[cfg_attr(target_os = "vxworks", allow(unused_unsafe))] pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result { #[cfg(not(any( all(target_os = "linux", not(target_env = "musl")), diff --git a/std/src/sys/pal/unix/fd/tests.rs b/std/src/sys/pal/unix/fd/tests.rs index 5d17e46786c79..c5301ce655787 100644 --- a/std/src/sys/pal/unix/fd/tests.rs +++ b/std/src/sys/pal/unix/fd/tests.rs @@ -1,6 +1,7 @@ +use core::mem::ManuallyDrop; + use super::{FileDesc, IoSlice}; use crate::os::unix::io::FromRawFd; -use core::mem::ManuallyDrop; #[test] fn limit_vector_count() { diff --git a/std/src/sys/pal/unix/fs.rs b/std/src/sys/pal/unix/fs.rs index 8308a48f16a9e..bdb83f0785784 100644 --- a/std/src/sys/pal/unix/fs.rs +++ b/std/src/sys/pal/unix/fs.rs @@ -4,29 +4,6 @@ #[cfg(test)] mod tests; -use crate::os::unix::prelude::*; - -use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt::{self, Write as _}; -use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom}; -use crate::mem; -use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd}; -use crate::path::{Path, PathBuf}; -use crate::ptr; -use crate::sync::Arc; -use crate::sys::common::small_c_string::run_path_with_cstr; -use crate::sys::fd::FileDesc; -use crate::sys::time::SystemTime; -use crate::sys::{cvt, cvt_r}; -use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; - -#[cfg(all(target_os = "linux", target_env = "gnu"))] -use crate::sys::weak::syscall; -#[cfg(target_os = "android")] -use crate::sys::weak::weak; - -use libc::{c_int, mode_t}; - #[cfg(all(target_os = "linux", target_env = "gnu"))] use libc::c_char; #[cfg(any( @@ -73,6 +50,7 @@ use libc::readdir64_r; target_os = "hurd", )))] use libc::readdir_r as readdir64_r; +use libc::{c_int, mode_t}; #[cfg(target_os = "android")] use libc::{ dirent as dirent64, fstat as fstat64, fstatat as fstatat64, ftruncate64, lseek64, @@ -97,7 +75,24 @@ use libc::{ ))] use libc::{dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, stat64}; +use crate::ffi::{CStr, OsStr, OsString}; +use crate::fmt::{self, Write as _}; +use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom}; +use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd}; +use crate::os::unix::prelude::*; +use crate::path::{Path, PathBuf}; +use crate::sync::Arc; +use crate::sys::common::small_c_string::run_path_with_cstr; +use crate::sys::fd::FileDesc; +use crate::sys::time::SystemTime; +#[cfg(all(target_os = "linux", target_env = "gnu"))] +use crate::sys::weak::syscall; +#[cfg(target_os = "android")] +use crate::sys::weak::weak; +use crate::sys::{cvt, cvt_r}; pub use crate::sys_common::fs::exists; +use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; +use crate::{mem, ptr}; pub struct File(FileDesc); @@ -463,15 +458,15 @@ impl FileAttr { #[cfg(target_os = "aix")] impl FileAttr { pub fn modified(&self) -> io::Result { - Ok(SystemTime::new(self.stat.st_mtime.tv_sec as i64, self.stat.st_mtime.tv_nsec as i64)) + SystemTime::new(self.stat.st_mtime.tv_sec as i64, self.stat.st_mtime.tv_nsec as i64) } pub fn accessed(&self) -> io::Result { - Ok(SystemTime::new(self.stat.st_atime.tv_sec as i64, self.stat.st_atime.tv_nsec as i64)) + SystemTime::new(self.stat.st_atime.tv_sec as i64, self.stat.st_atime.tv_nsec as i64) } pub fn created(&self) -> io::Result { - Ok(SystemTime::new(self.stat.st_ctime.tv_sec as i64, self.stat.st_ctime.tv_nsec as i64)) + SystemTime::new(self.stat.st_ctime.tv_sec as i64, self.stat.st_ctime.tv_nsec as i64) } } @@ -857,6 +852,7 @@ impl Drop for Dir { target_os = "espidf", target_os = "fuchsia", target_os = "horizon", + target_os = "vxworks", )))] { let fd = unsafe { libc::dirfd(self.0) }; @@ -1313,7 +1309,12 @@ impl File { } pub fn set_times(&self, times: FileTimes) -> io::Result<()> { - #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon")))] + #[cfg(not(any( + target_os = "redox", + target_os = "espidf", + target_os = "horizon", + target_os = "vxworks" + )))] let to_timespec = |time: Option| match time { Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts), Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_io_error!( @@ -1327,10 +1328,11 @@ impl File { None => Ok(libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT as _ }), }; cfg_if::cfg_if! { - if #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon"))] { + if #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon", target_os = "vxworks"))] { // Redox doesn't appear to support `UTIME_OMIT`. // ESP-IDF and HorizonOS do not support `futimens` at all and the behavior for those OS is therefore // the same as for Redox. + // `futimens` and `UTIME_OMIT` are a work in progress for vxworks. let _ = times; Err(io::const_io_error!( io::ErrorKind::Unsupported, @@ -1962,6 +1964,7 @@ pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> { Ok(()) } +#[cfg(not(target_os = "vxworks"))] pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> { run_path_with_cstr(path, &|path| { cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) }) @@ -1969,11 +1972,23 @@ pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> { }) } +#[cfg(target_os = "vxworks")] +pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> { + let (_, _, _) = (path, uid, gid); + Err(io::const_io_error!(io::ErrorKind::Unsupported, "lchown not supported by vxworks")) +} + #[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))] pub fn chroot(dir: &Path) -> io::Result<()> { run_path_with_cstr(dir, &|dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ())) } +#[cfg(target_os = "vxworks")] +pub fn chroot(dir: &Path) -> io::Result<()> { + let _ = dir; + Err(io::const_io_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks")) +} + pub use remove_dir_impl::remove_dir_all; // Fallback for REDOX, ESP-ID, Horizon, Vita, Vxworks and Miri @@ -2001,6 +2016,11 @@ mod remove_dir_impl { miri )))] mod remove_dir_impl { + #[cfg(not(all(target_os = "linux", target_env = "gnu")))] + use libc::{fdopendir, openat, unlinkat}; + #[cfg(all(target_os = "linux", target_env = "gnu"))] + use libc::{fdopendir, openat64 as openat, unlinkat}; + use super::{lstat, Dir, DirEntry, InnerReadDir, ReadDir}; use crate::ffi::CStr; use crate::io; @@ -2010,11 +2030,6 @@ mod remove_dir_impl { use crate::sys::common::small_c_string::run_path_with_cstr; use crate::sys::{cvt, cvt_r}; - #[cfg(not(all(target_os = "linux", target_env = "gnu")))] - use libc::{fdopendir, openat, unlinkat}; - #[cfg(all(target_os = "linux", target_env = "gnu"))] - use libc::{fdopendir, openat64 as openat, unlinkat}; - pub fn openat_nofollow_dironly(parent_fd: Option, p: &CStr) -> io::Result { let fd = cvt_r(|| unsafe { openat( diff --git a/std/src/sys/pal/unix/futex.rs b/std/src/sys/pal/unix/futex.rs index b8900da4cddb5..cc725045c4810 100644 --- a/std/src/sys/pal/unix/futex.rs +++ b/std/src/sys/pal/unix/futex.rs @@ -16,7 +16,7 @@ pub type SmallAtomic = AtomicU32; /// Must be the underlying type of SmallAtomic pub type SmallPrimitive = u32; -/// Wait for a futex_wake operation to wake us. +/// Waits for a `futex_wake` operation to wake us. /// /// Returns directly if the futex doesn't hold the expected value. /// @@ -87,7 +87,7 @@ pub fn futex_wait(futex: &AtomicU32, expected: u32, timeout: Option) - } } -/// Wake up one thread that's blocked on futex_wait on this futex. +/// Wakes up one thread that's blocked on `futex_wait` on this futex. /// /// Returns true if this actually woke up such a thread, /// or false if no thread was waiting on this futex. @@ -100,7 +100,7 @@ pub fn futex_wake(futex: &AtomicU32) -> bool { unsafe { libc::syscall(libc::SYS_futex, ptr, op, 1) > 0 } } -/// Wake up all threads that are waiting on futex_wait on this futex. +/// Wakes up all threads that are waiting on `futex_wait` on this futex. #[cfg(any(target_os = "linux", target_os = "android"))] pub fn futex_wake_all(futex: &AtomicU32) { let ptr = futex as *const AtomicU32; diff --git a/std/src/sys/pal/unix/io.rs b/std/src/sys/pal/unix/io.rs index 29c340dd34942..181c35a971eca 100644 --- a/std/src/sys/pal/unix/io.rs +++ b/std/src/sys/pal/unix/io.rs @@ -1,9 +1,9 @@ +use libc::{c_void, iovec}; + use crate::marker::PhantomData; use crate::os::fd::{AsFd, AsRawFd}; use crate::slice; -use libc::{c_void, iovec}; - #[derive(Copy, Clone)] #[repr(transparent)] pub struct IoSlice<'a> { diff --git a/std/src/sys/pal/unix/kernel_copy.rs b/std/src/sys/pal/unix/kernel_copy.rs index cd38b7c07e2b1..a671383cb7957 100644 --- a/std/src/sys/pal/unix/kernel_copy.rs +++ b/std/src/sys/pal/unix/kernel_copy.rs @@ -42,6 +42,12 @@ //! progress, they can hit a performance cliff. //! * complexity +#[cfg(not(any(all(target_os = "linux", target_env = "gnu"), target_os = "hurd")))] +use libc::sendfile as sendfile64; +#[cfg(any(all(target_os = "linux", target_env = "gnu"), target_os = "hurd"))] +use libc::sendfile64; +use libc::{EBADF, EINVAL, ENOSYS, EOPNOTSUPP, EOVERFLOW, EPERM, EXDEV}; + use crate::cmp::min; use crate::fs::{File, Metadata}; use crate::io::copy::generic_copy; @@ -54,16 +60,12 @@ use crate::net::TcpStream; use crate::os::unix::fs::FileTypeExt; use crate::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use crate::os::unix::net::UnixStream; +use crate::pipe::{PipeReader, PipeWriter}; use crate::process::{ChildStderr, ChildStdin, ChildStdout}; use crate::ptr; use crate::sync::atomic::{AtomicBool, AtomicU8, Ordering}; use crate::sys::cvt; use crate::sys::weak::syscall; -#[cfg(not(any(all(target_os = "linux", target_env = "gnu"), target_os = "hurd")))] -use libc::sendfile as sendfile64; -#[cfg(any(all(target_os = "linux", target_env = "gnu"), target_os = "hurd"))] -use libc::sendfile64; -use libc::{EBADF, EINVAL, ENOSYS, EOPNOTSUPP, EOVERFLOW, EPERM, EXDEV}; #[cfg(test)] mod tests; @@ -404,6 +406,30 @@ impl CopyWrite for &UnixStream { } } +impl CopyRead for PipeReader { + fn properties(&self) -> CopyParams { + CopyParams(FdMeta::Pipe, Some(self.as_raw_fd())) + } +} + +impl CopyRead for &PipeReader { + fn properties(&self) -> CopyParams { + CopyParams(FdMeta::Pipe, Some(self.as_raw_fd())) + } +} + +impl CopyWrite for PipeWriter { + fn properties(&self) -> CopyParams { + CopyParams(FdMeta::Pipe, Some(self.as_raw_fd())) + } +} + +impl CopyWrite for &PipeWriter { + fn properties(&self) -> CopyParams { + CopyParams(FdMeta::Pipe, Some(self.as_raw_fd())) + } +} + impl CopyWrite for ChildStdin { fn properties(&self) -> CopyParams { CopyParams(FdMeta::Pipe, Some(self.as_raw_fd())) diff --git a/std/src/sys/pal/unix/kernel_copy/tests.rs b/std/src/sys/pal/unix/kernel_copy/tests.rs index a524270e3fb85..1350d743ff6f3 100644 --- a/std/src/sys/pal/unix/kernel_copy/tests.rs +++ b/std/src/sys/pal/unix/kernel_copy/tests.rs @@ -1,8 +1,6 @@ use crate::fs::OpenOptions; use crate::io; -use crate::io::Result; -use crate::io::SeekFrom; -use crate::io::{BufRead, Read, Seek, Write}; +use crate::io::{BufRead, Read, Result, Seek, SeekFrom, Write}; use crate::os::unix::io::AsRawFd; use crate::sys_common::io::test::tmpdir; diff --git a/std/src/sys/pal/unix/mod.rs b/std/src/sys/pal/unix/mod.rs index 262f9c704a882..b62129f4cdd26 100644 --- a/std/src/sys/pal/unix/mod.rs +++ b/std/src/sys/pal/unix/mod.rs @@ -1,15 +1,13 @@ #![allow(missing_docs, nonstandard_style)] -use crate::io::ErrorKind; - pub use self::rand::hashmap_random_keys; +use crate::io::ErrorKind; #[cfg(not(target_os = "espidf"))] #[macro_use] pub mod weak; pub mod alloc; -pub mod android; pub mod args; pub mod env; pub mod fd; @@ -86,11 +84,12 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { target_vendor = "apple", )))] 'poll: { - use crate::sys::os::errno; #[cfg(not(all(target_os = "linux", target_env = "gnu")))] use libc::open as open64; #[cfg(all(target_os = "linux", target_env = "gnu"))] use libc::open64; + + use crate::sys::os::errno; let pfds: &mut [_] = &mut [ libc::pollfd { fd: 0, events: 0, revents: 0 }, libc::pollfd { fd: 1, events: 0, revents: 0 }, @@ -140,11 +139,12 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { target_os = "vita", )))] { - use crate::sys::os::errno; #[cfg(not(all(target_os = "linux", target_env = "gnu")))] use libc::open as open64; #[cfg(all(target_os = "linux", target_env = "gnu"))] use libc::open64; + + use crate::sys::os::errno; for fd in 0..3 { if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF { if open64(c"/dev/null".as_ptr().cast(), libc::O_RDWR, 0) == -1 { @@ -164,6 +164,8 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { target_os = "emscripten", target_os = "fuchsia", target_os = "horizon", + target_os = "vxworks", + target_os = "vita", // Unikraft's `signal` implementation is currently broken: // https://github.com/unikraft/lib-musl/issues/57 target_vendor = "unikraft", @@ -209,6 +211,8 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { target_os = "emscripten", target_os = "fuchsia", target_os = "horizon", + target_os = "vxworks", + target_os = "vita", )))] static ON_BROKEN_PIPE_FLAG_USED: crate::sync::atomic::AtomicBool = crate::sync::atomic::AtomicBool::new(false); @@ -218,6 +222,8 @@ static ON_BROKEN_PIPE_FLAG_USED: crate::sync::atomic::AtomicBool = target_os = "emscripten", target_os = "fuchsia", target_os = "horizon", + target_os = "vxworks", + target_os = "vita", )))] pub(crate) fn on_broken_pipe_flag_used() -> bool { ON_BROKEN_PIPE_FLAG_USED.load(crate::sync::atomic::Ordering::Relaxed) @@ -229,10 +235,7 @@ pub unsafe fn cleanup() { stack_overflow::cleanup(); } -#[cfg(target_os = "android")] -pub use crate::sys::android::signal; #[allow(unused_imports)] -#[cfg(not(target_os = "android"))] pub use libc::signal; #[inline] @@ -305,7 +308,7 @@ macro_rules! impl_is_minus_one { impl_is_minus_one! { i8 i16 i32 i64 isize } -/// Convert native return values to Result using the *-1 means error is in `errno`* convention. +/// Converts native return values to Result using the *-1 means error is in `errno`* convention. /// Non-error values are `Ok`-wrapped. pub fn cvt(t: T) -> crate::io::Result { if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) } diff --git a/std/src/sys/pal/unix/net.rs b/std/src/sys/pal/unix/net.rs index b8dc1538a6378..bc0e3f4eeeac8 100644 --- a/std/src/sys/pal/unix/net.rs +++ b/std/src/sys/pal/unix/net.rs @@ -1,17 +1,15 @@ -use crate::cmp; +use libc::{c_int, c_void, size_t, sockaddr, socklen_t, MSG_PEEK}; + use crate::ffi::CStr; use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut}; -use crate::mem; use crate::net::{Shutdown, SocketAddr}; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; -use crate::str; use crate::sys::fd::FileDesc; use crate::sys::pal::unix::IsMinusOne; use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr}; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::{Duration, Instant}; - -use libc::{c_int, c_void, size_t, sockaddr, socklen_t, MSG_PEEK}; +use crate::{cmp, mem}; cfg_if::cfg_if! { if #[cfg(target_vendor = "apple")] { @@ -47,7 +45,9 @@ pub fn cvt_gai(err: c_int) -> io::Result<()> { #[cfg(not(target_os = "espidf"))] let detail = unsafe { - str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap().to_owned() + // We can't always expect a UTF-8 environment. When we don't get that luxury, + // it's better to give a low-quality error message than none at all. + CStr::from_ptr(libc::gai_strerror(err)).to_string_lossy() }; #[cfg(target_os = "espidf")] @@ -213,16 +213,25 @@ impl Socket { } 0 => {} _ => { - // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look - // for POLLHUP rather than read readiness - if pollfd.revents & libc::POLLHUP != 0 { - let e = self.take_error()?.unwrap_or_else(|| { - io::const_io_error!( - io::ErrorKind::Uncategorized, - "no error set after POLLHUP", - ) - }); - return Err(e); + if cfg!(target_os = "vxworks") { + // VxWorks poll does not return POLLHUP or POLLERR in revents. Check if the + // connnection actually succeeded and return ok only when the socket is + // ready and no errors were found. + if let Some(e) = self.take_error()? { + return Err(e); + } + } else { + // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look + // for POLLHUP or POLLERR rather than read readiness + if pollfd.revents & (libc::POLLHUP | libc::POLLERR) != 0 { + let e = self.take_error()?.unwrap_or_else(|| { + io::const_io_error!( + io::ErrorKind::Uncategorized, + "no error set after POLLHUP", + ) + }); + return Err(e); + } } return Ok(()); diff --git a/std/src/sys/pal/unix/os.rs b/std/src/sys/pal/unix/os.rs index 9adc2b94e599e..a785b97ac8dc5 100644 --- a/std/src/sys/pal/unix/os.rs +++ b/std/src/sys/pal/unix/os.rs @@ -5,29 +5,20 @@ #[cfg(test)] mod tests; -use crate::os::unix::prelude::*; +use core::slice::memchr; + +use libc::{c_char, c_int, c_void}; use crate::error::Error as StdError; use crate::ffi::{CStr, CString, OsStr, OsString}; -use crate::fmt; -use crate::io; -use crate::iter; -use crate::mem; +use crate::os::unix::prelude::*; use crate::path::{self, PathBuf}; -use crate::ptr; -use crate::slice; -use crate::str; use crate::sync::{PoisonError, RwLock}; use crate::sys::common::small_c_string::{run_path_with_cstr, run_with_cstr}; -use crate::sys::cvt; -use crate::sys::fd; -use crate::vec; -use core::slice::memchr; - #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))] use crate::sys::weak::weak; - -use libc::{c_char, c_int, c_void}; +use crate::sys::{cvt, fd}; +use crate::{fmt, io, iter, mem, ptr, slice, str, vec}; const TMPBUF_SZ: usize = 128; @@ -248,13 +239,12 @@ impl StdError for JoinPathsError { #[cfg(target_os = "aix")] pub fn current_exe() -> io::Result { - use crate::io::ErrorKind; - #[cfg(test)] use realstd::env; #[cfg(not(test))] use crate::env; + use crate::io::ErrorKind; let exe_path = env::args().next().ok_or(io::const_io_error!( ErrorKind::NotFound, @@ -513,13 +503,12 @@ pub fn current_exe() -> io::Result { #[cfg(target_os = "fuchsia")] pub fn current_exe() -> io::Result { - use crate::io::ErrorKind; - #[cfg(test)] use realstd::env; #[cfg(not(test))] use crate::env; + use crate::io::ErrorKind; let exe_path = env::args().next().ok_or(io::const_io_error!( ErrorKind::Uncategorized, diff --git a/std/src/sys/pal/unix/pipe.rs b/std/src/sys/pal/unix/pipe.rs index 33db24e77e4da..f0ebc767badad 100644 --- a/std/src/sys/pal/unix/pipe.rs +++ b/std/src/sys/pal/unix/pipe.rs @@ -9,6 +9,7 @@ use crate::sys_common::{FromInner, IntoInner}; // Anonymous pipes //////////////////////////////////////////////////////////////////////////////// +#[derive(Debug)] pub struct AnonPipe(FileDesc); pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { @@ -46,6 +47,12 @@ pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { } impl AnonPipe { + #[allow(dead_code)] + // FIXME: This function seems legitimately unused. + pub fn try_clone(&self) -> io::Result { + self.0.duplicate().map(Self) + } + pub fn read(&self, buf: &mut [u8]) -> io::Result { self.0.read(buf) } @@ -79,6 +86,12 @@ impl AnonPipe { pub fn is_write_vectored(&self) -> bool { self.0.is_write_vectored() } + + #[allow(dead_code)] + // FIXME: This function seems legitimately unused. + pub fn as_file_desc(&self) -> &FileDesc { + &self.0 + } } impl IntoInner for AnonPipe { diff --git a/std/src/sys/pal/unix/process/process_common.rs b/std/src/sys/pal/unix/process/process_common.rs index f615e8086dccf..fec825054195a 100644 --- a/std/src/sys/pal/unix/process/process_common.rs +++ b/std/src/sys/pal/unix/process/process_common.rs @@ -1,24 +1,20 @@ #[cfg(all(test, not(target_os = "emscripten")))] mod tests; -use crate::os::unix::prelude::*; +use libc::{c_char, c_int, gid_t, pid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS}; use crate::collections::BTreeMap; use crate::ffi::{CStr, CString, OsStr, OsString}; -use crate::fmt; -use crate::io; +use crate::os::unix::prelude::*; use crate::path::Path; -use crate::ptr; use crate::sys::fd::FileDesc; use crate::sys::fs::File; +#[cfg(not(target_os = "fuchsia"))] +use crate::sys::fs::OpenOptions; use crate::sys::pipe::{self, AnonPipe}; use crate::sys_common::process::{CommandEnv, CommandEnvs}; use crate::sys_common::{FromInner, IntoInner}; - -#[cfg(not(target_os = "fuchsia"))] -use crate::sys::fs::OpenOptions; - -use libc::{c_char, c_int, gid_t, pid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS}; +use crate::{fmt, io, ptr}; cfg_if::cfg_if! { if #[cfg(target_os = "fuchsia")] { @@ -128,6 +124,7 @@ pub struct StdioPipes { // passed to do_exec() with configuration of what the child stdio should look // like +#[cfg_attr(target_os = "vita", allow(dead_code))] pub struct ChildPipes { pub stdin: ChildStdio, pub stdout: ChildStdio, diff --git a/std/src/sys/pal/unix/process/process_common/tests.rs b/std/src/sys/pal/unix/process/process_common/tests.rs index 823b4a5633629..e5c8dd6e341e1 100644 --- a/std/src/sys/pal/unix/process/process_common/tests.rs +++ b/std/src/sys/pal/unix/process/process_common/tests.rs @@ -1,9 +1,7 @@ use super::*; - use crate::ffi::OsStr; -use crate::mem; -use crate::ptr; use crate::sys::{cvt, cvt_nz}; +use crate::{mem, ptr}; macro_rules! t { ($e:expr) => { diff --git a/std/src/sys/pal/unix/process/process_fuchsia.rs b/std/src/sys/pal/unix/process/process_fuchsia.rs index 23c2be6adf9ee..f3d5fdec4c291 100644 --- a/std/src/sys/pal/unix/process/process_fuchsia.rs +++ b/std/src/sys/pal/unix/process/process_fuchsia.rs @@ -1,13 +1,9 @@ -use crate::fmt; -use crate::io; -use crate::mem; -use crate::num::NonZero; -use crate::ptr; +use libc::{c_int, size_t}; +use crate::num::NonZero; use crate::sys::process::process_common::*; use crate::sys::process::zircon::{zx_handle_t, Handle}; - -use libc::{c_int, size_t}; +use crate::{fmt, io, mem, ptr}; //////////////////////////////////////////////////////////////////////////////// // Command diff --git a/std/src/sys/pal/unix/process/process_unix.rs b/std/src/sys/pal/unix/process/process_unix.rs index abd4a334783e4..5552e9ac97753 100644 --- a/std/src/sys/pal/unix/process/process_unix.rs +++ b/std/src/sys/pal/unix/process/process_unix.rs @@ -1,20 +1,7 @@ -use crate::fmt; -use crate::io::{self, Error, ErrorKind}; -use crate::mem; -use crate::num::NonZero; -use crate::sys; -use crate::sys::cvt; -use crate::sys::process::process_common::*; - -#[cfg(target_os = "linux")] -use crate::sys::pal::unix::linux::pidfd::PidFd; - #[cfg(target_os = "vxworks")] use libc::RTP_ID as pid_t; - #[cfg(not(target_os = "vxworks"))] use libc::{c_int, pid_t}; - #[cfg(not(any( target_os = "vxworks", target_os = "l4re", @@ -23,6 +10,14 @@ use libc::{c_int, pid_t}; )))] use libc::{gid_t, uid_t}; +use crate::io::{self, Error, ErrorKind}; +use crate::num::NonZero; +use crate::sys::cvt; +#[cfg(target_os = "linux")] +use crate::sys::pal::unix::linux::pidfd::PidFd; +use crate::sys::process::process_common::*; +use crate::{fmt, mem, sys}; + cfg_if::cfg_if! { if #[cfg(all(target_os = "nto", target_env = "nto71"))] { use crate::thread; @@ -446,11 +441,12 @@ impl Command { stdio: &ChildPipes, envp: Option<&CStringArray>, ) -> io::Result> { + #[cfg(target_os = "linux")] + use core::sync::atomic::{AtomicU8, Ordering}; + use crate::mem::MaybeUninit; use crate::sys::weak::weak; use crate::sys::{self, cvt_nz, on_broken_pipe_flag_used}; - #[cfg(target_os = "linux")] - use core::sync::atomic::{AtomicU8, Ordering}; if self.get_gid().is_some() || self.get_uid().is_some() @@ -762,10 +758,11 @@ impl Command { #[cfg(target_os = "linux")] fn send_pidfd(&self, sock: &crate::sys::net::Socket) { + use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET}; + use crate::io::IoSlice; use crate::os::fd::RawFd; use crate::sys::cvt_r; - use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET}; unsafe { let child_pid = libc::getpid(); @@ -819,11 +816,11 @@ impl Command { #[cfg(target_os = "linux")] fn recv_pidfd(&self, sock: &crate::sys::net::Socket) -> pid_t { + use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET}; + use crate::io::IoSliceMut; use crate::sys::cvt_r; - use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET}; - unsafe { const SCM_MSG_LEN: usize = mem::size_of::<[c_int; 1]>(); @@ -1047,7 +1044,7 @@ impl From for ExitStatus { } } -/// Convert a signal number to a readable, searchable name. +/// Converts a signal number to a readable, searchable name. /// /// This string should be displayed right after the signal number. /// If a signal is unrecognized, it returns the empty string, so that @@ -1189,12 +1186,11 @@ impl ExitStatusError { #[cfg(target_os = "linux")] mod linux_child_ext { - use crate::io; - use crate::mem; use crate::os::linux::process as os; use crate::sys::pal::unix::linux::pidfd as imp; use crate::sys::pal::unix::ErrorKind; use crate::sys_common::FromInner; + use crate::{io, mem}; #[unstable(feature = "linux_pidfd", issue = "82971")] impl crate::os::linux::process::ChildExt for crate::process::Child { diff --git a/std/src/sys/pal/unix/process/process_unsupported.rs b/std/src/sys/pal/unix/process/process_unsupported.rs index 33d359d3f8411..c58548835ff3d 100644 --- a/std/src/sys/pal/unix/process/process_unsupported.rs +++ b/std/src/sys/pal/unix/process/process_unsupported.rs @@ -1,11 +1,10 @@ -use crate::fmt; +use libc::{c_int, pid_t}; + use crate::io; use crate::num::NonZero; use crate::sys::pal::unix::unsupported::*; use crate::sys::process::process_common::*; -use libc::{c_int, pid_t}; - //////////////////////////////////////////////////////////////////////////////// // Command //////////////////////////////////////////////////////////////////////////////// diff --git a/std/src/sys/pal/unix/process/process_unsupported/wait_status.rs b/std/src/sys/pal/unix/process/process_unsupported/wait_status.rs index 973188b1f2b27..f04036bde4922 100644 --- a/std/src/sys/pal/unix/process/process_unsupported/wait_status.rs +++ b/std/src/sys/pal/unix/process/process_unsupported/wait_status.rs @@ -2,12 +2,11 @@ //! //! Separate module to facilitate testing against a real Unix implementation. +use super::ExitStatusError; use crate::ffi::c_int; use crate::fmt; use crate::num::NonZero; -use super::ExitStatusError; - /// Emulated wait status for use by `process_unsupported.rs` /// /// Uses the "traditional unix" encoding. For use on platfors which are `#[cfg(unix)]` diff --git a/std/src/sys/pal/unix/process/process_vxworks.rs b/std/src/sys/pal/unix/process/process_vxworks.rs index 5007dbd34b4ab..6a9d8fab1d412 100644 --- a/std/src/sys/pal/unix/process/process_vxworks.rs +++ b/std/src/sys/pal/unix/process/process_vxworks.rs @@ -1,12 +1,11 @@ -use crate::fmt; +use libc::{self, c_char, c_int, RTP_ID}; + use crate::io::{self, ErrorKind}; use crate::num::NonZero; -use crate::sys; use crate::sys::cvt; +use crate::sys::pal::unix::thread; use crate::sys::process::process_common::*; -use crate::sys_common::thread; -use libc::RTP_ID; -use libc::{self, c_char, c_int}; +use crate::{fmt, sys}; //////////////////////////////////////////////////////////////////////////////// // Command @@ -68,7 +67,12 @@ impl Command { .as_ref() .map(|c| c.as_ptr()) .unwrap_or_else(|| *sys::os::environ() as *const _); - let stack_size = thread::min_stack(); + let stack_size = crate::cmp::max( + crate::env::var_os("RUST_MIN_STACK") + .and_then(|s| s.to_str().and_then(|s| s.parse().ok())) + .unwrap_or(thread::DEFAULT_MIN_STACK_SIZE), + libc::PTHREAD_STACK_MIN, + ); // ensure that access to the environment is synchronized let _lock = sys::os::env_read_lock(); diff --git a/std/src/sys/pal/unix/process/zircon.rs b/std/src/sys/pal/unix/process/zircon.rs index 2e596486f9c86..4035e2370a3c6 100644 --- a/std/src/sys/pal/unix/process/zircon.rs +++ b/std/src/sys/pal/unix/process/zircon.rs @@ -1,11 +1,11 @@ #![allow(non_camel_case_types, unused)] +use libc::{c_int, c_void, size_t}; + use crate::io; use crate::mem::MaybeUninit; use crate::os::raw::c_char; -use libc::{c_int, c_void, size_t}; - pub type zx_handle_t = u32; pub type zx_vaddr_t = usize; pub type zx_rights_t = u32; diff --git a/std/src/sys/pal/unix/rand.rs b/std/src/sys/pal/unix/rand.rs index e6df109a6b8f2..8a78ea8e7ccc7 100644 --- a/std/src/sys/pal/unix/rand.rs +++ b/std/src/sys/pal/unix/rand.rs @@ -24,7 +24,6 @@ pub fn hashmap_random_keys() -> (u64, u64) { mod imp { use crate::fs::File; use crate::io::Read; - #[cfg(any(target_os = "linux", target_os = "android"))] use crate::sys::weak::syscall; @@ -178,9 +177,10 @@ mod imp { #[cfg(target_vendor = "apple")] mod imp { - use crate::io; use libc::{c_int, c_void, size_t}; + use crate::io; + #[inline(always)] fn random_failure() -> ! { panic!("unexpected random generation error: {}", io::Error::last_os_error()); @@ -311,8 +311,10 @@ mod imp { #[cfg(target_os = "vxworks")] mod imp { + use core::sync::atomic::AtomicBool; + use core::sync::atomic::Ordering::Relaxed; + use crate::io; - use core::sync::atomic::{AtomicBool, Ordering::Relaxed}; pub fn fill_bytes(v: &mut [u8]) { static RNG_INIT: AtomicBool = AtomicBool::new(false); diff --git a/std/src/sys/pal/unix/stack_overflow.rs b/std/src/sys/pal/unix/stack_overflow.rs index 2e5bd85327a19..9ff44b54c41a1 100644 --- a/std/src/sys/pal/unix/stack_overflow.rs +++ b/std/src/sys/pal/unix/stack_overflow.rs @@ -1,10 +1,8 @@ #![cfg_attr(test, allow(dead_code))] +pub use self::imp::{cleanup, init}; use self::imp::{drop_handler, make_handler}; -pub use self::imp::cleanup; -pub use self::imp::init; - pub struct Handler { data: *mut libc::c_void, } @@ -37,23 +35,23 @@ impl Drop for Handler { target_os = "solaris" ))] mod imp { + #[cfg(not(all(target_os = "linux", target_env = "gnu")))] + use libc::{mmap as mmap64, mprotect, munmap}; + #[cfg(all(target_os = "linux", target_env = "gnu"))] + use libc::{mmap64, mprotect, munmap}; + use libc::{ + sigaction, sigaltstack, sighandler_t, MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, + PROT_NONE, PROT_READ, PROT_WRITE, SA_ONSTACK, SA_SIGINFO, SIGBUS, SIGSEGV, SIG_DFL, + SS_DISABLE, + }; + use super::Handler; use crate::cell::Cell; - use crate::io; - use crate::mem; use crate::ops::Range; - use crate::ptr; use crate::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; + use crate::sync::OnceLock; use crate::sys::pal::unix::os; - use crate::thread; - - #[cfg(not(all(target_os = "linux", target_env = "gnu")))] - use libc::{mmap as mmap64, mprotect, munmap}; - #[cfg(all(target_os = "linux", target_env = "gnu"))] - use libc::{mmap64, mprotect, munmap}; - use libc::{sigaction, sighandler_t, SA_ONSTACK, SA_SIGINFO, SIGBUS, SIGSEGV, SIG_DFL}; - use libc::{sigaltstack, SS_DISABLE}; - use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE}; + use crate::{io, mem, ptr, thread}; // We use a TLS variable to store the address of the guard page. While TLS // variables are not guaranteed to be signal-safe, this works out in practice @@ -86,13 +84,18 @@ mod imp { // out many large systems and all implementations allow returning from a // signal handler to work. For a more detailed explanation see the // comments on #26458. + /// SIGSEGV/SIGBUS entry point + /// # Safety + /// Rust doesn't call this, it *gets called*. + #[forbid(unsafe_op_in_unsafe_fn)] unsafe extern "C" fn signal_handler( signum: libc::c_int, info: *mut libc::siginfo_t, _data: *mut libc::c_void, ) { let (start, end) = GUARD.get(); - let addr = (*info).si_addr() as usize; + // SAFETY: this pointer is provided by the system and will always point to a valid `siginfo_t`. + let addr = unsafe { (*info).si_addr().addr() }; // If the faulting address is within the guard page, then we print a // message saying so and abort. @@ -104,9 +107,11 @@ mod imp { rtabort!("stack overflow"); } else { // Unregister ourselves by reverting back to the default behavior. - let mut action: sigaction = mem::zeroed(); + // SAFETY: assuming all platforms define struct sigaction as "zero-initializable" + let mut action: sigaction = unsafe { mem::zeroed() }; action.sa_sigaction = SIG_DFL; - sigaction(signum, &action, ptr::null_mut()); + // SAFETY: pray this is a well-behaved POSIX implementation of fn sigaction + unsafe { sigaction(signum, &action, ptr::null_mut()) }; // See comment above for why this function returns. } @@ -116,32 +121,45 @@ mod imp { static MAIN_ALTSTACK: AtomicPtr = AtomicPtr::new(ptr::null_mut()); static NEED_ALTSTACK: AtomicBool = AtomicBool::new(false); + /// # Safety + /// Must be called only once + #[forbid(unsafe_op_in_unsafe_fn)] pub unsafe fn init() { PAGE_SIZE.store(os::page_size(), Ordering::Relaxed); // Always write to GUARD to ensure the TLS variable is allocated. - let guard = install_main_guard().unwrap_or(0..0); + let guard = unsafe { install_main_guard().unwrap_or(0..0) }; GUARD.set((guard.start, guard.end)); - let mut action: sigaction = mem::zeroed(); + // SAFETY: assuming all platforms define struct sigaction as "zero-initializable" + let mut action: sigaction = unsafe { mem::zeroed() }; for &signal in &[SIGSEGV, SIGBUS] { - sigaction(signal, ptr::null_mut(), &mut action); + // SAFETY: just fetches the current signal handler into action + unsafe { sigaction(signal, ptr::null_mut(), &mut action) }; // Configure our signal handler if one is not already set. if action.sa_sigaction == SIG_DFL { + if !NEED_ALTSTACK.load(Ordering::Relaxed) { + // haven't set up our sigaltstack yet + NEED_ALTSTACK.store(true, Ordering::Release); + let handler = unsafe { make_handler(true) }; + MAIN_ALTSTACK.store(handler.data, Ordering::Relaxed); + mem::forget(handler); + } action.sa_flags = SA_SIGINFO | SA_ONSTACK; action.sa_sigaction = signal_handler as sighandler_t; - sigaction(signal, &action, ptr::null_mut()); - NEED_ALTSTACK.store(true, Ordering::Relaxed); + // SAFETY: only overriding signals if the default is set + unsafe { sigaction(signal, &action, ptr::null_mut()) }; } } - - let handler = make_handler(true); - MAIN_ALTSTACK.store(handler.data, Ordering::Relaxed); - mem::forget(handler); } + /// # Safety + /// Must be called only once + #[forbid(unsafe_op_in_unsafe_fn)] pub unsafe fn cleanup() { - drop_handler(MAIN_ALTSTACK.load(Ordering::Relaxed)); + // FIXME: I probably cause more bugs than I'm worth! + // see https://github.com/rust-lang/rust/issues/111272 + unsafe { drop_handler(MAIN_ALTSTACK.load(Ordering::Relaxed)) }; } unsafe fn get_stack() -> libc::stack_t { @@ -186,34 +204,48 @@ mod imp { libc::stack_t { ss_sp: stackp, ss_flags: 0, ss_size: sigstack_size } } + /// # Safety + /// Mutates the alternate signal stack + #[forbid(unsafe_op_in_unsafe_fn)] pub unsafe fn make_handler(main_thread: bool) -> Handler { - if !NEED_ALTSTACK.load(Ordering::Relaxed) { + if !NEED_ALTSTACK.load(Ordering::Acquire) { return Handler::null(); } if !main_thread { // Always write to GUARD to ensure the TLS variable is allocated. - let guard = current_guard().unwrap_or(0..0); + let guard = unsafe { current_guard() }.unwrap_or(0..0); GUARD.set((guard.start, guard.end)); } - let mut stack = mem::zeroed(); - sigaltstack(ptr::null(), &mut stack); + // SAFETY: assuming stack_t is zero-initializable + let mut stack = unsafe { mem::zeroed() }; + // SAFETY: reads current stack_t into stack + unsafe { sigaltstack(ptr::null(), &mut stack) }; // Configure alternate signal stack, if one is not already set. if stack.ss_flags & SS_DISABLE != 0 { - stack = get_stack(); - sigaltstack(&stack, ptr::null_mut()); + // SAFETY: We warned our caller this would happen! + unsafe { + stack = get_stack(); + sigaltstack(&stack, ptr::null_mut()); + } Handler { data: stack.ss_sp as *mut libc::c_void } } else { Handler::null() } } + /// # Safety + /// Must be called + /// - only with our handler or nullptr + /// - only when done with our altstack + /// This disables the alternate signal stack! + #[forbid(unsafe_op_in_unsafe_fn)] pub unsafe fn drop_handler(data: *mut libc::c_void) { if !data.is_null() { let sigstack_size = sigstack_size(); let page_size = PAGE_SIZE.load(Ordering::Relaxed); - let stack = libc::stack_t { + let disabling_stack = libc::stack_t { ss_sp: ptr::null_mut(), ss_flags: SS_DISABLE, // Workaround for bug in macOS implementation of sigaltstack @@ -222,10 +254,11 @@ mod imp { // both ss_sp and ss_size should be ignored in this case. ss_size: sigstack_size, }; - sigaltstack(&stack, ptr::null_mut()); - // We know from `get_stackp` that the alternate stack we installed is part of a mapping - // that started one page earlier, so walk back a page and unmap from there. - munmap(data.sub(page_size), sigstack_size + page_size); + // SAFETY: we warned the caller this disables the alternate signal stack! + unsafe { sigaltstack(&disabling_stack, ptr::null_mut()) }; + // SAFETY: We know from `get_stackp` that the alternate stack we installed is part of + // a mapping that started one page earlier, so walk back a page and unmap from there. + unsafe { munmap(data.sub(page_size), sigstack_size + page_size) }; } } @@ -306,9 +339,8 @@ mod imp { ret } - unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> { - let page_size = PAGE_SIZE.load(Ordering::Relaxed); - let stackptr = get_stack_start()?; + fn stack_start_aligned(page_size: usize) -> Option<*mut libc::c_void> { + let stackptr = unsafe { get_stack_start()? }; let stackaddr = stackptr.addr(); // Ensure stackaddr is page aligned! A parent process might @@ -325,107 +357,137 @@ mod imp { }) } + #[forbid(unsafe_op_in_unsafe_fn)] unsafe fn install_main_guard() -> Option> { let page_size = PAGE_SIZE.load(Ordering::Relaxed); - if cfg!(all(target_os = "linux", not(target_env = "musl"))) { - // Linux doesn't allocate the whole stack right away, and - // the kernel has its own stack-guard mechanism to fault - // when growing too close to an existing mapping. If we map - // our own guard, then the kernel starts enforcing a rather - // large gap above that, rendering much of the possible - // stack space useless. See #43052. - // - // Instead, we'll just note where we expect rlimit to start - // faulting, so our handler can report "stack overflow", and - // trust that the kernel's own stack guard will work. - let stackptr = get_stack_start_aligned()?; - let stackaddr = stackptr.addr(); - Some(stackaddr - page_size..stackaddr) - } else if cfg!(all(target_os = "linux", target_env = "musl")) { - // For the main thread, the musl's pthread_attr_getstack - // returns the current stack size, rather than maximum size - // it can eventually grow to. It cannot be used to determine - // the position of kernel's stack guard. - None - } else if cfg!(target_os = "freebsd") { - // FreeBSD's stack autogrows, and optionally includes a guard page - // at the bottom. If we try to remap the bottom of the stack - // ourselves, FreeBSD's guard page moves upwards. So we'll just use - // the builtin guard page. - let stackptr = get_stack_start_aligned()?; - let guardaddr = stackptr.addr(); - // Technically the number of guard pages is tunable and controlled - // by the security.bsd.stack_guard_page sysctl. - // By default it is 1, checking once is enough since it is - // a boot time config value. - static PAGES: crate::sync::OnceLock = crate::sync::OnceLock::new(); - - let pages = PAGES.get_or_init(|| { - use crate::sys::weak::dlsym; - dlsym!(fn sysctlbyname(*const libc::c_char, *mut libc::c_void, *mut libc::size_t, *const libc::c_void, libc::size_t) -> libc::c_int); - let mut guard: usize = 0; - let mut size = crate::mem::size_of_val(&guard); - let oid = crate::ffi::CStr::from_bytes_with_nul( - b"security.bsd.stack_guard_page\0", - ) - .unwrap(); - match sysctlbyname.get() { - Some(fcn) => { - if fcn(oid.as_ptr(), core::ptr::addr_of_mut!(guard) as *mut _, core::ptr::addr_of_mut!(size) as *mut _, crate::ptr::null_mut(), 0) == 0 { - guard - } else { - 1 - } - }, - _ => 1, - } - }); - Some(guardaddr..guardaddr + pages * page_size) - } else if cfg!(any(target_os = "openbsd", target_os = "netbsd")) { - // OpenBSD stack already includes a guard page, and stack is - // immutable. - // NetBSD stack includes the guard page. - // - // We'll just note where we expect rlimit to start - // faulting, so our handler can report "stack overflow", and - // trust that the kernel's own stack guard will work. - let stackptr = get_stack_start_aligned()?; - let stackaddr = stackptr.addr(); - Some(stackaddr - page_size..stackaddr) - } else { - // Reallocate the last page of the stack. - // This ensures SIGBUS will be raised on - // stack overflow. - // Systems which enforce strict PAX MPROTECT do not allow - // to mprotect() a mapping with less restrictive permissions - // than the initial mmap() used, so we mmap() here with - // read/write permissions and only then mprotect() it to - // no permissions at all. See issue #50313. - let stackptr = get_stack_start_aligned()?; - let result = mmap64( + + unsafe { + // this way someone on any unix-y OS can check that all these compile + if cfg!(all(target_os = "linux", not(target_env = "musl"))) { + install_main_guard_linux(page_size) + } else if cfg!(all(target_os = "linux", target_env = "musl")) { + install_main_guard_linux_musl(page_size) + } else if cfg!(target_os = "freebsd") { + install_main_guard_freebsd(page_size) + } else if cfg!(any(target_os = "netbsd", target_os = "openbsd")) { + install_main_guard_bsds(page_size) + } else { + install_main_guard_default(page_size) + } + } + } + + #[forbid(unsafe_op_in_unsafe_fn)] + unsafe fn install_main_guard_linux(page_size: usize) -> Option> { + // Linux doesn't allocate the whole stack right away, and + // the kernel has its own stack-guard mechanism to fault + // when growing too close to an existing mapping. If we map + // our own guard, then the kernel starts enforcing a rather + // large gap above that, rendering much of the possible + // stack space useless. See #43052. + // + // Instead, we'll just note where we expect rlimit to start + // faulting, so our handler can report "stack overflow", and + // trust that the kernel's own stack guard will work. + let stackptr = stack_start_aligned(page_size)?; + let stackaddr = stackptr.addr(); + Some(stackaddr - page_size..stackaddr) + } + + #[forbid(unsafe_op_in_unsafe_fn)] + unsafe fn install_main_guard_linux_musl(_page_size: usize) -> Option> { + // For the main thread, the musl's pthread_attr_getstack + // returns the current stack size, rather than maximum size + // it can eventually grow to. It cannot be used to determine + // the position of kernel's stack guard. + None + } + + #[forbid(unsafe_op_in_unsafe_fn)] + unsafe fn install_main_guard_freebsd(page_size: usize) -> Option> { + // FreeBSD's stack autogrows, and optionally includes a guard page + // at the bottom. If we try to remap the bottom of the stack + // ourselves, FreeBSD's guard page moves upwards. So we'll just use + // the builtin guard page. + let stackptr = stack_start_aligned(page_size)?; + let guardaddr = stackptr.addr(); + // Technically the number of guard pages is tunable and controlled + // by the security.bsd.stack_guard_page sysctl. + // By default it is 1, checking once is enough since it is + // a boot time config value. + static PAGES: OnceLock = OnceLock::new(); + + let pages = PAGES.get_or_init(|| { + use crate::sys::weak::dlsym; + dlsym!(fn sysctlbyname(*const libc::c_char, *mut libc::c_void, *mut libc::size_t, *const libc::c_void, libc::size_t) -> libc::c_int); + let mut guard: usize = 0; + let mut size = mem::size_of_val(&guard); + let oid = c"security.bsd.stack_guard_page"; + match sysctlbyname.get() { + Some(fcn) if unsafe { + fcn(oid.as_ptr(), + ptr::addr_of_mut!(guard).cast(), + ptr::addr_of_mut!(size), + ptr::null_mut(), + 0) == 0 + } => guard, + _ => 1, + } + }); + Some(guardaddr..guardaddr + pages * page_size) + } + + #[forbid(unsafe_op_in_unsafe_fn)] + unsafe fn install_main_guard_bsds(page_size: usize) -> Option> { + // OpenBSD stack already includes a guard page, and stack is + // immutable. + // NetBSD stack includes the guard page. + // + // We'll just note where we expect rlimit to start + // faulting, so our handler can report "stack overflow", and + // trust that the kernel's own stack guard will work. + let stackptr = stack_start_aligned(page_size)?; + let stackaddr = stackptr.addr(); + Some(stackaddr - page_size..stackaddr) + } + + #[forbid(unsafe_op_in_unsafe_fn)] + unsafe fn install_main_guard_default(page_size: usize) -> Option> { + // Reallocate the last page of the stack. + // This ensures SIGBUS will be raised on + // stack overflow. + // Systems which enforce strict PAX MPROTECT do not allow + // to mprotect() a mapping with less restrictive permissions + // than the initial mmap() used, so we mmap() here with + // read/write permissions and only then mprotect() it to + // no permissions at all. See issue #50313. + let stackptr = stack_start_aligned(page_size)?; + let result = unsafe { + mmap64( stackptr, page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_FIXED, -1, 0, - ); - if result != stackptr || result == MAP_FAILED { - panic!("failed to allocate a guard page: {}", io::Error::last_os_error()); - } + ) + }; + if result != stackptr || result == MAP_FAILED { + panic!("failed to allocate a guard page: {}", io::Error::last_os_error()); + } - let result = mprotect(stackptr, page_size, PROT_NONE); - if result != 0 { - panic!("failed to protect the guard page: {}", io::Error::last_os_error()); - } + let result = unsafe { mprotect(stackptr, page_size, PROT_NONE) }; + if result != 0 { + panic!("failed to protect the guard page: {}", io::Error::last_os_error()); + } - let guardaddr = stackptr.addr(); + let guardaddr = stackptr.addr(); - Some(guardaddr..guardaddr + page_size) - } + Some(guardaddr..guardaddr + page_size) } #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))] + // FIXME: I am probably not unsafe. unsafe fn current_guard() -> Option> { let stackptr = get_stack_start()?; let stackaddr = stackptr.addr(); @@ -440,6 +502,7 @@ mod imp { target_os = "netbsd", target_os = "l4re" ))] + // FIXME: I am probably not unsafe. unsafe fn current_guard() -> Option> { let mut ret = None; let mut attr: libc::pthread_attr_t = crate::mem::zeroed(); diff --git a/std/src/sys/pal/unix/thread.rs b/std/src/sys/pal/unix/thread.rs index 619f4e4121e73..44cb7b7b7ce5b 100644 --- a/std/src/sys/pal/unix/thread.rs +++ b/std/src/sys/pal/unix/thread.rs @@ -1,16 +1,13 @@ -use crate::cmp; use crate::ffi::CStr; -use crate::io; -use crate::mem; +use crate::mem::{self, ManuallyDrop}; use crate::num::NonZero; -use crate::ptr; -use crate::sys::{os, stack_overflow}; -use crate::time::Duration; - #[cfg(all(target_os = "linux", target_env = "gnu"))] use crate::sys::weak::dlsym; #[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))] use crate::sys::weak::weak; +use crate::sys::{os, stack_overflow}; +use crate::time::Duration; +use crate::{cmp, io, ptr}; #[cfg(not(any(target_os = "l4re", target_os = "vxworks", target_os = "espidf")))] pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024; #[cfg(target_os = "l4re")] @@ -268,11 +265,9 @@ impl Thread { } pub fn join(self) { - unsafe { - let ret = libc::pthread_join(self.id, ptr::null_mut()); - mem::forget(self); - assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret)); - } + let id = self.into_id(); + let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) }; + assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret)); } pub fn id(&self) -> libc::pthread_t { @@ -280,9 +275,7 @@ impl Thread { } pub fn into_id(self) -> libc::pthread_t { - let id = self.id; - mem::forget(self); - id + ManuallyDrop::new(self).id } } @@ -462,8 +455,18 @@ pub fn available_parallelism() -> io::Result> { Ok(NonZero::new_unchecked(sinfo.cpu_count as usize)) } + } else if #[cfg(target_os = "vxworks")] { + // Note: there is also `vxCpuConfiguredGet`, closer to _SC_NPROCESSORS_CONF + // expectations than the actual cores availability. + extern "C" { + fn vxCpuEnabledGet() -> libc::cpuset_t; + } + + // always fetches a valid bitmask + let set = unsafe { vxCpuEnabledGet() }; + Ok(NonZero::new_unchecked(set.count_ones() as usize)) } else { - // FIXME: implement on vxWorks, Redox, l4re + // FIXME: implement on Redox, l4re Err(io::const_io_error!(io::ErrorKind::Unsupported, "Getting the number of hardware threads is not supported on the target platform")) } } @@ -479,11 +482,9 @@ mod cgroups { use crate::borrow::Cow; use crate::ffi::OsString; use crate::fs::{exists, File}; - use crate::io::Read; - use crate::io::{BufRead, BufReader}; + use crate::io::{BufRead, BufReader, Read}; use crate::os::unix::ffi::OsStringExt; - use crate::path::Path; - use crate::path::PathBuf; + use crate::path::{Path, PathBuf}; use crate::str::from_utf8; #[derive(PartialEq)] diff --git a/std/src/sys/pal/unix/thread_parking.rs b/std/src/sys/pal/unix/thread_parking.rs index 1366410b71edc..1da5fce3cd30f 100644 --- a/std/src/sys/pal/unix/thread_parking.rs +++ b/std/src/sys/pal/unix/thread_parking.rs @@ -2,10 +2,11 @@ // separate modules for each platform. #![cfg(target_os = "netbsd")] +use libc::{_lwp_self, c_long, clockid_t, lwpid_t, time_t, timespec, CLOCK_MONOTONIC}; + use crate::ffi::{c_int, c_void}; use crate::ptr; use crate::time::Duration; -use libc::{_lwp_self, c_long, clockid_t, lwpid_t, time_t, timespec, CLOCK_MONOTONIC}; extern "C" { fn ___lwp_park60( diff --git a/std/src/sys/pal/unix/weak.rs b/std/src/sys/pal/unix/weak.rs index 4765a286e6b9e..35762f5a53b5b 100644 --- a/std/src/sys/pal/unix/weak.rs +++ b/std/src/sys/pal/unix/weak.rs @@ -23,9 +23,8 @@ use crate::ffi::CStr; use crate::marker::PhantomData; -use crate::mem; -use crate::ptr; use crate::sync::atomic::{self, AtomicPtr, Ordering}; +use crate::{mem, ptr}; // We can use true weak linkage on ELF targets. #[cfg(all(unix, not(target_vendor = "apple")))] @@ -169,14 +168,7 @@ pub(crate) macro syscall { if let Some(fun) = $name.get() { fun($($arg_name),*) } else { - // This looks like a hack, but concat_idents only accepts idents - // (not paths). - use libc::*; - - syscall( - concat_idents!(SYS_, $name), - $($arg_name),* - ) as $ret + libc::syscall(libc::${concat(SYS_, $name)}, $($arg_name),*) as $ret } } ) @@ -186,14 +178,7 @@ pub(crate) macro syscall { pub(crate) macro raw_syscall { (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => ( unsafe fn $name($($arg_name:$t),*) -> $ret { - // This looks like a hack, but concat_idents only accepts idents - // (not paths). - use libc::*; - - syscall( - concat_idents!(SYS_, $name), - $($arg_name),* - ) as $ret + libc::syscall(libc::${concat(SYS_, $name)}, $($arg_name),*) as $ret } ) } diff --git a/std/src/sys/pal/unsupported/os.rs b/std/src/sys/pal/unsupported/os.rs index 3be98898bbeb9..481fd62c04fe8 100644 --- a/std/src/sys/pal/unsupported/os.rs +++ b/std/src/sys/pal/unsupported/os.rs @@ -1,10 +1,9 @@ use super::unsupported; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::path::{self, PathBuf}; +use crate::{fmt, io}; pub fn errno() -> i32 { 0 diff --git a/std/src/sys/pal/unsupported/pipe.rs b/std/src/sys/pal/unsupported/pipe.rs index d7d8f297ae586..6799d21a1ff75 100644 --- a/std/src/sys/pal/unsupported/pipe.rs +++ b/std/src/sys/pal/unsupported/pipe.rs @@ -1,8 +1,19 @@ +use crate::fmt; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; pub struct AnonPipe(!); +impl fmt::Debug for AnonPipe { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0 + } +} + impl AnonPipe { + pub fn try_clone(&self) -> io::Result { + self.0 + } + pub fn read(&self, _buf: &mut [u8]) -> io::Result { self.0 } diff --git a/std/src/sys/pal/unsupported/process.rs b/std/src/sys/pal/unsupported/process.rs index 2445d9073dbb9..40231bfc90b1e 100644 --- a/std/src/sys/pal/unsupported/process.rs +++ b/std/src/sys/pal/unsupported/process.rs @@ -1,14 +1,12 @@ +pub use crate::ffi::OsString as EnvKey; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::num::NonZero; use crate::path::Path; use crate::sys::fs::File; use crate::sys::pipe::AnonPipe; use crate::sys::unsupported; use crate::sys_common::process::{CommandEnv, CommandEnvs}; - -pub use crate::ffi::OsString as EnvKey; +use crate::{fmt, io}; //////////////////////////////////////////////////////////////////////////////// // Command diff --git a/std/src/sys/pal/wasi/args.rs b/std/src/sys/pal/wasi/args.rs index c42c310e3a254..6b6d1b8ff4e2e 100644 --- a/std/src/sys/pal/wasi/args.rs +++ b/std/src/sys/pal/wasi/args.rs @@ -1,9 +1,8 @@ #![deny(unsafe_op_in_unsafe_fn)] use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; use crate::os::wasi::ffi::OsStrExt; -use crate::vec; +use crate::{fmt, vec}; pub struct Args { iter: vec::IntoIter, diff --git a/std/src/sys/pal/wasi/fs.rs b/std/src/sys/pal/wasi/fs.rs index c58e6a08b374e..11900886f0b5c 100644 --- a/std/src/sys/pal/wasi/fs.rs +++ b/std/src/sys/pal/wasi/fs.rs @@ -2,22 +2,19 @@ use super::fd::WasiFd; use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, SeekFrom}; -use crate::iter; use crate::mem::{self, ManuallyDrop}; use crate::os::raw::c_int; use crate::os::wasi::ffi::{OsStrExt, OsStringExt}; use crate::os::wasi::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::path::{Path, PathBuf}; -use crate::ptr; use crate::sync::Arc; use crate::sys::common::small_c_string::run_path_with_cstr; use crate::sys::time::SystemTime; use crate::sys::unsupported; -use crate::sys_common::{AsInner, FromInner, IntoInner}; - pub use crate::sys_common::fs::exists; +use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::{fmt, iter, ptr}; pub struct File { fd: WasiFd, diff --git a/std/src/sys/pal/wasi/helpers.rs b/std/src/sys/pal/wasi/helpers.rs index 82149cef8fad1..4b770ee23bc5d 100644 --- a/std/src/sys/pal/wasi/helpers.rs +++ b/std/src/sys/pal/wasi/helpers.rs @@ -1,5 +1,4 @@ -use crate::io as std_io; -use crate::mem; +use crate::{io as std_io, mem}; #[inline] pub fn is_interrupted(errno: i32) -> bool { diff --git a/std/src/sys/pal/wasi/mod.rs b/std/src/sys/pal/wasi/mod.rs index d8fe06d1973c9..f4dc3ebd4140b 100644 --- a/std/src/sys/pal/wasi/mod.rs +++ b/std/src/sys/pal/wasi/mod.rs @@ -48,8 +48,5 @@ mod helpers; // import conflict rules. If we glob export `helpers` and `common` together, // then the compiler complains about conflicts. -pub use helpers::abort_internal; -pub use helpers::decode_error_kind; use helpers::err2io; -pub use helpers::hashmap_random_keys; -pub use helpers::is_interrupted; +pub use helpers::{abort_internal, decode_error_kind, hashmap_random_keys, is_interrupted}; diff --git a/std/src/sys/pal/wasi/os.rs b/std/src/sys/pal/wasi/os.rs index e96296997e6a9..f5b17d9df94b4 100644 --- a/std/src/sys/pal/wasi/os.rs +++ b/std/src/sys/pal/wasi/os.rs @@ -1,18 +1,16 @@ #![deny(unsafe_op_in_unsafe_fn)] +use core::slice::memchr; + use crate::error::Error as StdError; use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::ops::Drop; use crate::os::wasi::prelude::*; use crate::path::{self, PathBuf}; -use crate::str; use crate::sys::common::small_c_string::{run_path_with_cstr, run_with_cstr}; use crate::sys::unsupported; -use crate::vec; -use core::slice::memchr; +use crate::{fmt, io, str, vec}; // Add a few symbols not in upstream `libc` just yet. mod libc { diff --git a/std/src/sys/pal/wasi/thread.rs b/std/src/sys/pal/wasi/thread.rs index 975eef2451f4c..c37acd8dfeeb7 100644 --- a/std/src/sys/pal/wasi/thread.rs +++ b/std/src/sys/pal/wasi/thread.rs @@ -1,9 +1,8 @@ use crate::ffi::CStr; -use crate::io; -use crate::mem; use crate::num::NonZero; use crate::sys::unsupported; use crate::time::Duration; +use crate::{io, mem}; cfg_if::cfg_if! { if #[cfg(target_feature = "atomics")] { @@ -172,12 +171,10 @@ impl Thread { pub fn join(self) { cfg_if::cfg_if! { if #[cfg(target_feature = "atomics")] { - unsafe { - let ret = libc::pthread_join(self.id, ptr::null_mut()); - mem::forget(self); - if ret != 0 { - rtabort!("failed to join thread: {}", io::Error::from_raw_os_error(ret)); - } + let id = mem::ManuallyDrop::new(self).id; + let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) }; + if ret != 0 { + rtabort!("failed to join thread: {}", io::Error::from_raw_os_error(ret)); } } else { self.0 diff --git a/std/src/sys/pal/wasip2/mod.rs b/std/src/sys/pal/wasip2/mod.rs index 0930d2e22fa8d..f20630e10cff9 100644 --- a/std/src/sys/pal/wasip2/mod.rs +++ b/std/src/sys/pal/wasip2/mod.rs @@ -51,10 +51,7 @@ mod helpers; // import conflict rules. If we glob export `helpers` and `common` together, // then the compiler complains about conflicts. -pub use helpers::abort_internal; -pub use helpers::decode_error_kind; use helpers::err2io; -pub use helpers::hashmap_random_keys; -pub use helpers::is_interrupted; +pub use helpers::{abort_internal, decode_error_kind, hashmap_random_keys, is_interrupted}; mod cabi_realloc; diff --git a/std/src/sys/pal/wasm/alloc.rs b/std/src/sys/pal/wasm/alloc.rs index b74ce0d47425a..ef9d753d7f86c 100644 --- a/std/src/sys/pal/wasm/alloc.rs +++ b/std/src/sys/pal/wasm/alloc.rs @@ -57,10 +57,8 @@ unsafe impl GlobalAlloc for System { #[cfg(target_feature = "atomics")] mod lock { - use crate::sync::atomic::{ - AtomicI32, - Ordering::{Acquire, Release}, - }; + use crate::sync::atomic::AtomicI32; + use crate::sync::atomic::Ordering::{Acquire, Release}; static LOCKED: AtomicI32 = AtomicI32::new(0); diff --git a/std/src/sys/pal/wasm/atomics/futex.rs b/std/src/sys/pal/wasm/atomics/futex.rs index 3584138ca0447..42913a99ee9d6 100644 --- a/std/src/sys/pal/wasm/atomics/futex.rs +++ b/std/src/sys/pal/wasm/atomics/futex.rs @@ -24,7 +24,7 @@ pub fn futex_wait(futex: &AtomicU32, expected: u32, timeout: Option) - } } -/// Wake up one thread that's blocked on futex_wait on this futex. +/// Wakes up one thread that's blocked on `futex_wait` on this futex. /// /// Returns true if this actually woke up such a thread, /// or false if no thread was waiting on this futex. @@ -32,7 +32,7 @@ pub fn futex_wake(futex: &AtomicU32) -> bool { unsafe { wasm::memory_atomic_notify(futex as *const AtomicU32 as *mut i32, 1) > 0 } } -/// Wake up all threads that are waiting on futex_wait on this futex. +/// Wakes up all threads that are waiting on `futex_wait` on this futex. pub fn futex_wake_all(futex: &AtomicU32) { unsafe { wasm::memory_atomic_notify(futex as *const AtomicU32 as *mut i32, i32::MAX as u32); diff --git a/std/src/sys/pal/windows/alloc.rs b/std/src/sys/pal/windows/alloc.rs index 987be6b69eec9..92b68b26032c6 100644 --- a/std/src/sys/pal/windows/alloc.rs +++ b/std/src/sys/pal/windows/alloc.rs @@ -1,10 +1,11 @@ +use core::mem::MaybeUninit; + use crate::alloc::{GlobalAlloc, Layout, System}; use crate::ffi::c_void; use crate::ptr; use crate::sync::atomic::{AtomicPtr, Ordering}; use crate::sys::c::{self, windows_targets}; use crate::sys::common::alloc::{realloc_fallback, MIN_ALIGN}; -use core::mem::MaybeUninit; #[cfg(test)] mod tests; @@ -37,7 +38,7 @@ windows_targets::link!("kernel32.dll" "system" fn GetProcessHeap() -> c::HANDLE) // Note that `dwBytes` is allowed to be zero, contrary to some other allocators. // // See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-heapalloc -windows_targets::link!("kernel32.dll" "system" fn HeapAlloc(hheap: c::HANDLE, dwflags: u32, dwbytes: usize) -> *mut core::ffi::c_void); +windows_targets::link!("kernel32.dll" "system" fn HeapAlloc(hheap: c::HANDLE, dwflags: u32, dwbytes: usize) -> *mut c_void); // Reallocate a block of memory behind a given pointer `lpMem` from a given heap `hHeap`, // to a block of at least `dwBytes` bytes, either shrinking the block in place, @@ -61,9 +62,9 @@ windows_targets::link!("kernel32.dll" "system" fn HeapAlloc(hheap: c::HANDLE, dw windows_targets::link!("kernel32.dll" "system" fn HeapReAlloc( hheap: c::HANDLE, dwflags : u32, - lpmem: *const core::ffi::c_void, + lpmem: *const c_void, dwbytes: usize -) -> *mut core::ffi::c_void); +) -> *mut c_void); // Free a block of memory behind a given pointer `lpMem` from a given heap `hHeap`. // Returns a nonzero value if the operation is successful, and zero if the operation fails. @@ -79,7 +80,7 @@ windows_targets::link!("kernel32.dll" "system" fn HeapReAlloc( // Note that `lpMem` is allowed to be null, which will not cause the operation to fail. // // See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-heapfree -windows_targets::link!("kernel32.dll" "system" fn HeapFree(hheap: c::HANDLE, dwflags: u32, lpmem: *const core::ffi::c_void) -> c::BOOL); +windows_targets::link!("kernel32.dll" "system" fn HeapFree(hheap: c::HANDLE, dwflags: u32, lpmem: *const c_void) -> c::BOOL); // Cached handle to the default heap of the current process. // Either a non-null handle returned by `GetProcessHeap`, or null when not yet initialized or `GetProcessHeap` failed. diff --git a/std/src/sys/pal/windows/args.rs b/std/src/sys/pal/windows/args.rs index 5098c05196e25..66e75a8357149 100644 --- a/std/src/sys/pal/windows/args.rs +++ b/std/src/sys/pal/windows/args.rs @@ -8,8 +8,6 @@ mod tests; use super::os::current_exe; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::num::NonZero; use crate::os::windows::prelude::*; use crate::path::{Path, PathBuf}; @@ -18,9 +16,7 @@ use crate::sys::process::ensure_no_nuls; use crate::sys::{c, to_u16s}; use crate::sys_common::wstr::WStrUnits; use crate::sys_common::AsInner; -use crate::vec; - -use crate::iter; +use crate::{fmt, io, iter, vec}; /// This is the const equivalent to `NonZero::new(n).unwrap()` /// diff --git a/std/src/sys/pal/windows/c.rs b/std/src/sys/pal/windows/c.rs index 296d19a926d96..08b75186aef90 100644 --- a/std/src/sys/pal/windows/c.rs +++ b/std/src/sys/pal/windows/c.rs @@ -4,13 +4,9 @@ #![cfg_attr(test, allow(dead_code))] #![unstable(issue = "none", feature = "windows_c")] #![allow(clippy::style)] -#![allow(unsafe_op_in_unsafe_fn)] -use crate::ffi::CStr; -use crate::mem; -use crate::os::raw::{c_char, c_int, c_uint, c_ulong, c_ushort, c_void}; -use crate::os::windows::io::{AsRawHandle, BorrowedHandle}; -use crate::ptr; +use core::ffi::{c_uint, c_ulong, c_ushort, c_void, CStr}; +use core::{mem, ptr}; pub(super) mod windows_targets; @@ -19,12 +15,6 @@ pub use windows_sys::*; pub type WCHAR = u16; -pub type socklen_t = c_int; -pub type ADDRESS_FAMILY = c_ushort; -pub use FD_SET as fd_set; -pub use LINGER as linger; -pub use TIMEVAL as timeval; - pub const INVALID_HANDLE_VALUE: HANDLE = ::core::ptr::without_provenance_mut(-1i32 as _); // https://learn.microsoft.com/en-us/cpp/c-runtime-library/exit-success-exit-failure?view=msvc-170 @@ -42,20 +32,6 @@ pub const INIT_ONCE_STATIC_INIT: INIT_ONCE = INIT_ONCE { Ptr: ptr::null_mut() }; pub const OBJ_DONT_REPARSE: u32 = windows_sys::OBJ_DONT_REPARSE as u32; pub const FRS_ERR_SYSVOL_POPULATE_TIMEOUT: u32 = windows_sys::FRS_ERR_SYSVOL_POPULATE_TIMEOUT as u32; -pub const AF_INET: c_int = windows_sys::AF_INET as c_int; -pub const AF_INET6: c_int = windows_sys::AF_INET6 as c_int; - -#[repr(C)] -pub struct ip_mreq { - pub imr_multiaddr: in_addr, - pub imr_interface: in_addr, -} - -#[repr(C)] -pub struct ipv6_mreq { - pub ipv6mr_multiaddr: in6_addr, - pub ipv6mr_interface: c_uint, -} // Equivalent to the `NT_SUCCESS` C preprocessor macro. // See: https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/using-ntstatus-values @@ -127,45 +103,6 @@ pub struct MOUNT_POINT_REPARSE_BUFFER { pub PathBuffer: WCHAR, } -#[repr(C)] -pub struct SOCKADDR_STORAGE_LH { - pub ss_family: ADDRESS_FAMILY, - pub __ss_pad1: [c_char; 6], - pub __ss_align: i64, - pub __ss_pad2: [c_char; 112], -} - -#[repr(C)] -#[derive(Copy, Clone)] -pub struct sockaddr_in { - pub sin_family: ADDRESS_FAMILY, - pub sin_port: c_ushort, - pub sin_addr: in_addr, - pub sin_zero: [c_char; 8], -} - -#[repr(C)] -#[derive(Copy, Clone)] -pub struct sockaddr_in6 { - pub sin6_family: ADDRESS_FAMILY, - pub sin6_port: c_ushort, - pub sin6_flowinfo: c_ulong, - pub sin6_addr: in6_addr, - pub sin6_scope_id: c_ulong, -} - -#[repr(C)] -#[derive(Copy, Clone)] -pub struct in_addr { - pub s_addr: u32, -} - -#[repr(C)] -#[derive(Copy, Clone)] -pub struct in6_addr { - pub s6_addr: [u8; 16], -} - // Desktop specific functions & types cfg_if::cfg_if! { if #[cfg(not(target_vendor = "uwp"))] { @@ -173,125 +110,6 @@ if #[cfg(not(target_vendor = "uwp"))] { } } -pub unsafe extern "system" fn WriteFileEx( - hFile: BorrowedHandle<'_>, - lpBuffer: *mut ::core::ffi::c_void, - nNumberOfBytesToWrite: u32, - lpOverlapped: *mut OVERLAPPED, - lpCompletionRoutine: LPOVERLAPPED_COMPLETION_ROUTINE, -) -> BOOL { - windows_sys::WriteFileEx( - hFile.as_raw_handle(), - lpBuffer.cast::(), - nNumberOfBytesToWrite, - lpOverlapped, - lpCompletionRoutine, - ) -} - -pub unsafe extern "system" fn ReadFileEx( - hFile: BorrowedHandle<'_>, - lpBuffer: *mut ::core::ffi::c_void, - nNumberOfBytesToRead: u32, - lpOverlapped: *mut OVERLAPPED, - lpCompletionRoutine: LPOVERLAPPED_COMPLETION_ROUTINE, -) -> BOOL { - windows_sys::ReadFileEx( - hFile.as_raw_handle(), - lpBuffer.cast::(), - nNumberOfBytesToRead, - lpOverlapped, - lpCompletionRoutine, - ) -} - -// POSIX compatibility shims. -pub unsafe fn recv(socket: SOCKET, buf: *mut c_void, len: c_int, flags: c_int) -> c_int { - windows_sys::recv(socket, buf.cast::(), len, flags) -} -pub unsafe fn send(socket: SOCKET, buf: *const c_void, len: c_int, flags: c_int) -> c_int { - windows_sys::send(socket, buf.cast::(), len, flags) -} -pub unsafe fn recvfrom( - socket: SOCKET, - buf: *mut c_void, - len: c_int, - flags: c_int, - addr: *mut SOCKADDR, - addrlen: *mut c_int, -) -> c_int { - windows_sys::recvfrom(socket, buf.cast::(), len, flags, addr, addrlen) -} -pub unsafe fn sendto( - socket: SOCKET, - buf: *const c_void, - len: c_int, - flags: c_int, - addr: *const SOCKADDR, - addrlen: c_int, -) -> c_int { - windows_sys::sendto(socket, buf.cast::(), len, flags, addr, addrlen) -} -pub unsafe fn getaddrinfo( - node: *const c_char, - service: *const c_char, - hints: *const ADDRINFOA, - res: *mut *mut ADDRINFOA, -) -> c_int { - windows_sys::getaddrinfo(node.cast::(), service.cast::(), hints, res) -} - -cfg_if::cfg_if! { -if #[cfg(not(target_vendor = "uwp"))] { -pub unsafe fn NtReadFile( - filehandle: BorrowedHandle<'_>, - event: HANDLE, - apcroutine: PIO_APC_ROUTINE, - apccontext: *mut c_void, - iostatusblock: &mut IO_STATUS_BLOCK, - buffer: *mut crate::mem::MaybeUninit, - length: u32, - byteoffset: Option<&i64>, - key: Option<&u32>, -) -> NTSTATUS { - windows_sys::NtReadFile( - filehandle.as_raw_handle(), - event, - apcroutine, - apccontext, - iostatusblock, - buffer.cast::(), - length, - byteoffset.map(|o| o as *const i64).unwrap_or(ptr::null()), - key.map(|k| k as *const u32).unwrap_or(ptr::null()), - ) -} -pub unsafe fn NtWriteFile( - filehandle: BorrowedHandle<'_>, - event: HANDLE, - apcroutine: PIO_APC_ROUTINE, - apccontext: *mut c_void, - iostatusblock: &mut IO_STATUS_BLOCK, - buffer: *const u8, - length: u32, - byteoffset: Option<&i64>, - key: Option<&u32>, -) -> NTSTATUS { - windows_sys::NtWriteFile( - filehandle.as_raw_handle(), - event, - apcroutine, - apccontext, - iostatusblock, - buffer.cast::(), - length, - byteoffset.map(|o| o as *const i64).unwrap_or(ptr::null()), - key.map(|k| k as *const u32).unwrap_or(ptr::null()), - ) -} -} -} - // Use raw-dylib to import ProcessPrng as we can't rely on there being an import library. cfg_if::cfg_if! { if #[cfg(not(target_vendor = "win7"))] { @@ -315,26 +133,26 @@ compat_fn_with_fallback! { // >= Win10 1607 // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreaddescription pub fn SetThreadDescription(hthread: HANDLE, lpthreaddescription: PCWSTR) -> HRESULT { - SetLastError(ERROR_CALL_NOT_IMPLEMENTED as u32); E_NOTIMPL + unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as u32); E_NOTIMPL } } // >= Win10 1607 // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreaddescription pub fn GetThreadDescription(hthread: HANDLE, lpthreaddescription: *mut PWSTR) -> HRESULT { - SetLastError(ERROR_CALL_NOT_IMPLEMENTED as u32); E_NOTIMPL + unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as u32); E_NOTIMPL } } // >= Win8 / Server 2012 // https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime #[cfg(target_vendor = "win7")] pub fn GetSystemTimePreciseAsFileTime(lpsystemtimeasfiletime: *mut FILETIME) -> () { - GetSystemTimeAsFileTime(lpsystemtimeasfiletime) + unsafe { GetSystemTimeAsFileTime(lpsystemtimeasfiletime) } } // >= Win11 / Server 2022 // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppath2a pub fn GetTempPath2W(bufferlength: u32, buffer: PWSTR) -> u32 { - GetTempPathW(bufferlength, buffer) + unsafe { GetTempPathW(bufferlength, buffer) } } } @@ -367,12 +185,12 @@ extern "system" { compat_fn_optional! { crate::sys::compat::load_synch_functions(); pub fn WaitOnAddress( - address: *const ::core::ffi::c_void, - compareaddress: *const ::core::ffi::c_void, + address: *const c_void, + compareaddress: *const c_void, addresssize: usize, dwmilliseconds: u32 ) -> BOOL; - pub fn WakeByAddressSingle(address: *const ::core::ffi::c_void); + pub fn WakeByAddressSingle(address: *const c_void); } #[cfg(any(target_vendor = "win7", target_vendor = "uwp"))] @@ -419,36 +237,36 @@ compat_fn_with_fallback! { shareaccess: FILE_SHARE_MODE, createdisposition: NTCREATEFILE_CREATE_DISPOSITION, createoptions: NTCREATEFILE_CREATE_OPTIONS, - eabuffer: *const ::core::ffi::c_void, + eabuffer: *const c_void, ealength: u32 ) -> NTSTATUS { STATUS_NOT_IMPLEMENTED } #[cfg(target_vendor = "uwp")] pub fn NtReadFile( - filehandle: BorrowedHandle<'_>, + filehandle: HANDLE, event: HANDLE, apcroutine: PIO_APC_ROUTINE, - apccontext: *mut c_void, - iostatusblock: &mut IO_STATUS_BLOCK, - buffer: *mut crate::mem::MaybeUninit, + apccontext: *const c_void, + iostatusblock: *mut IO_STATUS_BLOCK, + buffer: *mut c_void, length: u32, - byteoffset: Option<&i64>, - key: Option<&u32> + byteoffset: *const i64, + key: *const u32 ) -> NTSTATUS { STATUS_NOT_IMPLEMENTED } #[cfg(target_vendor = "uwp")] pub fn NtWriteFile( - filehandle: BorrowedHandle<'_>, + filehandle: HANDLE, event: HANDLE, apcroutine: PIO_APC_ROUTINE, - apccontext: *mut c_void, - iostatusblock: &mut IO_STATUS_BLOCK, - buffer: *const u8, + apccontext: *const c_void, + iostatusblock: *mut IO_STATUS_BLOCK, + buffer: *const c_void, length: u32, - byteoffset: Option<&i64>, - key: Option<&u32> + byteoffset: *const i64, + key: *const u32 ) -> NTSTATUS { STATUS_NOT_IMPLEMENTED } @@ -457,44 +275,3 @@ compat_fn_with_fallback! { Status as u32 } } - -// # Arm32 shim -// -// AddVectoredExceptionHandler and WSAStartup use platform-specific types. -// However, Microsoft no longer supports thumbv7a so definitions for those targets -// are not included in the win32 metadata. We work around that by defining them here. -// -// Where possible, these definitions should be kept in sync with https://docs.rs/windows-sys -cfg_if::cfg_if! { -if #[cfg(not(target_vendor = "uwp"))] { - #[link(name = "kernel32")] - extern "system" { - pub fn AddVectoredExceptionHandler( - first: u32, - handler: PVECTORED_EXCEPTION_HANDLER, - ) -> *mut c_void; - } - pub type PVECTORED_EXCEPTION_HANDLER = Option< - unsafe extern "system" fn(exceptioninfo: *mut EXCEPTION_POINTERS) -> i32, - >; - #[repr(C)] - pub struct EXCEPTION_POINTERS { - pub ExceptionRecord: *mut EXCEPTION_RECORD, - pub ContextRecord: *mut CONTEXT, - } - #[cfg(target_arch = "arm")] - pub enum CONTEXT {} -}} -// WSAStartup is only redefined here so that we can override WSADATA for Arm32 -windows_targets::link!("ws2_32.dll" "system" fn WSAStartup(wversionrequested: u16, lpwsadata: *mut WSADATA) -> i32); -#[cfg(target_arch = "arm")] -#[repr(C)] -pub struct WSADATA { - pub wVersion: u16, - pub wHighVersion: u16, - pub szDescription: [u8; 257], - pub szSystemStatus: [u8; 129], - pub iMaxSockets: u16, - pub iMaxUdpDg: u16, - pub lpVendorInfo: PSTR, -} diff --git a/std/src/sys/pal/windows/c/bindings.txt b/std/src/sys/pal/windows/c/bindings.txt index 5ad4a3731d822..afacc370c3420 100644 --- a/std/src/sys/pal/windows/c/bindings.txt +++ b/std/src/sys/pal/windows/c/bindings.txt @@ -2059,6 +2059,7 @@ Windows.Win32.Networking.WinSock.SOCK_RDM Windows.Win32.Networking.WinSock.SOCK_SEQPACKET Windows.Win32.Networking.WinSock.SOCK_STREAM Windows.Win32.Networking.WinSock.SOCKADDR +Windows.Win32.Networking.WinSock.SOCKADDR_STORAGE Windows.Win32.Networking.WinSock.SOCKADDR_UN Windows.Win32.Networking.WinSock.SOCKET Windows.Win32.Networking.WinSock.SOCKET_ERROR @@ -2175,6 +2176,7 @@ Windows.Win32.Networking.WinSock.WSARecv Windows.Win32.Networking.WinSock.WSASend Windows.Win32.Networking.WinSock.WSASERVICE_NOT_FOUND Windows.Win32.Networking.WinSock.WSASocketW +Windows.Win32.Networking.WinSock.WSAStartup Windows.Win32.Networking.WinSock.WSASYSCALLFAILURE Windows.Win32.Networking.WinSock.WSASYSNOTREADY Windows.Win32.Networking.WinSock.WSATRY_AGAIN @@ -2419,6 +2421,7 @@ Windows.Win32.System.Console.STD_HANDLE Windows.Win32.System.Console.STD_INPUT_HANDLE Windows.Win32.System.Console.STD_OUTPUT_HANDLE Windows.Win32.System.Console.WriteConsoleW +Windows.Win32.System.Diagnostics.Debug.AddVectoredExceptionHandler Windows.Win32.System.Diagnostics.Debug.ARM64_NT_NEON128 Windows.Win32.System.Diagnostics.Debug.CONTEXT Windows.Win32.System.Diagnostics.Debug.EXCEPTION_RECORD @@ -2462,6 +2465,7 @@ Windows.Win32.System.LibraryLoader.GetProcAddress Windows.Win32.System.Performance.QueryPerformanceCounter Windows.Win32.System.Performance.QueryPerformanceFrequency Windows.Win32.System.Pipes.CreateNamedPipeW +Windows.Win32.System.Pipes.CreatePipe Windows.Win32.System.Pipes.NAMED_PIPE_MODE Windows.Win32.System.Pipes.PIPE_ACCEPT_REMOTE_CLIENTS Windows.Win32.System.Pipes.PIPE_CLIENT_END diff --git a/std/src/sys/pal/windows/c/windows_sys.rs b/std/src/sys/pal/windows/c/windows_sys.rs index fea00fec9ae59..9f22f54819509 100644 --- a/std/src/sys/pal/windows/c/windows_sys.rs +++ b/std/src/sys/pal/windows/c/windows_sys.rs @@ -5,6 +5,7 @@ windows_targets::link!("advapi32.dll" "system" fn OpenProcessToken(processhandle windows_targets::link!("advapi32.dll" "system" "SystemFunction036" fn RtlGenRandom(randombuffer : *mut core::ffi::c_void, randombufferlength : u32) -> BOOLEAN); windows_targets::link!("kernel32.dll" "system" fn AcquireSRWLockExclusive(srwlock : *mut SRWLOCK)); windows_targets::link!("kernel32.dll" "system" fn AcquireSRWLockShared(srwlock : *mut SRWLOCK)); +windows_targets::link!("kernel32.dll" "system" fn AddVectoredExceptionHandler(first : u32, handler : PVECTORED_EXCEPTION_HANDLER) -> *mut core::ffi::c_void); windows_targets::link!("kernel32.dll" "system" fn CancelIo(hfile : HANDLE) -> BOOL); windows_targets::link!("kernel32.dll" "system" fn CloseHandle(hobject : HANDLE) -> BOOL); windows_targets::link!("kernel32.dll" "system" fn CompareStringOrdinal(lpstring1 : PCWSTR, cchcount1 : i32, lpstring2 : PCWSTR, cchcount2 : i32, bignorecase : BOOL) -> COMPARESTRING_RESULT); @@ -14,6 +15,7 @@ windows_targets::link!("kernel32.dll" "system" fn CreateEventW(lpeventattributes windows_targets::link!("kernel32.dll" "system" fn CreateFileW(lpfilename : PCWSTR, dwdesiredaccess : u32, dwsharemode : FILE_SHARE_MODE, lpsecurityattributes : *const SECURITY_ATTRIBUTES, dwcreationdisposition : FILE_CREATION_DISPOSITION, dwflagsandattributes : FILE_FLAGS_AND_ATTRIBUTES, htemplatefile : HANDLE) -> HANDLE); windows_targets::link!("kernel32.dll" "system" fn CreateHardLinkW(lpfilename : PCWSTR, lpexistingfilename : PCWSTR, lpsecurityattributes : *const SECURITY_ATTRIBUTES) -> BOOL); windows_targets::link!("kernel32.dll" "system" fn CreateNamedPipeW(lpname : PCWSTR, dwopenmode : FILE_FLAGS_AND_ATTRIBUTES, dwpipemode : NAMED_PIPE_MODE, nmaxinstances : u32, noutbuffersize : u32, ninbuffersize : u32, ndefaulttimeout : u32, lpsecurityattributes : *const SECURITY_ATTRIBUTES) -> HANDLE); +windows_targets::link!("kernel32.dll" "system" fn CreatePipe(hreadpipe : *mut HANDLE, hwritepipe : *mut HANDLE, lppipeattributes : *const SECURITY_ATTRIBUTES, nsize : u32) -> BOOL); windows_targets::link!("kernel32.dll" "system" fn CreateProcessW(lpapplicationname : PCWSTR, lpcommandline : PWSTR, lpprocessattributes : *const SECURITY_ATTRIBUTES, lpthreadattributes : *const SECURITY_ATTRIBUTES, binherithandles : BOOL, dwcreationflags : PROCESS_CREATION_FLAGS, lpenvironment : *const core::ffi::c_void, lpcurrentdirectory : PCWSTR, lpstartupinfo : *const STARTUPINFOW, lpprocessinformation : *mut PROCESS_INFORMATION) -> BOOL); windows_targets::link!("kernel32.dll" "system" fn CreateSymbolicLinkW(lpsymlinkfilename : PCWSTR, lptargetfilename : PCWSTR, dwflags : SYMBOLIC_LINK_FLAGS) -> BOOLEAN); windows_targets::link!("kernel32.dll" "system" fn CreateThread(lpthreadattributes : *const SECURITY_ATTRIBUTES, dwstacksize : usize, lpstartaddress : LPTHREAD_START_ROUTINE, lpparameter : *const core::ffi::c_void, dwcreationflags : THREAD_CREATION_FLAGS, lpthreadid : *mut u32) -> HANDLE); @@ -113,6 +115,7 @@ windows_targets::link!("ws2_32.dll" "system" fn WSAGetLastError() -> WSA_ERROR); windows_targets::link!("ws2_32.dll" "system" fn WSARecv(s : SOCKET, lpbuffers : *const WSABUF, dwbuffercount : u32, lpnumberofbytesrecvd : *mut u32, lpflags : *mut u32, lpoverlapped : *mut OVERLAPPED, lpcompletionroutine : LPWSAOVERLAPPED_COMPLETION_ROUTINE) -> i32); windows_targets::link!("ws2_32.dll" "system" fn WSASend(s : SOCKET, lpbuffers : *const WSABUF, dwbuffercount : u32, lpnumberofbytessent : *mut u32, dwflags : u32, lpoverlapped : *mut OVERLAPPED, lpcompletionroutine : LPWSAOVERLAPPED_COMPLETION_ROUTINE) -> i32); windows_targets::link!("ws2_32.dll" "system" fn WSASocketW(af : i32, r#type : i32, protocol : i32, lpprotocolinfo : *const WSAPROTOCOL_INFOW, g : u32, dwflags : u32) -> SOCKET); +windows_targets::link!("ws2_32.dll" "system" fn WSAStartup(wversionrequested : u16, lpwsadata : *mut WSADATA) -> i32); windows_targets::link!("ws2_32.dll" "system" fn accept(s : SOCKET, addr : *mut SOCKADDR, addrlen : *mut i32) -> SOCKET); windows_targets::link!("ws2_32.dll" "system" fn bind(s : SOCKET, name : *const SOCKADDR, namelen : i32) -> i32); windows_targets::link!("ws2_32.dll" "system" fn closesocket(s : SOCKET) -> i32); @@ -2283,6 +2286,12 @@ pub type EXCEPTION_DISPOSITION = i32; pub const EXCEPTION_MAXIMUM_PARAMETERS: u32 = 15u32; #[repr(C)] #[derive(Clone, Copy)] +pub struct EXCEPTION_POINTERS { + pub ExceptionRecord: *mut EXCEPTION_RECORD, + pub ContextRecord: *mut CONTEXT, +} +#[repr(C)] +#[derive(Clone, Copy)] pub struct EXCEPTION_RECORD { pub ExceptionCode: NTSTATUS, pub ExceptionFlags: u32, @@ -2859,6 +2868,8 @@ pub type PTIMERAPCROUTINE = Option< dwtimerhighvalue: u32, ), >; +pub type PVECTORED_EXCEPTION_HANDLER = + Option i32>; pub type PWSTR = *mut u16; pub const READ_CONTROL: FILE_ACCESS_RIGHTS = 131072u32; pub const REALTIME_PRIORITY_CLASS: PROCESS_CREATION_FLAGS = 256u32; @@ -2890,6 +2901,14 @@ pub struct SOCKADDR { } #[repr(C)] #[derive(Clone, Copy)] +pub struct SOCKADDR_STORAGE { + pub ss_family: ADDRESS_FAMILY, + pub __ss_pad1: [i8; 6], + pub __ss_align: i64, + pub __ss_pad2: [i8; 112], +} +#[repr(C)] +#[derive(Clone, Copy)] pub struct SOCKADDR_UN { pub sun_family: ADDRESS_FAMILY, pub sun_path: [i8; 108], @@ -3283,5 +3302,19 @@ pub struct XSAVE_FORMAT { pub XmmRegisters: [M128A; 8], pub Reserved4: [u8; 224], } + +#[cfg(target_arch = "arm")] +#[repr(C)] +pub struct WSADATA { + pub wVersion: u16, + pub wHighVersion: u16, + pub szDescription: [u8; 257], + pub szSystemStatus: [u8; 129], + pub iMaxSockets: u16, + pub iMaxUdpDg: u16, + pub lpVendorInfo: PSTR, +} +#[cfg(target_arch = "arm")] +pub enum CONTEXT {} // ignore-tidy-filelength use super::windows_targets; diff --git a/std/src/sys/pal/windows/compat.rs b/std/src/sys/pal/windows/compat.rs index 49fa1603f3e1e..75232dfc0b0f1 100644 --- a/std/src/sys/pal/windows/compat.rs +++ b/std/src/sys/pal/windows/compat.rs @@ -158,8 +158,10 @@ macro_rules! compat_fn_with_fallback { static PTR: AtomicPtr = AtomicPtr::new(load as *mut _); unsafe extern "system" fn load($($argname: $argtype),*) -> $rettype { - let func = load_from_module(Module::new($module)); - func($($argname),*) + unsafe { + let func = load_from_module(Module::new($module)); + func($($argname),*) + } } fn load_from_module(module: Option) -> F { @@ -182,8 +184,10 @@ macro_rules! compat_fn_with_fallback { #[inline(always)] pub unsafe fn call($($argname: $argtype),*) -> $rettype { - let func: F = mem::transmute(PTR.load(Ordering::Relaxed)); - func($($argname),*) + unsafe { + let func: F = mem::transmute(PTR.load(Ordering::Relaxed)); + func($($argname),*) + } } } #[allow(unused)] @@ -225,7 +229,7 @@ macro_rules! compat_fn_optional { } #[inline] pub unsafe extern "system" fn $symbol($($argname: $argtype),*) $(-> $rettype)? { - $symbol::option().unwrap()($($argname),*) + unsafe { $symbol::option().unwrap()($($argname),*) } } )+ ) diff --git a/std/src/sys/pal/windows/fs.rs b/std/src/sys/pal/windows/fs.rs index 48c39392047f0..d99d4931de40f 100644 --- a/std/src/sys/pal/windows/fs.rs +++ b/std/src/sys/pal/windows/fs.rs @@ -1,26 +1,21 @@ use core::ptr::addr_of; -use crate::os::windows::prelude::*; - +use super::api::{self, WinError}; +use super::{to_u16s, IoResult}; use crate::borrow::Cow; use crate::ffi::{c_void, OsStr, OsString}; -use crate::fmt; use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom}; use crate::mem::{self, MaybeUninit}; use crate::os::windows::io::{AsHandle, BorrowedHandle}; +use crate::os::windows::prelude::*; use crate::path::{Path, PathBuf}; -use crate::ptr; -use crate::slice; use crate::sync::Arc; use crate::sys::handle::Handle; +use crate::sys::path::maybe_verbatim; use crate::sys::time::SystemTime; use crate::sys::{c, cvt, Align8}; use crate::sys_common::{AsInner, FromInner, IntoInner}; -use crate::thread; - -use super::api::{self, WinError}; -use super::{to_u16s, IoResult}; -use crate::sys::path::maybe_verbatim; +use crate::{fmt, ptr, slice, thread}; pub struct File { handle: Handle, @@ -32,6 +27,7 @@ pub struct FileAttr { creation_time: c::FILETIME, last_access_time: c::FILETIME, last_write_time: c::FILETIME, + change_time: Option, file_size: u64, reparse_tag: u32, volume_serial_number: Option, @@ -377,6 +373,7 @@ impl File { creation_time: info.ftCreationTime, last_access_time: info.ftLastAccessTime, last_write_time: info.ftLastWriteTime, + change_time: None, // Only available in FILE_BASIC_INFO file_size: (info.nFileSizeLow as u64) | ((info.nFileSizeHigh as u64) << 32), reparse_tag, volume_serial_number: Some(info.dwVolumeSerialNumber), @@ -413,6 +410,10 @@ impl File { dwLowDateTime: info.LastWriteTime as u32, dwHighDateTime: (info.LastWriteTime >> 32) as u32, }, + change_time: Some(c::FILETIME { + dwLowDateTime: info.ChangeTime as u32, + dwHighDateTime: (info.ChangeTime >> 32) as u32, + }), file_size: 0, reparse_tag: 0, volume_serial_number: None, @@ -631,7 +632,7 @@ impl File { Ok(()) } - /// Get only basic file information such as attributes and file times. + /// Gets only basic file information such as attributes and file times. fn basic_info(&self) -> io::Result { unsafe { let mut info: c::FILE_BASIC_INFO = mem::zeroed(); @@ -957,6 +958,10 @@ impl FileAttr { to_u64(&self.creation_time) } + pub fn changed_u64(&self) -> Option { + self.change_time.as_ref().map(|c| to_u64(c)) + } + pub fn volume_serial_number(&self) -> Option { self.volume_serial_number } @@ -976,6 +981,7 @@ impl From for FileAttr { creation_time: wfd.ftCreationTime, last_access_time: wfd.ftLastAccessTime, last_write_time: wfd.ftLastWriteTime, + change_time: None, file_size: ((wfd.nFileSizeHigh as u64) << 32) | (wfd.nFileSizeLow as u64), reparse_tag: if wfd.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 { // reserved unless this is a reparse point diff --git a/std/src/sys/pal/windows/futex.rs b/std/src/sys/pal/windows/futex.rs index c54810e06cdd6..8c5081a607aa3 100644 --- a/std/src/sys/pal/windows/futex.rs +++ b/std/src/sys/pal/windows/futex.rs @@ -1,14 +1,13 @@ -use super::api::{self, WinError}; -use crate::sys::c; -use crate::sys::dur2timeout; use core::ffi::c_void; -use core::mem; -use core::ptr; use core::sync::atomic::{ AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicPtr, AtomicU16, AtomicU32, AtomicU64, AtomicU8, AtomicUsize, }; use core::time::Duration; +use core::{mem, ptr}; + +use super::api::{self, WinError}; +use crate::sys::{c, dur2timeout}; /// An atomic for use as a futex that is at least 8-bits but may be larger. pub type SmallAtomic = AtomicU8; diff --git a/std/src/sys/pal/windows/handle.rs b/std/src/sys/pal/windows/handle.rs index aaa1831dcc24d..82a880faf5fa7 100644 --- a/std/src/sys/pal/windows/handle.rs +++ b/std/src/sys/pal/windows/handle.rs @@ -3,20 +3,20 @@ #[cfg(test)] mod tests; -use crate::cmp; +use core::ffi::c_void; +use core::{cmp, mem, ptr}; + use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut, Read}; -use crate::mem; use crate::os::windows::io::{ AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle, OwnedHandle, RawHandle, }; -use crate::ptr; -use crate::sys::c; -use crate::sys::cvt; +use crate::sys::{c, cvt}; use crate::sys_common::{AsInner, FromInner, IntoInner}; /// An owned container for `HANDLE` object, closing them on Drop. /// /// All methods are inherited through a `Deref` impl to `RawHandle` +#[derive(Debug)] pub struct Handle(OwnedHandle); impl Handle { @@ -136,6 +136,12 @@ impl Handle { } } + pub fn read_to_end(&self, buf: &mut Vec) -> io::Result { + let mut me = self; + + Read::read_to_end(&mut me, buf) + } + pub unsafe fn read_overlapped( &self, buf: &mut [mem::MaybeUninit], @@ -243,15 +249,15 @@ impl Handle { // the provided `len`. let status = unsafe { c::NtReadFile( - self.as_handle(), + self.as_raw_handle(), ptr::null_mut(), None, ptr::null_mut(), &mut io_status, - buf, + buf.cast::(), len, - offset.map(|n| n as _).as_ref(), - None, + offset.as_ref().map(|n| ptr::from_ref(n).cast::()).unwrap_or(ptr::null()), + ptr::null(), ) }; @@ -293,15 +299,15 @@ impl Handle { let len = cmp::min(buf.len(), u32::MAX as usize) as u32; let status = unsafe { c::NtWriteFile( - self.as_handle(), + self.as_raw_handle(), ptr::null_mut(), None, ptr::null_mut(), &mut io_status, - buf.as_ptr(), + buf.as_ptr().cast::(), len, - offset.map(|n| n as _).as_ref(), - None, + offset.as_ref().map(|n| ptr::from_ref(n).cast::()).unwrap_or(ptr::null()), + ptr::null(), ) }; let status = if status == c::STATUS_PENDING { diff --git a/std/src/sys/pal/windows/io.rs b/std/src/sys/pal/windows/io.rs index bf3dfdfdd3e7d..785a3f6768b70 100644 --- a/std/src/sys/pal/windows/io.rs +++ b/std/src/sys/pal/windows/io.rs @@ -1,9 +1,10 @@ +use core::ffi::c_void; + use crate::marker::PhantomData; use crate::mem::size_of; use crate::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle}; use crate::slice; use crate::sys::c; -use core::ffi::c_void; #[derive(Copy, Clone)] #[repr(transparent)] diff --git a/std/src/sys/pal/windows/mod.rs b/std/src/sys/pal/windows/mod.rs index b85a8318bcbbd..6ed77fbc3d445 100644 --- a/std/src/sys/pal/windows/mod.rs +++ b/std/src/sys/pal/windows/mod.rs @@ -1,6 +1,7 @@ #![allow(missing_docs, nonstandard_style)] -#![deny(unsafe_op_in_unsafe_fn)] +#![forbid(unsafe_op_in_unsafe_fn)] +pub use self::rand::hashmap_random_keys; use crate::ffi::{OsStr, OsString}; use crate::io::ErrorKind; use crate::mem::MaybeUninit; @@ -9,8 +10,6 @@ use crate::path::PathBuf; use crate::sys::pal::windows::api::wide_str; use crate::time::Duration; -pub use self::rand::hashmap_random_keys; - #[macro_use] pub mod compat; diff --git a/std/src/sys/pal/windows/net.rs b/std/src/sys/pal/windows/net.rs index d51fb56238f2c..ce995f5ed5af7 100644 --- a/std/src/sys/pal/windows/net.rs +++ b/std/src/sys/pal/windows/net.rs @@ -1,30 +1,113 @@ #![unstable(issue = "none", feature = "windows_net")] -use crate::cmp; +use core::ffi::{c_int, c_long, c_ulong, c_ushort}; + use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut, Read}; -use crate::mem; use crate::net::{Shutdown, SocketAddr}; use crate::os::windows::io::{ AsRawSocket, AsSocket, BorrowedSocket, FromRawSocket, IntoRawSocket, OwnedSocket, RawSocket, }; -use crate::ptr; use crate::sync::OnceLock; -use crate::sys; use crate::sys::c; -use crate::sys_common::net; -use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::sys_common::{net, AsInner, FromInner, IntoInner}; use crate::time::Duration; +use crate::{cmp, mem, ptr, sys}; -use core::ffi::{c_int, c_long, c_ulong, c_ushort}; - +#[allow(non_camel_case_types)] pub type wrlen_t = i32; pub mod netc { - pub use crate::sys::c::ADDRESS_FAMILY as sa_family_t; - pub use crate::sys::c::ADDRINFOA as addrinfo; - pub use crate::sys::c::SOCKADDR as sockaddr; - pub use crate::sys::c::SOCKADDR_STORAGE_LH as sockaddr_storage; - pub use crate::sys::c::*; + //! BSD socket compatibility shim + //! + //! Some Windows API types are not quite what's expected by our cross-platform + //! net code. E.g. naming differences or different pointer types. + + use core::ffi::{c_char, c_int, c_uint, c_ulong, c_ushort, c_void}; + + use crate::sys::c::{self, ADDRESS_FAMILY, ADDRINFOA, SOCKADDR, SOCKET}; + // re-exports from Windows API bindings. + pub use crate::sys::c::{ + bind, connect, freeaddrinfo, getpeername, getsockname, getsockopt, listen, setsockopt, + ADDRESS_FAMILY as sa_family_t, ADDRINFOA as addrinfo, IPPROTO_IP, IPPROTO_IPV6, + IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP, IPV6_MULTICAST_LOOP, IPV6_V6ONLY, + IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP, IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_TTL, + SOCKADDR as sockaddr, SOCKADDR_STORAGE as sockaddr_storage, SOCK_DGRAM, SOCK_STREAM, + SOL_SOCKET, SO_BROADCAST, SO_RCVTIMEO, SO_SNDTIMEO, + }; + + #[allow(non_camel_case_types)] + pub type socklen_t = c_int; + + pub const AF_INET: i32 = c::AF_INET as i32; + pub const AF_INET6: i32 = c::AF_INET6 as i32; + + // The following two structs use a union in the generated bindings but + // our cross-platform code expects a normal field so it's redefined here. + // As a consequence, we also need to redefine other structs that use this struct. + #[repr(C)] + #[derive(Copy, Clone)] + pub struct in_addr { + pub s_addr: u32, + } + + #[repr(C)] + #[derive(Copy, Clone)] + pub struct in6_addr { + pub s6_addr: [u8; 16], + } + + #[repr(C)] + pub struct ip_mreq { + pub imr_multiaddr: in_addr, + pub imr_interface: in_addr, + } + + #[repr(C)] + pub struct ipv6_mreq { + pub ipv6mr_multiaddr: in6_addr, + pub ipv6mr_interface: c_uint, + } + + #[repr(C)] + #[derive(Copy, Clone)] + pub struct sockaddr_in { + pub sin_family: ADDRESS_FAMILY, + pub sin_port: c_ushort, + pub sin_addr: in_addr, + pub sin_zero: [c_char; 8], + } + + #[repr(C)] + #[derive(Copy, Clone)] + pub struct sockaddr_in6 { + pub sin6_family: ADDRESS_FAMILY, + pub sin6_port: c_ushort, + pub sin6_flowinfo: c_ulong, + pub sin6_addr: in6_addr, + pub sin6_scope_id: c_ulong, + } + + pub unsafe fn send(socket: SOCKET, buf: *const c_void, len: c_int, flags: c_int) -> c_int { + unsafe { c::send(socket, buf.cast::(), len, flags) } + } + pub unsafe fn sendto( + socket: SOCKET, + buf: *const c_void, + len: c_int, + flags: c_int, + addr: *const SOCKADDR, + addrlen: c_int, + ) -> c_int { + unsafe { c::sendto(socket, buf.cast::(), len, flags, addr, addrlen) } + } + pub unsafe fn getaddrinfo( + node: *const c_char, + service: *const c_char, + hints: *const ADDRINFOA, + res: *mut *mut ADDRINFOA, + ) -> c_int { + unsafe { c::getaddrinfo(node.cast::(), service.cast::(), hints, res) } + } } pub struct Socket(OwnedSocket); @@ -102,8 +185,8 @@ where impl Socket { pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result { let family = match *addr { - SocketAddr::V4(..) => c::AF_INET, - SocketAddr::V6(..) => c::AF_INET6, + SocketAddr::V4(..) => netc::AF_INET, + SocketAddr::V6(..) => netc::AF_INET6, }; let socket = unsafe { c::WSASocketW( @@ -157,7 +240,7 @@ impl Socket { return Err(io::Error::ZERO_TIMEOUT); } - let mut timeout = c::timeval { + let mut timeout = c::TIMEVAL { tv_sec: cmp::min(timeout.as_secs(), c_long::MAX as u64) as c_long, tv_usec: timeout.subsec_micros() as c_long, }; @@ -167,7 +250,7 @@ impl Socket { } let fds = { - let mut fds = unsafe { mem::zeroed::() }; + let mut fds = unsafe { mem::zeroed::() }; fds.fd_count = 1; fds.fd_array[0] = self.as_raw(); fds @@ -295,8 +378,8 @@ impl Socket { buf: &mut [u8], flags: c_int, ) -> io::Result<(usize, SocketAddr)> { - let mut storage = unsafe { mem::zeroed::() }; - let mut addrlen = mem::size_of_val(&storage) as c::socklen_t; + let mut storage = unsafe { mem::zeroed::() }; + let mut addrlen = mem::size_of_val(&storage) as netc::socklen_t; let length = cmp::min(buf.len(), ::MAX as usize) as wrlen_t; // On unix when a socket is shut down all further reads return 0, so we @@ -399,7 +482,7 @@ impl Socket { } pub fn set_linger(&self, linger: Option) -> io::Result<()> { - let linger = c::linger { + let linger = c::LINGER { l_onoff: linger.is_some() as c_ushort, l_linger: linger.unwrap_or_default().as_secs() as c_ushort, }; @@ -408,7 +491,7 @@ impl Socket { } pub fn linger(&self) -> io::Result> { - let val: c::linger = net::getsockopt(self, c::SOL_SOCKET, c::SO_LINGER)?; + let val: c::LINGER = net::getsockopt(self, c::SOL_SOCKET, c::SO_LINGER)?; Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64))) } diff --git a/std/src/sys/pal/windows/os.rs b/std/src/sys/pal/windows/os.rs index f1f4d3a5d26ef..5242bc9da31fe 100644 --- a/std/src/sys/pal/windows/os.rs +++ b/std/src/sys/pal/windows/os.rs @@ -5,20 +5,15 @@ #[cfg(test)] mod tests; -use crate::os::windows::prelude::*; - +use super::api::{self, WinError}; +use super::to_u16s; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::os::windows::ffi::EncodeWide; +use crate::os::windows::prelude::*; use crate::path::{self, PathBuf}; -use crate::ptr; -use crate::slice; use crate::sys::{c, cvt}; - -use super::api::{self, WinError}; -use super::to_u16s; +use crate::{fmt, io, ptr, slice}; pub fn errno() -> i32 { api::get_last_error().code as i32 diff --git a/std/src/sys/pal/windows/pipe.rs b/std/src/sys/pal/windows/pipe.rs index 7a309b9638bd2..7d1b5aca1d5fe 100644 --- a/std/src/sys/pal/windows/pipe.rs +++ b/std/src/sys/pal/windows/pipe.rs @@ -1,18 +1,15 @@ -use crate::os::windows::prelude::*; - use crate::ffi::OsStr; -use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read}; -use crate::mem; +use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; +use crate::os::windows::prelude::*; use crate::path::Path; -use crate::ptr; use crate::sync::atomic::AtomicUsize; use crate::sync::atomic::Ordering::Relaxed; -use crate::sys::c; use crate::sys::fs::{File, OpenOptions}; use crate::sys::handle::Handle; -use crate::sys::hashmap_random_keys; use crate::sys::pal::windows::api::{self, WinError}; +use crate::sys::{c, hashmap_random_keys}; use crate::sys_common::{FromInner, IntoInner}; +use crate::{mem, ptr}; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes @@ -181,7 +178,7 @@ pub fn spawn_pipe_relay( their_handle_inheritable: bool, ) -> io::Result { // We need this handle to live for the lifetime of the thread spawned below. - let source = source.duplicate()?; + let source = source.try_clone()?; // create a new pair of anon pipes. let Pipes { theirs, ours } = anon_pipe(ours_readable, their_handle_inheritable)?; @@ -221,15 +218,6 @@ fn random_number() -> usize { } } -// Abstracts over `ReadFileEx` and `WriteFileEx` -type AlertableIoFn = unsafe extern "system" fn( - BorrowedHandle<'_>, - *mut core::ffi::c_void, - u32, - *mut c::OVERLAPPED, - c::LPOVERLAPPED_COMPLETION_ROUTINE, -) -> c::BOOL; - impl AnonPipe { pub fn handle(&self) -> &Handle { &self.inner @@ -237,14 +225,18 @@ impl AnonPipe { pub fn into_handle(self) -> Handle { self.inner } - fn duplicate(&self) -> io::Result { + + pub fn try_clone(&self) -> io::Result { self.inner.duplicate(0, false, c::DUPLICATE_SAME_ACCESS).map(|inner| AnonPipe { inner }) } pub fn read(&self, buf: &mut [u8]) -> io::Result { let result = unsafe { let len = crate::cmp::min(buf.len(), u32::MAX as usize) as u32; - self.alertable_io_internal(c::ReadFileEx, buf.as_mut_ptr() as _, len) + let ptr = buf.as_mut_ptr(); + self.alertable_io_internal(|overlapped, callback| { + c::ReadFileEx(self.inner.as_raw_handle(), ptr, len, overlapped, callback) + }) }; match result { @@ -260,7 +252,10 @@ impl AnonPipe { pub fn read_buf(&self, mut buf: BorrowedCursor<'_>) -> io::Result<()> { let result = unsafe { let len = crate::cmp::min(buf.capacity(), u32::MAX as usize) as u32; - self.alertable_io_internal(c::ReadFileEx, buf.as_mut().as_mut_ptr() as _, len) + let ptr = buf.as_mut().as_mut_ptr().cast::(); + self.alertable_io_internal(|overlapped, callback| { + c::ReadFileEx(self.inner.as_raw_handle(), ptr, len, overlapped, callback) + }) }; match result { @@ -295,7 +290,9 @@ impl AnonPipe { pub fn write(&self, buf: &[u8]) -> io::Result { unsafe { let len = crate::cmp::min(buf.len(), u32::MAX as usize) as u32; - self.alertable_io_internal(c::WriteFileEx, buf.as_ptr() as _, len) + self.alertable_io_internal(|overlapped, callback| { + c::WriteFileEx(self.inner.as_raw_handle(), buf.as_ptr(), len, overlapped, callback) + }) } } @@ -323,12 +320,9 @@ impl AnonPipe { /// [`ReadFileEx`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-readfileex /// [`WriteFileEx`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-writefileex /// [Asynchronous Procedure Call]: https://docs.microsoft.com/en-us/windows/win32/sync/asynchronous-procedure-calls - #[allow(unsafe_op_in_unsafe_fn)] unsafe fn alertable_io_internal( &self, - io: AlertableIoFn, - buf: *mut core::ffi::c_void, - len: u32, + io: impl FnOnce(&mut c::OVERLAPPED, c::LPOVERLAPPED_COMPLETION_ROUTINE) -> c::BOOL, ) -> io::Result { // Use "alertable I/O" to synchronize the pipe I/O. // This has four steps. @@ -366,20 +360,25 @@ impl AnonPipe { lpOverlapped: *mut c::OVERLAPPED, ) { // Set `async_result` using a pointer smuggled through `hEvent`. - let result = - AsyncResult { error: dwErrorCode, transferred: dwNumberOfBytesTransferred }; - *(*lpOverlapped).hEvent.cast::>() = Some(result); + // SAFETY: + // At this point, the OVERLAPPED struct will have been written to by the OS, + // except for our `hEvent` field which we set to a valid AsyncResult pointer (see below) + unsafe { + let result = + AsyncResult { error: dwErrorCode, transferred: dwNumberOfBytesTransferred }; + *(*lpOverlapped).hEvent.cast::>() = Some(result); + } } // STEP 1: Start the I/O operation. - let mut overlapped: c::OVERLAPPED = crate::mem::zeroed(); + let mut overlapped: c::OVERLAPPED = unsafe { crate::mem::zeroed() }; // `hEvent` is unused by `ReadFileEx` and `WriteFileEx`. // Therefore the documentation suggests using it to smuggle a pointer to the callback. overlapped.hEvent = core::ptr::addr_of_mut!(async_result) as *mut _; // Asynchronous read of the pipe. // If successful, `callback` will be called once it completes. - let result = io(self.inner.as_handle(), buf, len, &mut overlapped, Some(callback)); + let result = io(&mut overlapped, Some(callback)); if result == c::FALSE { // We can return here because the call failed. // After this we must not return until the I/O completes. @@ -390,7 +389,7 @@ impl AnonPipe { let result = loop { // STEP 2: Enter an alertable state. // The second parameter of `SleepEx` is used to make this sleep alertable. - c::SleepEx(c::INFINITE, c::TRUE); + unsafe { c::SleepEx(c::INFINITE, c::TRUE) }; if let Some(result) = async_result { break result; } diff --git a/std/src/sys/pal/windows/process.rs b/std/src/sys/pal/windows/process.rs index 76d2cb77d474c..06eae5a07b068 100644 --- a/std/src/sys/pal/windows/process.rs +++ b/std/src/sys/pal/windows/process.rs @@ -3,35 +3,28 @@ #[cfg(test)] mod tests; -use crate::cmp; +use core::ffi::c_void; + +use super::api::{self, WinError}; use crate::collections::BTreeMap; -use crate::env; use crate::env::consts::{EXE_EXTENSION, EXE_SUFFIX}; use crate::ffi::{OsStr, OsString}; -use crate::fmt; use crate::io::{self, Error, ErrorKind}; -use crate::mem; use crate::mem::MaybeUninit; use crate::num::NonZero; use crate::os::windows::ffi::{OsStrExt, OsStringExt}; use crate::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle}; use crate::path::{Path, PathBuf}; -use crate::ptr; use crate::sync::Mutex; use crate::sys::args::{self, Arg}; use crate::sys::c::{self, EXIT_FAILURE, EXIT_SUCCESS}; -use crate::sys::cvt; use crate::sys::fs::{File, OpenOptions}; use crate::sys::handle::Handle; -use crate::sys::path; use crate::sys::pipe::{self, AnonPipe}; -use crate::sys::stdio; +use crate::sys::{cvt, path, stdio}; use crate::sys_common::process::{CommandEnv, CommandEnvs}; use crate::sys_common::IntoInner; - -use core::ffi::c_void; - -use super::api::{self, WinError}; +use crate::{cmp, env, fmt, mem, ptr}; //////////////////////////////////////////////////////////////////////////////// // Command @@ -549,7 +542,7 @@ where None } -/// Check if a file exists without following symlinks. +/// Checks if a file exists without following symlinks. fn program_exists(path: &Path) -> Option> { unsafe { let path = args::to_user_path(path).ok()?; @@ -571,7 +564,7 @@ impl Stdio { Ok(io) => unsafe { let io = Handle::from_raw_handle(io); let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS); - io.into_raw_handle(); + let _ = io.into_raw_handle(); // Don't close the handle ret }, // If no stdio handle is available, then propagate the null value. diff --git a/std/src/sys/pal/windows/process/tests.rs b/std/src/sys/pal/windows/process/tests.rs index 3fc0c75240c33..65325fa64a077 100644 --- a/std/src/sys/pal/windows/process/tests.rs +++ b/std/src/sys/pal/windows/process/tests.rs @@ -1,5 +1,4 @@ -use super::make_command_line; -use super::Arg; +use super::{make_command_line, Arg}; use crate::env; use crate::ffi::{OsStr, OsString}; use crate::process::Command; diff --git a/std/src/sys/pal/windows/stdio.rs b/std/src/sys/pal/windows/stdio.rs index c6a21665157d7..575f2250eb91c 100644 --- a/std/src/sys/pal/windows/stdio.rs +++ b/std/src/sys/pal/windows/stdio.rs @@ -1,16 +1,13 @@ #![unstable(issue = "none", feature = "windows_stdio")] +use core::str::utf8_char_width; + use super::api::{self, WinError}; -use crate::cmp; -use crate::io; use crate::mem::MaybeUninit; use crate::os::windows::io::{FromRawHandle, IntoRawHandle}; -use crate::ptr; -use crate::str; -use crate::sys::c; -use crate::sys::cvt; use crate::sys::handle::Handle; -use core::str::utf8_char_width; +use crate::sys::{c, cvt}; +use crate::{cmp, io, ptr, str}; #[cfg(test)] mod tests; @@ -97,7 +94,7 @@ fn write(handle_id: u32, data: &[u8], incomplete_utf8: &mut IncompleteUtf8) -> i unsafe { let handle = Handle::from_raw_handle(handle); let ret = handle.write(data); - handle.into_raw_handle(); // Don't close the handle + let _ = handle.into_raw_handle(); // Don't close the handle return ret; } } @@ -246,7 +243,7 @@ impl io::Read for Stdin { unsafe { let handle = Handle::from_raw_handle(handle); let ret = handle.read(buf); - handle.into_raw_handle(); // Don't close the handle + let _ = handle.into_raw_handle(); // Don't close the handle return ret; } } diff --git a/std/src/sys/pal/windows/thread.rs b/std/src/sys/pal/windows/thread.rs index 668a3c05e20be..28bce529cd991 100644 --- a/std/src/sys/pal/windows/thread.rs +++ b/std/src/sys/pal/windows/thread.rs @@ -1,18 +1,15 @@ +use core::ffi::c_void; + +use super::time::WaitableTimer; +use super::to_u16s; use crate::ffi::CStr; -use crate::io; use crate::num::NonZero; -use crate::os::windows::io::AsRawHandle; -use crate::os::windows::io::HandleOrNull; -use crate::ptr; -use crate::sys::c; +use crate::os::windows::io::{AsRawHandle, HandleOrNull}; use crate::sys::handle::Handle; -use crate::sys::stack_overflow; +use crate::sys::{c, stack_overflow}; use crate::sys_common::FromInner; use crate::time::Duration; -use core::ffi::c_void; - -use super::time::WaitableTimer; -use super::to_u16s; +use crate::{io, ptr}; pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024; diff --git a/std/src/sys/pal/windows/time.rs b/std/src/sys/pal/windows/time.rs index b853daeffebd7..d9010e3996109 100644 --- a/std/src/sys/pal/windows/time.rs +++ b/std/src/sys/pal/windows/time.rs @@ -1,13 +1,12 @@ +use core::hash::{Hash, Hasher}; +use core::ops::Neg; + use crate::cmp::Ordering; -use crate::fmt; -use crate::mem; use crate::ptr::null; use crate::sys::c; use crate::sys_common::IntoInner; use crate::time::Duration; - -use core::hash::{Hash, Hasher}; -use core::ops::Neg; +use crate::{fmt, mem}; const NANOS_PER_SEC: u64 = 1_000_000_000; const INTERVALS_PER_SEC: u64 = NANOS_PER_SEC / 100; @@ -166,8 +165,7 @@ fn intervals2dur(intervals: u64) -> Duration { mod perf_counter { use super::NANOS_PER_SEC; use crate::sync::atomic::{AtomicU64, Ordering}; - use crate::sys::c; - use crate::sys::cvt; + use crate::sys::{c, cvt}; use crate::sys_common::mul_div_u64; use crate::time::Duration; @@ -230,7 +228,7 @@ pub(super) struct WaitableTimer { handle: c::HANDLE, } impl WaitableTimer { - /// Create a high-resolution timer. Will fail before Windows 10, version 1803. + /// Creates a high-resolution timer. Will fail before Windows 10, version 1803. pub fn high_resolution() -> Result { let handle = unsafe { c::CreateWaitableTimerExW( diff --git a/std/src/sys/pal/xous/alloc.rs b/std/src/sys/pal/xous/alloc.rs index 601411173aacb..9ea43445d0206 100644 --- a/std/src/sys/pal/xous/alloc.rs +++ b/std/src/sys/pal/xous/alloc.rs @@ -46,10 +46,8 @@ unsafe impl GlobalAlloc for System { } mod lock { - use crate::sync::atomic::{ - AtomicI32, - Ordering::{Acquire, Release}, - }; + use crate::sync::atomic::AtomicI32; + use crate::sync::atomic::Ordering::{Acquire, Release}; static LOCKED: AtomicI32 = AtomicI32::new(0); diff --git a/std/src/sys/pal/xous/net/dns.rs b/std/src/sys/pal/xous/net/dns.rs index 63056324bfbd9..50efe978c4a83 100644 --- a/std/src/sys/pal/xous/net/dns.rs +++ b/std/src/sys/pal/xous/net/dns.rs @@ -1,8 +1,9 @@ +use core::convert::{TryFrom, TryInto}; + use crate::io; use crate::net::{Ipv4Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; use crate::os::xous::ffi::lend_mut; use crate::os::xous::services::{dns_server, DnsLendMut}; -use core::convert::{TryFrom, TryInto}; pub struct DnsError { pub code: u8, diff --git a/std/src/sys/pal/xous/net/tcplistener.rs b/std/src/sys/pal/xous/net/tcplistener.rs index 47305013083c8..ddfb289162b69 100644 --- a/std/src/sys/pal/xous/net/tcplistener.rs +++ b/std/src/sys/pal/xous/net/tcplistener.rs @@ -1,11 +1,11 @@ +use core::convert::TryInto; +use core::sync::atomic::{AtomicBool, AtomicU16, AtomicUsize, Ordering}; + use super::*; -use crate::fmt; -use crate::io; use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use crate::os::xous::services; use crate::sync::Arc; -use core::convert::TryInto; -use core::sync::atomic::{AtomicBool, AtomicU16, AtomicUsize, Ordering}; +use crate::{fmt, io}; macro_rules! unimpl { () => { diff --git a/std/src/sys/pal/xous/net/tcpstream.rs b/std/src/sys/pal/xous/net/tcpstream.rs index 0ad8811071111..03442cf2fcdfd 100644 --- a/std/src/sys/pal/xous/net/tcpstream.rs +++ b/std/src/sys/pal/xous/net/tcpstream.rs @@ -1,3 +1,5 @@ +use core::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}; + use super::*; use crate::fmt; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; @@ -5,7 +7,6 @@ use crate::net::{IpAddr, Ipv4Addr, Shutdown, SocketAddr, SocketAddrV4, SocketAdd use crate::os::xous::services; use crate::sync::Arc; use crate::time::Duration; -use core::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}; macro_rules! unimpl { () => { diff --git a/std/src/sys/pal/xous/net/udp.rs b/std/src/sys/pal/xous/net/udp.rs index 3d0522b25f3fb..de5133280ba9d 100644 --- a/std/src/sys/pal/xous/net/udp.rs +++ b/std/src/sys/pal/xous/net/udp.rs @@ -1,13 +1,13 @@ +use core::convert::TryInto; +use core::sync::atomic::{AtomicUsize, Ordering}; + use super::*; use crate::cell::Cell; -use crate::fmt; -use crate::io; use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use crate::os::xous::services; use crate::sync::Arc; use crate::time::Duration; -use core::convert::TryInto; -use core::sync::atomic::{AtomicUsize, Ordering}; +use crate::{fmt, io}; macro_rules! unimpl { () => { diff --git a/std/src/sys/pal/xous/os.rs b/std/src/sys/pal/xous/os.rs index 9be09eed62989..8f8f35428c487 100644 --- a/std/src/sys/pal/xous/os.rs +++ b/std/src/sys/pal/xous/os.rs @@ -1,11 +1,10 @@ use super::unsupported; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::os::xous::ffi::Error as XousError; use crate::path::{self, PathBuf}; +use crate::{fmt, io}; #[cfg(not(test))] #[cfg(feature = "panic_unwind")] diff --git a/std/src/sys/pal/xous/thread.rs b/std/src/sys/pal/xous/thread.rs index 279f24f9ee8e4..a95b0aa14d255 100644 --- a/std/src/sys/pal/xous/thread.rs +++ b/std/src/sys/pal/xous/thread.rs @@ -1,3 +1,5 @@ +use core::arch::asm; + use crate::ffi::CStr; use crate::io; use crate::num::NonZero; @@ -7,7 +9,6 @@ use crate::os::xous::ffi::{ }; use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; use crate::time::Duration; -use core::arch::asm; pub struct Thread { tid: ThreadId, diff --git a/std/src/sys/pal/xous/time.rs b/std/src/sys/pal/xous/time.rs index 4e4ae67efffa2..ae8be81c0b7c5 100644 --- a/std/src/sys/pal/xous/time.rs +++ b/std/src/sys/pal/xous/time.rs @@ -1,7 +1,7 @@ use crate::os::xous::ffi::blocking_scalar; -use crate::os::xous::services::{ - systime_server, ticktimer_server, SystimeScalar::GetUtcTimeMs, TicktimerScalar::ElapsedMs, -}; +use crate::os::xous::services::SystimeScalar::GetUtcTimeMs; +use crate::os::xous::services::TicktimerScalar::ElapsedMs; +use crate::os::xous::services::{systime_server, ticktimer_server}; use crate::time::Duration; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] diff --git a/std/src/sys/pal/zkvm/os.rs b/std/src/sys/pal/zkvm/os.rs index e7d6cd52a258e..68d91a123acd4 100644 --- a/std/src/sys/pal/zkvm/os.rs +++ b/std/src/sys/pal/zkvm/os.rs @@ -1,12 +1,11 @@ use super::{abi, unsupported, WORD_SIZE}; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::path::{self, PathBuf}; use crate::sys::os_str; use crate::sys_common::FromInner; +use crate::{fmt, io}; pub fn errno() -> i32 { 0 diff --git a/std/src/sys/pal/zkvm/stdio.rs b/std/src/sys/pal/zkvm/stdio.rs index e771ed0de28db..dd218c8894ca5 100644 --- a/std/src/sys/pal/zkvm/stdio.rs +++ b/std/src/sys/pal/zkvm/stdio.rs @@ -1,4 +1,5 @@ -use super::{abi, abi::fileno}; +use super::abi; +use super::abi::fileno; use crate::io; pub struct Stdin; diff --git a/std/src/sys/path/unix.rs b/std/src/sys/path/unix.rs index 837f68d3eaff7..2a7c025c3c46a 100644 --- a/std/src/sys/path/unix.rs +++ b/std/src/sys/path/unix.rs @@ -1,7 +1,6 @@ -use crate::env; use crate::ffi::OsStr; -use crate::io; use crate::path::{Path, PathBuf, Prefix}; +use crate::{env, io}; #[inline] pub fn is_sep_byte(b: u8) -> bool { diff --git a/std/src/sys/path/unsupported_backslash.rs b/std/src/sys/path/unsupported_backslash.rs index 7045c9be25b08..855f443678c6c 100644 --- a/std/src/sys/path/unsupported_backslash.rs +++ b/std/src/sys/path/unsupported_backslash.rs @@ -1,3 +1,4 @@ +#![forbid(unsafe_op_in_unsafe_fn)] use crate::ffi::OsStr; use crate::io; use crate::path::{Path, PathBuf, Prefix}; diff --git a/std/src/sys/path/windows.rs b/std/src/sys/path/windows.rs index cebc791023115..21841eb18cc0e 100644 --- a/std/src/sys/path/windows.rs +++ b/std/src/sys/path/windows.rs @@ -1,8 +1,7 @@ use crate::ffi::{OsStr, OsString}; -use crate::io; use crate::path::{Path, PathBuf, Prefix}; -use crate::ptr; use crate::sys::pal::{c, fill_utf16_buf, os2path, to_u16s}; +use crate::{io, ptr}; #[cfg(test)] mod tests; @@ -218,7 +217,7 @@ pub(crate) fn maybe_verbatim(path: &Path) -> io::Result> { get_long_path(path, true) } -/// Get a normalized absolute path that can bypass path length limits. +/// Gets a normalized absolute path that can bypass path length limits. /// /// Setting prefer_verbatim to true suggests a stronger preference for verbatim /// paths even when not strictly necessary. This allows the Windows API to avoid diff --git a/std/src/sys/personality/dwarf/eh.rs b/std/src/sys/personality/dwarf/eh.rs index ff88ef4e0e1d0..c37c3e442aea6 100644 --- a/std/src/sys/personality/dwarf/eh.rs +++ b/std/src/sys/personality/dwarf/eh.rs @@ -12,9 +12,9 @@ #![allow(non_upper_case_globals)] #![allow(unused)] +use core::{mem, ptr}; + use super::DwarfReader; -use core::mem; -use core::ptr; pub const DW_EH_PE_omit: u8 = 0xFF; pub const DW_EH_PE_absptr: u8 = 0x00; @@ -70,45 +70,51 @@ pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>) -> Result let func_start = context.func_start; let mut reader = DwarfReader::new(lsda); - - let start_encoding = reader.read::(); - // base address for landing pad offsets - let lpad_base = if start_encoding != DW_EH_PE_omit { - read_encoded_pointer(&mut reader, context, start_encoding)? - } else { - func_start + let lpad_base = unsafe { + let start_encoding = reader.read::(); + // base address for landing pad offsets + if start_encoding != DW_EH_PE_omit { + read_encoded_pointer(&mut reader, context, start_encoding)? + } else { + func_start + } }; + let call_site_encoding = unsafe { + let ttype_encoding = reader.read::(); + if ttype_encoding != DW_EH_PE_omit { + // Rust doesn't analyze exception types, so we don't care about the type table + reader.read_uleb128(); + } - let ttype_encoding = reader.read::(); - if ttype_encoding != DW_EH_PE_omit { - // Rust doesn't analyze exception types, so we don't care about the type table - reader.read_uleb128(); - } - - let call_site_encoding = reader.read::(); - let call_site_table_length = reader.read_uleb128(); - let action_table = reader.ptr.add(call_site_table_length as usize); + reader.read::() + }; + let action_table = unsafe { + let call_site_table_length = reader.read_uleb128(); + reader.ptr.add(call_site_table_length as usize) + }; let ip = context.ip; if !USING_SJLJ_EXCEPTIONS { // read the callsite table while reader.ptr < action_table { - // these are offsets rather than pointers; - let cs_start = read_encoded_offset(&mut reader, call_site_encoding)?; - let cs_len = read_encoded_offset(&mut reader, call_site_encoding)?; - let cs_lpad = read_encoded_offset(&mut reader, call_site_encoding)?; - let cs_action_entry = reader.read_uleb128(); - // Callsite table is sorted by cs_start, so if we've passed the ip, we - // may stop searching. - if ip < func_start.wrapping_add(cs_start) { - break; - } - if ip < func_start.wrapping_add(cs_start + cs_len) { - if cs_lpad == 0 { - return Ok(EHAction::None); - } else { - let lpad = lpad_base.wrapping_add(cs_lpad); - return Ok(interpret_cs_action(action_table, cs_action_entry, lpad)); + unsafe { + // these are offsets rather than pointers; + let cs_start = read_encoded_offset(&mut reader, call_site_encoding)?; + let cs_len = read_encoded_offset(&mut reader, call_site_encoding)?; + let cs_lpad = read_encoded_offset(&mut reader, call_site_encoding)?; + let cs_action_entry = reader.read_uleb128(); + // Callsite table is sorted by cs_start, so if we've passed the ip, we + // may stop searching. + if ip < func_start.wrapping_add(cs_start) { + break; + } + if ip < func_start.wrapping_add(cs_start + cs_len) { + if cs_lpad == 0 { + return Ok(EHAction::None); + } else { + let lpad = lpad_base.wrapping_add(cs_lpad); + return Ok(interpret_cs_action(action_table, cs_action_entry, lpad)); + } } } } @@ -125,15 +131,15 @@ pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>) -> Result } let mut idx = ip.addr(); loop { - let cs_lpad = reader.read_uleb128(); - let cs_action_entry = reader.read_uleb128(); + let cs_lpad = unsafe { reader.read_uleb128() }; + let cs_action_entry = unsafe { reader.read_uleb128() }; idx -= 1; if idx == 0 { // Can never have null landing pad for sjlj -- that would have // been indicated by a -1 call site index. // FIXME(strict provenance) let lpad = ptr::with_exposed_provenance((cs_lpad + 1) as usize); - return Ok(interpret_cs_action(action_table, cs_action_entry, lpad)); + return Ok(unsafe { interpret_cs_action(action_table, cs_action_entry, lpad) }); } } } @@ -151,9 +157,9 @@ unsafe fn interpret_cs_action( } else { // If lpad != 0 and cs_action_entry != 0, we have to check ttype_index. // If ttype_index == 0 under the condition, we take cleanup action. - let action_record = action_table.offset(cs_action_entry as isize - 1); + let action_record = unsafe { action_table.offset(cs_action_entry as isize - 1) }; let mut action_reader = DwarfReader::new(action_record); - let ttype_index = action_reader.read_sleb128(); + let ttype_index = unsafe { action_reader.read_sleb128() }; if ttype_index == 0 { EHAction::Cleanup(lpad) } else if ttype_index > 0 { @@ -170,7 +176,7 @@ fn round_up(unrounded: usize, align: usize) -> Result { if align.is_power_of_two() { Ok((unrounded + align - 1) & !(align - 1)) } else { Err(()) } } -/// Read a offset (`usize`) from `reader` whose encoding is described by `encoding`. +/// Reads an offset (`usize`) from `reader` whose encoding is described by `encoding`. /// /// `encoding` must be a [DWARF Exception Header Encoding as described by the LSB spec][LSB-dwarf-ext]. /// In addition the upper ("application") part must be zero. @@ -186,23 +192,25 @@ unsafe fn read_encoded_offset(reader: &mut DwarfReader, encoding: u8) -> Result< if encoding == DW_EH_PE_omit || encoding & 0xF0 != 0 { return Err(()); } - let result = match encoding & 0x0F { - // despite the name, LLVM also uses absptr for offsets instead of pointers - DW_EH_PE_absptr => reader.read::(), - DW_EH_PE_uleb128 => reader.read_uleb128() as usize, - DW_EH_PE_udata2 => reader.read::() as usize, - DW_EH_PE_udata4 => reader.read::() as usize, - DW_EH_PE_udata8 => reader.read::() as usize, - DW_EH_PE_sleb128 => reader.read_sleb128() as usize, - DW_EH_PE_sdata2 => reader.read::() as usize, - DW_EH_PE_sdata4 => reader.read::() as usize, - DW_EH_PE_sdata8 => reader.read::() as usize, - _ => return Err(()), + let result = unsafe { + match encoding & 0x0F { + // despite the name, LLVM also uses absptr for offsets instead of pointers + DW_EH_PE_absptr => reader.read::(), + DW_EH_PE_uleb128 => reader.read_uleb128() as usize, + DW_EH_PE_udata2 => reader.read::() as usize, + DW_EH_PE_udata4 => reader.read::() as usize, + DW_EH_PE_udata8 => reader.read::() as usize, + DW_EH_PE_sleb128 => reader.read_sleb128() as usize, + DW_EH_PE_sdata2 => reader.read::() as usize, + DW_EH_PE_sdata4 => reader.read::() as usize, + DW_EH_PE_sdata8 => reader.read::() as usize, + _ => return Err(()), + } }; Ok(result) } -/// Read a pointer from `reader` whose encoding is described by `encoding`. +/// Reads a pointer from `reader` whose encoding is described by `encoding`. /// /// `encoding` must be a [DWARF Exception Header Encoding as described by the LSB spec][LSB-dwarf-ext]. /// @@ -250,14 +258,14 @@ unsafe fn read_encoded_pointer( if encoding & 0x0F != DW_EH_PE_absptr { return Err(()); } - reader.read::<*const u8>() + unsafe { reader.read::<*const u8>() } } else { - let offset = read_encoded_offset(reader, encoding & 0x0F)?; + let offset = unsafe { read_encoded_offset(reader, encoding & 0x0F)? }; base_ptr.wrapping_add(offset) }; if encoding & DW_EH_PE_indirect != 0 { - ptr = *(ptr.cast::<*const u8>()); + ptr = unsafe { *(ptr.cast::<*const u8>()) }; } Ok(ptr) diff --git a/std/src/sys/personality/dwarf/mod.rs b/std/src/sys/personality/dwarf/mod.rs index 89f7f133e21b4..5c52d96c4cad4 100644 --- a/std/src/sys/personality/dwarf/mod.rs +++ b/std/src/sys/personality/dwarf/mod.rs @@ -5,6 +5,7 @@ // This module is used only by x86_64-pc-windows-gnu for now, but we // are compiling it everywhere to avoid regressions. #![allow(unused)] +#![forbid(unsafe_op_in_unsafe_fn)] #[cfg(test)] mod tests; @@ -17,7 +18,6 @@ pub struct DwarfReader { pub ptr: *const u8, } -#[forbid(unsafe_op_in_unsafe_fn)] impl DwarfReader { pub fn new(ptr: *const u8) -> DwarfReader { DwarfReader { ptr } diff --git a/std/src/sys/personality/emcc.rs b/std/src/sys/personality/emcc.rs index cb52ae89b1911..d374e3ad4c8f6 100644 --- a/std/src/sys/personality/emcc.rs +++ b/std/src/sys/personality/emcc.rs @@ -1,9 +1,10 @@ //! On Emscripten Rust panics are wrapped in C++ exceptions, so we just forward //! to `__gxx_personality_v0` which is provided by Emscripten. -use crate::ffi::c_int; use unwind as uw; +use crate::ffi::c_int; + // This is required by the compiler to exist (e.g., it's a lang item), but it's // never actually called by the compiler. Emscripten EH doesn't use a // personality function at all, it instead uses __cxa_find_matching_catch. diff --git a/std/src/sys/personality/gcc.rs b/std/src/sys/personality/gcc.rs index 0dc53550ca943..f6b1844e153fd 100644 --- a/std/src/sys/personality/gcc.rs +++ b/std/src/sys/personality/gcc.rs @@ -35,10 +35,12 @@ //! //! Once stack has been unwound down to the handler frame level, unwinding stops //! and the last personality routine transfers control to the catch block. +#![forbid(unsafe_op_in_unsafe_fn)] + +use unwind as uw; use super::dwarf::eh::{self, EHAction, EHContext}; use crate::ffi::c_int; -use unwind as uw; // Register ids were lifted from LLVM's TargetLowering::getExceptionPointerRegister() // and TargetLowering::getExceptionSelectorRegister() for each architecture, @@ -92,107 +94,116 @@ const UNWIND_DATA_REG: (i32, i32) = (4, 5); // a0, a1 // https://github.com/gcc-mirror/gcc/blob/trunk/libgcc/unwind-c.c cfg_if::cfg_if! { - if #[cfg(all(not(all(target_vendor = "apple", not(target_os = "watchos"))), target_arch = "arm", not(target_os = "netbsd")))] { - // ARM EHABI personality routine. - // https://web.archive.org/web/20190728160938/https://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf - // - // Apple 32-bit ARM (but not watchOS) uses the default routine instead - // since it uses SjLj unwinding. + if #[cfg(all( + target_arch = "arm", + not(all(target_vendor = "apple", not(target_os = "watchos"))), + not(target_os = "netbsd"), + ))] { + /// personality fn called by [ARM EHABI][armeabi-eh] + /// + /// Apple 32-bit ARM (but not watchOS) uses the default routine instead + /// since it uses "setjmp-longjmp" unwinding. + /// + /// [armeabi-eh]: https://web.archive.org/web/20190728160938/https://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf #[lang = "eh_personality"] unsafe extern "C" fn rust_eh_personality( state: uw::_Unwind_State, exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, ) -> uw::_Unwind_Reason_Code { - let state = state as c_int; - let action = state & uw::_US_ACTION_MASK as c_int; - let search_phase = if action == uw::_US_VIRTUAL_UNWIND_FRAME as c_int { - // Backtraces on ARM will call the personality routine with - // state == _US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND. In those cases - // we want to continue unwinding the stack, otherwise all our backtraces - // would end at __rust_try - if state & uw::_US_FORCE_UNWIND as c_int != 0 { + unsafe { + let state = state as c_int; + let action = state & uw::_US_ACTION_MASK as c_int; + let search_phase = if action == uw::_US_VIRTUAL_UNWIND_FRAME as c_int { + // Backtraces on ARM will call the personality routine with + // state == _US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND. In those cases + // we want to continue unwinding the stack, otherwise all our backtraces + // would end at __rust_try + if state & uw::_US_FORCE_UNWIND as c_int != 0 { + return continue_unwind(exception_object, context); + } + true + } else if action == uw::_US_UNWIND_FRAME_STARTING as c_int { + false + } else if action == uw::_US_UNWIND_FRAME_RESUME as c_int { return continue_unwind(exception_object, context); - } - true - } else if action == uw::_US_UNWIND_FRAME_STARTING as c_int { - false - } else if action == uw::_US_UNWIND_FRAME_RESUME as c_int { - return continue_unwind(exception_object, context); - } else { - return uw::_URC_FAILURE; - }; + } else { + return uw::_URC_FAILURE; + }; - // The DWARF unwinder assumes that _Unwind_Context holds things like the function - // and LSDA pointers, however ARM EHABI places them into the exception object. - // To preserve signatures of functions like _Unwind_GetLanguageSpecificData(), which - // take only the context pointer, GCC personality routines stash a pointer to - // exception_object in the context, using location reserved for ARM's - // "scratch register" (r12). - uw::_Unwind_SetGR(context, uw::UNWIND_POINTER_REG, exception_object as uw::_Unwind_Ptr); - // ...A more principled approach would be to provide the full definition of ARM's - // _Unwind_Context in our libunwind bindings and fetch the required data from there - // directly, bypassing DWARF compatibility functions. + // The DWARF unwinder assumes that _Unwind_Context holds things like the function + // and LSDA pointers, however ARM EHABI places them into the exception object. + // To preserve signatures of functions like _Unwind_GetLanguageSpecificData(), which + // take only the context pointer, GCC personality routines stash a pointer to + // exception_object in the context, using location reserved for ARM's + // "scratch register" (r12). + uw::_Unwind_SetGR(context, uw::UNWIND_POINTER_REG, exception_object as uw::_Unwind_Ptr); + // ...A more principled approach would be to provide the full definition of ARM's + // _Unwind_Context in our libunwind bindings and fetch the required data from there + // directly, bypassing DWARF compatibility functions. - let eh_action = match find_eh_action(context) { - Ok(action) => action, - Err(_) => return uw::_URC_FAILURE, - }; - if search_phase { - match eh_action { - EHAction::None | EHAction::Cleanup(_) => { - return continue_unwind(exception_object, context); - } - EHAction::Catch(_) | EHAction::Filter(_) => { - // EHABI requires the personality routine to update the - // SP value in the barrier cache of the exception object. - (*exception_object).private[5] = - uw::_Unwind_GetGR(context, uw::UNWIND_SP_REG); - return uw::_URC_HANDLER_FOUND; + let eh_action = match find_eh_action(context) { + Ok(action) => action, + Err(_) => return uw::_URC_FAILURE, + }; + if search_phase { + match eh_action { + EHAction::None | EHAction::Cleanup(_) => { + return continue_unwind(exception_object, context); + } + EHAction::Catch(_) | EHAction::Filter(_) => { + // EHABI requires the personality routine to update the + // SP value in the barrier cache of the exception object. + (*exception_object).private[5] = + uw::_Unwind_GetGR(context, uw::UNWIND_SP_REG); + return uw::_URC_HANDLER_FOUND; + } + EHAction::Terminate => return uw::_URC_FAILURE, } - EHAction::Terminate => return uw::_URC_FAILURE, - } - } else { - match eh_action { - EHAction::None => return continue_unwind(exception_object, context), - EHAction::Filter(_) if state & uw::_US_FORCE_UNWIND as c_int != 0 => return continue_unwind(exception_object, context), - EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { - uw::_Unwind_SetGR( - context, - UNWIND_DATA_REG.0, - exception_object as uw::_Unwind_Ptr, - ); - uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); - uw::_Unwind_SetIP(context, lpad); - return uw::_URC_INSTALL_CONTEXT; + } else { + match eh_action { + EHAction::None => return continue_unwind(exception_object, context), + EHAction::Filter(_) if state & uw::_US_FORCE_UNWIND as c_int != 0 => return continue_unwind(exception_object, context), + EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { + uw::_Unwind_SetGR( + context, + UNWIND_DATA_REG.0, + exception_object as uw::_Unwind_Ptr, + ); + uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); + uw::_Unwind_SetIP(context, lpad); + return uw::_URC_INSTALL_CONTEXT; + } + EHAction::Terminate => return uw::_URC_FAILURE, } - EHAction::Terminate => return uw::_URC_FAILURE, } - } - // On ARM EHABI the personality routine is responsible for actually - // unwinding a single stack frame before returning (ARM EHABI Sec. 6.1). - unsafe fn continue_unwind( - exception_object: *mut uw::_Unwind_Exception, - context: *mut uw::_Unwind_Context, - ) -> uw::_Unwind_Reason_Code { - if __gnu_unwind_frame(exception_object, context) == uw::_URC_NO_REASON { - uw::_URC_CONTINUE_UNWIND - } else { - uw::_URC_FAILURE - } - } - // defined in libgcc - extern "C" { - fn __gnu_unwind_frame( + // On ARM EHABI the personality routine is responsible for actually + // unwinding a single stack frame before returning (ARM EHABI Sec. 6.1). + unsafe fn continue_unwind( exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, - ) -> uw::_Unwind_Reason_Code; + ) -> uw::_Unwind_Reason_Code { + unsafe { + if __gnu_unwind_frame(exception_object, context) == uw::_URC_NO_REASON { + uw::_URC_CONTINUE_UNWIND + } else { + uw::_URC_FAILURE + } + } + } + // defined in libgcc + extern "C" { + fn __gnu_unwind_frame( + exception_object: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context, + ) -> uw::_Unwind_Reason_Code; + } } } } else { - // Default personality routine, which is used directly on most targets - // and indirectly on Windows x86_64 via SEH. + /// Default personality routine, which is used directly on most targets + /// and indirectly on Windows x86_64 and AArch64 via SEH. unsafe extern "C" fn rust_eh_personality_impl( version: c_int, actions: uw::_Unwind_Action, @@ -200,43 +211,49 @@ cfg_if::cfg_if! { exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, ) -> uw::_Unwind_Reason_Code { - if version != 1 { - return uw::_URC_FATAL_PHASE1_ERROR; - } - let eh_action = match find_eh_action(context) { - Ok(action) => action, - Err(_) => return uw::_URC_FATAL_PHASE1_ERROR, - }; - if actions as i32 & uw::_UA_SEARCH_PHASE as i32 != 0 { - match eh_action { - EHAction::None | EHAction::Cleanup(_) => uw::_URC_CONTINUE_UNWIND, - EHAction::Catch(_) | EHAction::Filter(_) => uw::_URC_HANDLER_FOUND, - EHAction::Terminate => uw::_URC_FATAL_PHASE1_ERROR, + unsafe { + if version != 1 { + return uw::_URC_FATAL_PHASE1_ERROR; } - } else { - match eh_action { - EHAction::None => uw::_URC_CONTINUE_UNWIND, - // Forced unwinding hits a terminate action. - EHAction::Filter(_) if actions as i32 & uw::_UA_FORCE_UNWIND as i32 != 0 => uw::_URC_CONTINUE_UNWIND, - EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { - uw::_Unwind_SetGR( - context, - UNWIND_DATA_REG.0, - exception_object.cast(), - ); - uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); - uw::_Unwind_SetIP(context, lpad); - uw::_URC_INSTALL_CONTEXT + let eh_action = match find_eh_action(context) { + Ok(action) => action, + Err(_) => return uw::_URC_FATAL_PHASE1_ERROR, + }; + if actions as i32 & uw::_UA_SEARCH_PHASE as i32 != 0 { + match eh_action { + EHAction::None | EHAction::Cleanup(_) => uw::_URC_CONTINUE_UNWIND, + EHAction::Catch(_) | EHAction::Filter(_) => uw::_URC_HANDLER_FOUND, + EHAction::Terminate => uw::_URC_FATAL_PHASE1_ERROR, + } + } else { + match eh_action { + EHAction::None => uw::_URC_CONTINUE_UNWIND, + // Forced unwinding hits a terminate action. + EHAction::Filter(_) if actions as i32 & uw::_UA_FORCE_UNWIND as i32 != 0 => uw::_URC_CONTINUE_UNWIND, + EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { + uw::_Unwind_SetGR( + context, + UNWIND_DATA_REG.0, + exception_object.cast(), + ); + uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); + uw::_Unwind_SetIP(context, lpad); + uw::_URC_INSTALL_CONTEXT + } + EHAction::Terminate => uw::_URC_FATAL_PHASE2_ERROR, } - EHAction::Terminate => uw::_URC_FATAL_PHASE2_ERROR, } } } cfg_if::cfg_if! { if #[cfg(all(windows, any(target_arch = "aarch64", target_arch = "x86_64"), target_env = "gnu"))] { - // On x86_64 MinGW targets, the unwinding mechanism is SEH however the unwind - // handler data (aka LSDA) uses GCC-compatible encoding. + /// personality fn called by [Windows Structured Exception Handling][windows-eh] + /// + /// On x86_64 and AArch64 MinGW targets, the unwinding mechanism is SEH, + /// however the unwind handler data (aka LSDA) uses GCC-compatible encoding + /// + /// [windows-eh]: https://learn.microsoft.com/en-us/cpp/cpp/structured-exception-handling-c-cpp?view=msvc-170 #[lang = "eh_personality"] #[allow(nonstandard_style)] unsafe extern "C" fn rust_eh_personality( @@ -245,16 +262,33 @@ cfg_if::cfg_if! { contextRecord: *mut uw::CONTEXT, dispatcherContext: *mut uw::DISPATCHER_CONTEXT, ) -> uw::EXCEPTION_DISPOSITION { - uw::_GCC_specific_handler( - exceptionRecord, - establisherFrame, - contextRecord, - dispatcherContext, - rust_eh_personality_impl, - ) + // SAFETY: the cfg is still target_os = "windows" and target_env = "gnu", + // which means that this is the correct function to call, passing our impl fn + // as the callback which gets actually used + unsafe { + uw::_GCC_specific_handler( + exceptionRecord, + establisherFrame, + contextRecord, + dispatcherContext, + rust_eh_personality_impl, + ) + } } } else { - // The personality routine for most of our targets. + /// personality fn called by [Itanium C++ ABI Exception Handling][itanium-eh] + /// + /// The personality routine for most non-Windows targets. This will be called by + /// the unwinding library: + /// - "In the search phase, the framework repeatedly calls the personality routine, + /// with the _UA_SEARCH_PHASE flag as described below, first for the current PC + /// and register state, and then unwinding a frame to a new PC at each step..." + /// - "If the search phase reports success, the framework restarts in the cleanup + /// phase. Again, it repeatedly calls the personality routine, with the + /// _UA_CLEANUP_PHASE flag as described below, first for the current PC and + /// register state, and then unwinding a frame to a new PC at each step..."i + /// + /// [itanium-eh]: https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html #[lang = "eh_personality"] unsafe extern "C" fn rust_eh_personality( version: c_int, @@ -263,13 +297,17 @@ cfg_if::cfg_if! { exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, ) -> uw::_Unwind_Reason_Code { - rust_eh_personality_impl( - version, - actions, - exception_class, - exception_object, - context, - ) + // SAFETY: the platform support must modify the cfg for the inner fn + // if it needs something different than what is currently invoked. + unsafe { + rust_eh_personality_impl( + version, + actions, + exception_class, + exception_object, + context, + ) + } } } } @@ -277,18 +315,20 @@ cfg_if::cfg_if! { } unsafe fn find_eh_action(context: *mut uw::_Unwind_Context) -> Result { - let lsda = uw::_Unwind_GetLanguageSpecificData(context) as *const u8; - let mut ip_before_instr: c_int = 0; - let ip = uw::_Unwind_GetIPInfo(context, &mut ip_before_instr); - let eh_context = EHContext { - // The return address points 1 byte past the call instruction, - // which could be in the next IP range in LSDA range table. - // - // `ip = -1` has special meaning, so use wrapping sub to allow for that - ip: if ip_before_instr != 0 { ip } else { ip.wrapping_sub(1) }, - func_start: uw::_Unwind_GetRegionStart(context), - get_text_start: &|| uw::_Unwind_GetTextRelBase(context), - get_data_start: &|| uw::_Unwind_GetDataRelBase(context), - }; - eh::find_eh_action(lsda, &eh_context) + unsafe { + let lsda = uw::_Unwind_GetLanguageSpecificData(context) as *const u8; + let mut ip_before_instr: c_int = 0; + let ip = uw::_Unwind_GetIPInfo(context, &mut ip_before_instr); + let eh_context = EHContext { + // The return address points 1 byte past the call instruction, + // which could be in the next IP range in LSDA range table. + // + // `ip = -1` has special meaning, so use wrapping sub to allow for that + ip: if ip_before_instr != 0 { ip } else { ip.wrapping_sub(1) }, + func_start: uw::_Unwind_GetRegionStart(context), + get_text_start: &|| uw::_Unwind_GetTextRelBase(context), + get_data_start: &|| uw::_Unwind_GetDataRelBase(context), + }; + eh::find_eh_action(lsda, &eh_context) + } } diff --git a/std/src/sys/sync/condvar/futex.rs b/std/src/sys/sync/condvar/futex.rs index 4586d0fd941a7..39cd97c01ea32 100644 --- a/std/src/sys/sync/condvar/futex.rs +++ b/std/src/sys/sync/condvar/futex.rs @@ -1,4 +1,5 @@ -use crate::sync::atomic::{AtomicU32, Ordering::Relaxed}; +use crate::sync::atomic::AtomicU32; +use crate::sync::atomic::Ordering::Relaxed; use crate::sys::futex::{futex_wait, futex_wake, futex_wake_all}; use crate::sys::sync::Mutex; use crate::time::Duration; diff --git a/std/src/sys/sync/condvar/itron.rs b/std/src/sys/sync/condvar/itron.rs index 3a3039889e98b..f6f2b698e4945 100644 --- a/std/src/sys/sync/condvar/itron.rs +++ b/std/src/sys/sync/condvar/itron.rs @@ -1,9 +1,13 @@ //! POSIX conditional variable implementation based on user-space wait queues. -use crate::sys::pal::itron::{ - abi, error::expect_success_aborting, spin::SpinMutex, task, time::with_tmos_strong, -}; -use crate::{mem::replace, ptr::NonNull, sys::sync::Mutex, time::Duration}; +use crate::mem::replace; +use crate::ptr::NonNull; +use crate::sys::pal::itron::error::expect_success_aborting; +use crate::sys::pal::itron::spin::SpinMutex; +use crate::sys::pal::itron::time::with_tmos_strong; +use crate::sys::pal::itron::{abi, task}; +use crate::sys::sync::Mutex; +use crate::time::Duration; // The implementation is inspired by the queue-based implementation shown in // Andrew D. Birrell's paper "Implementing Condition Variables with Semaphores" diff --git a/std/src/sys/sync/condvar/pthread.rs b/std/src/sys/sync/condvar/pthread.rs index a2a96410d932c..2b4bdfe415c80 100644 --- a/std/src/sys/sync/condvar/pthread.rs +++ b/std/src/sys/sync/condvar/pthread.rs @@ -1,6 +1,7 @@ use crate::cell::UnsafeCell; use crate::ptr; -use crate::sync::atomic::{AtomicPtr, Ordering::Relaxed}; +use crate::sync::atomic::AtomicPtr; +use crate::sync::atomic::Ordering::Relaxed; use crate::sys::sync::{mutex, Mutex}; #[cfg(not(target_os = "nto"))] use crate::sys::time::TIMESPEC_MAX; diff --git a/std/src/sys/sync/condvar/teeos.rs b/std/src/sys/sync/condvar/teeos.rs index 6457da91c2a5d..943867cd76169 100644 --- a/std/src/sys/sync/condvar/teeos.rs +++ b/std/src/sys/sync/condvar/teeos.rs @@ -1,6 +1,7 @@ use crate::cell::UnsafeCell; use crate::ptr; -use crate::sync::atomic::{AtomicPtr, Ordering::Relaxed}; +use crate::sync::atomic::AtomicPtr; +use crate::sync::atomic::Ordering::Relaxed; use crate::sys::sync::mutex::{self, Mutex}; use crate::sys::time::TIMESPEC_MAX; use crate::sys_common::lazy_box::{LazyBox, LazyInit}; diff --git a/std/src/sys/sync/condvar/windows7.rs b/std/src/sys/sync/condvar/windows7.rs index 07fa5fdd698ee..56eeeda551ebb 100644 --- a/std/src/sys/sync/condvar/windows7.rs +++ b/std/src/sys/sync/condvar/windows7.rs @@ -1,7 +1,6 @@ use crate::cell::UnsafeCell; -use crate::sys::c; -use crate::sys::os; use crate::sys::sync::{mutex, Mutex}; +use crate::sys::{c, os}; use crate::time::Duration; pub struct Condvar { diff --git a/std/src/sys/sync/condvar/xous.rs b/std/src/sys/sync/condvar/xous.rs index 7b218818ef8ef..007383479a100 100644 --- a/std/src/sys/sync/condvar/xous.rs +++ b/std/src/sys/sync/condvar/xous.rs @@ -1,8 +1,9 @@ +use core::sync::atomic::{AtomicUsize, Ordering}; + use crate::os::xous::ffi::{blocking_scalar, scalar}; use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; use crate::sys::sync::Mutex; use crate::time::Duration; -use core::sync::atomic::{AtomicUsize, Ordering}; // The implementation is inspired by Andrew D. Birrell's paper // "Implementing Condition Variables with Semaphores" diff --git a/std/src/sys/sync/mutex/fuchsia.rs b/std/src/sys/sync/mutex/fuchsia.rs index 5d89e5a13fd36..81a6361a83a49 100644 --- a/std/src/sys/sync/mutex/fuchsia.rs +++ b/std/src/sys/sync/mutex/fuchsia.rs @@ -37,10 +37,8 @@ //! //! [mutex in Fuchsia's libsync]: https://cs.opensource.google/fuchsia/fuchsia/+/main:zircon/system/ulib/sync/mutex.c -use crate::sync::atomic::{ - AtomicU32, - Ordering::{Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::AtomicU32; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use crate::sys::futex::zircon::{ zx_futex_wait, zx_futex_wake_single_owner, zx_handle_t, zx_thread_self, ZX_ERR_BAD_HANDLE, ZX_ERR_BAD_STATE, ZX_ERR_INVALID_ARGS, ZX_ERR_TIMED_OUT, ZX_ERR_WRONG_TYPE, ZX_OK, diff --git a/std/src/sys/sync/mutex/itron.rs b/std/src/sys/sync/mutex/itron.rs index 4ba32a8fbcd69..8440ffdd33772 100644 --- a/std/src/sys/sync/mutex/itron.rs +++ b/std/src/sys/sync/mutex/itron.rs @@ -1,18 +1,17 @@ //! Mutex implementation backed by μITRON mutexes. Assumes `acre_mtx` and //! `TA_INHERIT` are available. +#![forbid(unsafe_op_in_unsafe_fn)] -use crate::sys::pal::itron::{ - abi, - error::{expect_success, expect_success_aborting, fail, ItronError}, - spin::SpinIdOnceCell, -}; +use crate::sys::pal::itron::abi; +use crate::sys::pal::itron::error::{expect_success, expect_success_aborting, fail, ItronError}; +use crate::sys::pal::itron::spin::SpinIdOnceCell; pub struct Mutex { /// The ID of the underlying mutex object mtx: SpinIdOnceCell<()>, } -/// Create a mutex object. This function never panics. +/// Creates a mutex object. This function never panics. fn new_mtx() -> Result { ItronError::err_if_negative(unsafe { abi::acre_mtx(&abi::T_CMTX { @@ -30,7 +29,7 @@ impl Mutex { Mutex { mtx: SpinIdOnceCell::new() } } - /// Get the inner mutex's ID, which is lazily created. + /// Gets the inner mutex's ID, which is lazily created. fn raw(&self) -> abi::ID { match self.mtx.get_or_try_init(|| new_mtx().map(|id| (id, ()))) { Ok((id, ())) => id, diff --git a/std/src/sys/sync/mutex/xous.rs b/std/src/sys/sync/mutex/xous.rs index 1426e48f8b7af..63efa5a0210ab 100644 --- a/std/src/sys/sync/mutex/xous.rs +++ b/std/src/sys/sync/mutex/xous.rs @@ -1,9 +1,7 @@ use crate::os::xous::ffi::{blocking_scalar, do_yield}; use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; -use crate::sync::atomic::{ - AtomicBool, AtomicUsize, - Ordering::{Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use crate::sync::atomic::{AtomicBool, AtomicUsize}; pub struct Mutex { /// The "locked" value indicates how many threads are waiting on this diff --git a/std/src/sys/sync/once/futex.rs b/std/src/sys/sync/once/futex.rs index 8a231e65ad134..2c8a054282b01 100644 --- a/std/src/sys/sync/once/futex.rs +++ b/std/src/sys/sync/once/futex.rs @@ -1,14 +1,12 @@ use crate::cell::Cell; use crate::sync as public; -use crate::sync::atomic::{ - AtomicU32, - Ordering::{Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::AtomicU32; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use crate::sync::once::ExclusiveState; use crate::sys::futex::{futex_wait, futex_wake_all}; // On some platforms, the OS is very nice and handles the waiter queue for us. -// This means we only need one atomic value with 5 states: +// This means we only need one atomic value with 4 states: /// No initialization has run yet, and no thread is currently using the Once. const INCOMPLETE: u32 = 0; @@ -19,16 +17,20 @@ const POISONED: u32 = 1; /// Some thread is currently attempting to run initialization. It may succeed, /// so all future threads need to wait for it to finish. const RUNNING: u32 = 2; -/// Some thread is currently attempting to run initialization and there are threads -/// waiting for it to finish. -const QUEUED: u32 = 3; /// Initialization has completed and all future calls should finish immediately. -const COMPLETE: u32 = 4; +const COMPLETE: u32 = 3; -// Threads wait by setting the state to QUEUED and calling `futex_wait` on the state +// An additional bit indicates whether there are waiting threads: + +/// May only be set if the state is not COMPLETE. +const QUEUED: u32 = 4; + +// Threads wait by setting the QUEUED bit and calling `futex_wait` on the state // variable. When the running thread finishes, it will wake all waiting threads using // `futex_wake_all`. +const STATE_MASK: u32 = 0b11; + pub struct OnceState { poisoned: bool, set_state_to: Cell, @@ -47,7 +49,7 @@ impl OnceState { } struct CompletionGuard<'a> { - state: &'a AtomicU32, + state_and_queued: &'a AtomicU32, set_state_on_drop_to: u32, } @@ -56,32 +58,32 @@ impl<'a> Drop for CompletionGuard<'a> { // Use release ordering to propagate changes to all threads checking // up on the Once. `futex_wake_all` does its own synchronization, hence // we do not need `AcqRel`. - if self.state.swap(self.set_state_on_drop_to, Release) == QUEUED { - futex_wake_all(self.state); + if self.state_and_queued.swap(self.set_state_on_drop_to, Release) & QUEUED != 0 { + futex_wake_all(self.state_and_queued); } } } pub struct Once { - state: AtomicU32, + state_and_queued: AtomicU32, } impl Once { #[inline] pub const fn new() -> Once { - Once { state: AtomicU32::new(INCOMPLETE) } + Once { state_and_queued: AtomicU32::new(INCOMPLETE) } } #[inline] pub fn is_completed(&self) -> bool { // Use acquire ordering to make all initialization changes visible to the // current thread. - self.state.load(Acquire) == COMPLETE + self.state_and_queued.load(Acquire) == COMPLETE } #[inline] pub(crate) fn state(&mut self) -> ExclusiveState { - match *self.state.get_mut() { + match *self.state_and_queued.get_mut() { INCOMPLETE => ExclusiveState::Incomplete, POISONED => ExclusiveState::Poisoned, COMPLETE => ExclusiveState::Complete, @@ -89,31 +91,73 @@ impl Once { } } - // This uses FnMut to match the API of the generic implementation. As this - // implementation is quite light-weight, it is generic over the closure and - // so avoids the cost of dynamic dispatch. #[cold] #[track_caller] - pub fn call(&self, ignore_poisoning: bool, f: &mut impl FnMut(&public::OnceState)) { - let mut state = self.state.load(Acquire); + pub fn wait(&self, ignore_poisoning: bool) { + let mut state_and_queued = self.state_and_queued.load(Acquire); loop { + let state = state_and_queued & STATE_MASK; + let queued = state_and_queued & QUEUED != 0; match state { + COMPLETE => return, + POISONED if !ignore_poisoning => { + // Panic to propagate the poison. + panic!("Once instance has previously been poisoned"); + } + _ => { + // Set the QUEUED bit if it has not already been set. + if !queued { + state_and_queued += QUEUED; + if let Err(new) = self.state_and_queued.compare_exchange_weak( + state, + state_and_queued, + Relaxed, + Acquire, + ) { + state_and_queued = new; + continue; + } + } + + futex_wait(&self.state_and_queued, state_and_queued, None); + state_and_queued = self.state_and_queued.load(Acquire); + } + } + } + } + + #[cold] + #[track_caller] + pub fn call(&self, ignore_poisoning: bool, f: &mut dyn FnMut(&public::OnceState)) { + let mut state_and_queued = self.state_and_queued.load(Acquire); + loop { + let state = state_and_queued & STATE_MASK; + let queued = state_and_queued & QUEUED != 0; + match state { + COMPLETE => return, POISONED if !ignore_poisoning => { // Panic to propagate the poison. panic!("Once instance has previously been poisoned"); } INCOMPLETE | POISONED => { // Try to register the current thread as the one running. - if let Err(new) = - self.state.compare_exchange_weak(state, RUNNING, Acquire, Acquire) - { - state = new; + let next = RUNNING + if queued { QUEUED } else { 0 }; + if let Err(new) = self.state_and_queued.compare_exchange_weak( + state_and_queued, + next, + Acquire, + Acquire, + ) { + state_and_queued = new; continue; } + // `waiter_queue` will manage other waiting threads, and // wake them up on drop. - let mut waiter_queue = - CompletionGuard { state: &self.state, set_state_on_drop_to: POISONED }; + let mut waiter_queue = CompletionGuard { + state_and_queued: &self.state_and_queued, + set_state_on_drop_to: POISONED, + }; // Run the function, letting it know if we're poisoned or not. let f_state = public::OnceState { inner: OnceState { @@ -125,21 +169,27 @@ impl Once { waiter_queue.set_state_on_drop_to = f_state.inner.set_state_to.get(); return; } - RUNNING | QUEUED => { - // Set the state to QUEUED if it is not already. - if state == RUNNING - && let Err(new) = - self.state.compare_exchange_weak(RUNNING, QUEUED, Relaxed, Acquire) - { - state = new; - continue; + _ => { + // All other values must be RUNNING. + assert!(state == RUNNING); + + // Set the QUEUED bit if it is not already set. + if !queued { + state_and_queued += QUEUED; + if let Err(new) = self.state_and_queued.compare_exchange_weak( + state, + state_and_queued, + Relaxed, + Acquire, + ) { + state_and_queued = new; + continue; + } } - futex_wait(&self.state, QUEUED, None); - state = self.state.load(Acquire); + futex_wait(&self.state_and_queued, state_and_queued, None); + state_and_queued = self.state_and_queued.load(Acquire); } - COMPLETE => return, - _ => unreachable!("state is never set to invalid values"), } } } diff --git a/std/src/sys/sync/once/mod.rs b/std/src/sys/sync/once/mod.rs index 61b29713fa1a9..0e38937b1219a 100644 --- a/std/src/sys/sync/once/mod.rs +++ b/std/src/sys/sync/once/mod.rs @@ -9,6 +9,7 @@ cfg_if::cfg_if! { if #[cfg(any( + all(target_os = "windows", not(target_vendor="win7")), target_os = "linux", target_os = "android", all(target_arch = "wasm32", target_feature = "atomics"), diff --git a/std/src/sys/sync/once/no_threads.rs b/std/src/sys/sync/once/no_threads.rs index 11fde1888ba7c..12c1d9f5a6c98 100644 --- a/std/src/sys/sync/once/no_threads.rs +++ b/std/src/sys/sync/once/no_threads.rs @@ -55,6 +55,12 @@ impl Once { } } + #[cold] + #[track_caller] + pub fn wait(&self, _ignore_poisoning: bool) { + panic!("not implementable on this target"); + } + #[cold] #[track_caller] pub fn call(&self, ignore_poisoning: bool, f: &mut impl FnMut(&public::OnceState)) { diff --git a/std/src/sys/sync/once/queue.rs b/std/src/sys/sync/once/queue.rs index 730cdb768bd27..86f72c82008bc 100644 --- a/std/src/sys/sync/once/queue.rs +++ b/std/src/sys/sync/once/queue.rs @@ -56,22 +56,21 @@ // allowed, so no need for `SeqCst`. use crate::cell::Cell; -use crate::fmt; -use crate::ptr; -use crate::sync as public; -use crate::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; +use crate::sync::atomic::Ordering::{AcqRel, Acquire, Release}; +use crate::sync::atomic::{AtomicBool, AtomicPtr}; use crate::sync::once::ExclusiveState; use crate::thread::{self, Thread}; +use crate::{fmt, ptr, sync as public}; -type Masked = (); +type StateAndQueue = *mut (); pub struct Once { - state_and_queue: AtomicPtr, + state_and_queue: AtomicPtr<()>, } pub struct OnceState { poisoned: bool, - set_state_on_drop_to: Cell<*mut Masked>, + set_state_on_drop_to: Cell, } // Four states that a Once can be in, encoded into the lower bits of @@ -83,7 +82,8 @@ const COMPLETE: usize = 0x3; // Mask to learn about the state. All other bits are the queue of waiters if // this is in the RUNNING state. -const STATE_MASK: usize = 0x3; +const STATE_MASK: usize = 0b11; +const QUEUE_MASK: usize = !STATE_MASK; // Representation of a node in the linked list of waiters, used while in the // RUNNING state. @@ -95,15 +95,23 @@ const STATE_MASK: usize = 0x3; struct Waiter { thread: Cell>, signaled: AtomicBool, - next: *const Waiter, + next: Cell<*const Waiter>, } // Head of a linked list of waiters. // Every node is a struct on the stack of a waiting thread. // Will wake up the waiters when it gets dropped, i.e. also on panic. struct WaiterQueue<'a> { - state_and_queue: &'a AtomicPtr, - set_state_on_drop_to: *mut Masked, + state_and_queue: &'a AtomicPtr<()>, + set_state_on_drop_to: StateAndQueue, +} + +fn to_queue(current: StateAndQueue) -> *const Waiter { + current.mask(QUEUE_MASK).cast() +} + +fn to_state(current: StateAndQueue) -> usize { + current.addr() & STATE_MASK } impl Once { @@ -119,7 +127,7 @@ impl Once { // operations visible to us, and, this being a fast path, weaker // ordering helps with performance. This `Acquire` synchronizes with // `Release` operations on the slow path. - self.state_and_queue.load(Ordering::Acquire).addr() == COMPLETE + self.state_and_queue.load(Acquire).addr() == COMPLETE } #[inline] @@ -132,6 +140,25 @@ impl Once { } } + #[cold] + #[track_caller] + pub fn wait(&self, ignore_poisoning: bool) { + let mut current = self.state_and_queue.load(Acquire); + loop { + let state = to_state(current); + match state { + COMPLETE => return, + POISONED if !ignore_poisoning => { + // Panic to propagate the poison. + panic!("Once instance has previously been poisoned"); + } + _ => { + current = wait(&self.state_and_queue, current, !ignore_poisoning); + } + } + } + } + // This is a non-generic function to reduce the monomorphization cost of // using `call_once` (this isn't exactly a trivial or small implementation). // @@ -146,9 +173,10 @@ impl Once { #[cold] #[track_caller] pub fn call(&self, ignore_poisoning: bool, init: &mut dyn FnMut(&public::OnceState)) { - let mut state_and_queue = self.state_and_queue.load(Ordering::Acquire); + let mut current = self.state_and_queue.load(Acquire); loop { - match state_and_queue.addr() { + let state = to_state(current); + match state { COMPLETE => break, POISONED if !ignore_poisoning => { // Panic to propagate the poison. @@ -156,16 +184,16 @@ impl Once { } POISONED | INCOMPLETE => { // Try to register this thread as the one RUNNING. - let exchange_result = self.state_and_queue.compare_exchange( - state_and_queue, - ptr::without_provenance_mut(RUNNING), - Ordering::Acquire, - Ordering::Acquire, - ); - if let Err(old) = exchange_result { - state_and_queue = old; + if let Err(new) = self.state_and_queue.compare_exchange_weak( + current, + current.mask(QUEUE_MASK).wrapping_byte_add(RUNNING), + Acquire, + Acquire, + ) { + current = new; continue; } + // `waiter_queue` will manage other waiting threads, and // wake them up on drop. let mut waiter_queue = WaiterQueue { @@ -176,54 +204,57 @@ impl Once { // poisoned or not. let init_state = public::OnceState { inner: OnceState { - poisoned: state_and_queue.addr() == POISONED, + poisoned: state == POISONED, set_state_on_drop_to: Cell::new(ptr::without_provenance_mut(COMPLETE)), }, }; init(&init_state); waiter_queue.set_state_on_drop_to = init_state.inner.set_state_on_drop_to.get(); - break; + return; } _ => { // All other values must be RUNNING with possibly a // pointer to the waiter queue in the more significant bits. - assert!(state_and_queue.addr() & STATE_MASK == RUNNING); - wait(&self.state_and_queue, state_and_queue); - state_and_queue = self.state_and_queue.load(Ordering::Acquire); + assert!(state == RUNNING); + current = wait(&self.state_and_queue, current, true); } } } } } -fn wait(state_and_queue: &AtomicPtr, mut current_state: *mut Masked) { - // Note: the following code was carefully written to avoid creating a - // mutable reference to `node` that gets aliased. +fn wait( + state_and_queue: &AtomicPtr<()>, + mut current: StateAndQueue, + return_on_poisoned: bool, +) -> StateAndQueue { + let node = &Waiter { + thread: Cell::new(Some(thread::current())), + signaled: AtomicBool::new(false), + next: Cell::new(ptr::null()), + }; + loop { - // Don't queue this thread if the status is no longer running, - // otherwise we will not be woken up. - if current_state.addr() & STATE_MASK != RUNNING { - return; + let state = to_state(current); + let queue = to_queue(current); + + // If initialization has finished, return. + if state == COMPLETE || (return_on_poisoned && state == POISONED) { + return current; } - // Create the node for our current thread. - let node = Waiter { - thread: Cell::new(Some(thread::current())), - signaled: AtomicBool::new(false), - next: current_state.with_addr(current_state.addr() & !STATE_MASK) as *const Waiter, - }; - let me = core::ptr::addr_of!(node) as *const Masked as *mut Masked; + // Update the node for our current thread. + node.next.set(queue); // Try to slide in the node at the head of the linked list, making sure // that another thread didn't just replace the head of the linked list. - let exchange_result = state_and_queue.compare_exchange( - current_state, - me.with_addr(me.addr() | RUNNING), - Ordering::Release, - Ordering::Relaxed, - ); - if let Err(old) = exchange_result { - current_state = old; + if let Err(new) = state_and_queue.compare_exchange_weak( + current, + ptr::from_ref(node).wrapping_byte_add(state) as StateAndQueue, + Release, + Acquire, + ) { + current = new; continue; } @@ -232,14 +263,15 @@ fn wait(state_and_queue: &AtomicPtr, mut current_state: *mut Masked) { // would drop our `Waiter` node and leave a hole in the linked list // (and a dangling reference). Guard against spurious wakeups by // reparking ourselves until we are signaled. - while !node.signaled.load(Ordering::Acquire) { + while !node.signaled.load(Acquire) { // If the managing thread happens to signal and unpark us before we // can park ourselves, the result could be this thread never gets // unparked. Luckily `park` comes with the guarantee that if it got // an `unpark` just before on an unparked thread it does not park. thread::park(); } - break; + + return state_and_queue.load(Acquire); } } @@ -253,11 +285,10 @@ impl fmt::Debug for Once { impl Drop for WaiterQueue<'_> { fn drop(&mut self) { // Swap out our state with however we finished. - let state_and_queue = - self.state_and_queue.swap(self.set_state_on_drop_to, Ordering::AcqRel); + let current = self.state_and_queue.swap(self.set_state_on_drop_to, AcqRel); // We should only ever see an old state which was RUNNING. - assert_eq!(state_and_queue.addr() & STATE_MASK, RUNNING); + assert_eq!(current.addr() & STATE_MASK, RUNNING); // Walk the entire linked list of waiters and wake them up (in lifo // order, last to register is first to wake up). @@ -266,16 +297,13 @@ impl Drop for WaiterQueue<'_> { // free `node` if there happens to be has a spurious wakeup. // So we have to take out the `thread` field and copy the pointer to // `next` first. - let mut queue = - state_and_queue.with_addr(state_and_queue.addr() & !STATE_MASK) as *const Waiter; + let mut queue = to_queue(current); while !queue.is_null() { - let next = (*queue).next; + let next = (*queue).next.get(); let thread = (*queue).thread.take().unwrap(); - (*queue).signaled.store(true, Ordering::Release); - // ^- FIXME (maybe): This is another case of issue #55005 - // `store()` has a potentially dangling ref to `signaled`. - queue = next; + (*queue).signaled.store(true, Release); thread.unpark(); + queue = next; } } } diff --git a/std/src/sys/sync/rwlock/futex.rs b/std/src/sys/sync/rwlock/futex.rs index aa0de900238f5..75ecc2ab5c52f 100644 --- a/std/src/sys/sync/rwlock/futex.rs +++ b/std/src/sys/sync/rwlock/futex.rs @@ -1,7 +1,5 @@ -use crate::sync::atomic::{ - AtomicU32, - Ordering::{Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::AtomicU32; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use crate::sys::futex::{futex_wait, futex_wake, futex_wake_all}; pub struct RwLock { @@ -222,7 +220,7 @@ impl RwLock { } } - /// Wake up waiting threads after unlocking. + /// Wakes up waiting threads after unlocking. /// /// If both are waiting, this will wake up only one writer, but will fall /// back to waking up readers if there was no writer to wake up. diff --git a/std/src/sys/sync/rwlock/queue.rs b/std/src/sys/sync/rwlock/queue.rs index 337cc6c2ca094..458c16516bbe1 100644 --- a/std/src/sys/sync/rwlock/queue.rs +++ b/std/src/sys/sync/rwlock/queue.rs @@ -111,10 +111,8 @@ use crate::cell::OnceCell; use crate::hint::spin_loop; use crate::mem; use crate::ptr::{self, null_mut, without_provenance_mut, NonNull}; -use crate::sync::atomic::{ - AtomicBool, AtomicPtr, - Ordering::{AcqRel, Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; +use crate::sync::atomic::{AtomicBool, AtomicPtr}; use crate::thread::{self, Thread}; // Locking uses exponential backoff. `SPIN_COUNT` indicates how many times the @@ -186,7 +184,7 @@ struct Node { } impl Node { - /// Create a new queue node. + /// Creates a new queue node. fn new(write: bool) -> Node { Node { next: AtomicLink::new(None), diff --git a/std/src/sys/sync/rwlock/solid.rs b/std/src/sys/sync/rwlock/solid.rs index 7558eee8edd33..0537140202091 100644 --- a/std/src/sys/sync/rwlock/solid.rs +++ b/std/src/sys/sync/rwlock/solid.rs @@ -1,12 +1,9 @@ //! A readers-writer lock implementation backed by the SOLID kernel extension. +#![forbid(unsafe_op_in_unsafe_fn)] -use crate::sys::pal::{ - abi, - itron::{ - error::{expect_success, expect_success_aborting, fail, ItronError}, - spin::SpinIdOnceCell, - }, -}; +use crate::sys::pal::abi; +use crate::sys::pal::itron::error::{expect_success, expect_success_aborting, fail, ItronError}; +use crate::sys::pal::itron::spin::SpinIdOnceCell; pub struct RwLock { /// The ID of the underlying mutex object @@ -27,7 +24,7 @@ impl RwLock { RwLock { rwl: SpinIdOnceCell::new() } } - /// Get the inner mutex's ID, which is lazily created. + /// Gets the inner mutex's ID, which is lazily created. fn raw(&self) -> abi::ID { match self.rwl.get_or_try_init(|| new_rwl().map(|id| (id, ()))) { Ok((id, ())) => id, diff --git a/std/src/sys/sync/thread_parking/darwin.rs b/std/src/sys/sync/thread_parking/darwin.rs index 973c08f03171e..96e3d23c332c4 100644 --- a/std/src/sys/sync/thread_parking/darwin.rs +++ b/std/src/sys/sync/thread_parking/darwin.rs @@ -13,10 +13,8 @@ #![allow(non_camel_case_types)] use crate::pin::Pin; -use crate::sync::atomic::{ - AtomicI8, - Ordering::{Acquire, Release}, -}; +use crate::sync::atomic::AtomicI8; +use crate::sync::atomic::Ordering::{Acquire, Release}; use crate::time::Duration; type dispatch_semaphore_t = *mut crate::ffi::c_void; diff --git a/std/src/sys/sync/thread_parking/futex.rs b/std/src/sys/sync/thread_parking/futex.rs index 034eececb2a28..ce852eaadc4d9 100644 --- a/std/src/sys/sync/thread_parking/futex.rs +++ b/std/src/sys/sync/thread_parking/futex.rs @@ -36,7 +36,7 @@ pub struct Parker { // Ordering::Release when writing NOTIFIED (the 'token') in unpark(), and using // Ordering::Acquire when checking for this state in park(). impl Parker { - /// Construct the futex parker. The UNIX parker implementation + /// Constructs the futex parker. The UNIX parker implementation /// requires this to happen in-place. pub unsafe fn new_in_place(parker: *mut Parker) { unsafe { parker.write(Self { state: Atomic::new(EMPTY) }) }; diff --git a/std/src/sys/sync/thread_parking/id.rs b/std/src/sys/sync/thread_parking/id.rs index 0466743966034..a7b07b509dfd8 100644 --- a/std/src/sys/sync/thread_parking/id.rs +++ b/std/src/sys/sync/thread_parking/id.rs @@ -9,10 +9,8 @@ use crate::cell::UnsafeCell; use crate::pin::Pin; -use crate::sync::atomic::{ - fence, AtomicI8, - Ordering::{Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use crate::sync::atomic::{fence, AtomicI8}; use crate::sys::thread_parking::{current, park, park_timeout, unpark, ThreadId}; use crate::time::Duration; @@ -30,7 +28,7 @@ impl Parker { Parker { state: AtomicI8::new(EMPTY), tid: UnsafeCell::new(None) } } - /// Create a new thread parker. UNIX requires this to happen in-place. + /// Creates a new thread parker. UNIX requires this to happen in-place. pub unsafe fn new_in_place(parker: *mut Parker) { parker.write(Parker::new()) } diff --git a/std/src/sys/sync/thread_parking/pthread.rs b/std/src/sys/sync/thread_parking/pthread.rs index fdac1096dbfc1..c64600e9e29c3 100644 --- a/std/src/sys/sync/thread_parking/pthread.rs +++ b/std/src/sys/sync/thread_parking/pthread.rs @@ -92,7 +92,7 @@ pub struct Parker { } impl Parker { - /// Construct the UNIX parker in-place. + /// Constructs the UNIX parker in-place. /// /// # Safety /// The constructed parker must never be moved. diff --git a/std/src/sys/sync/thread_parking/windows7.rs b/std/src/sys/sync/thread_parking/windows7.rs index 3a8d40dc5cfac..1000b63b6d01a 100644 --- a/std/src/sys/sync/thread_parking/windows7.rs +++ b/std/src/sys/sync/thread_parking/windows7.rs @@ -57,14 +57,13 @@ // [3]: https://docs.microsoft.com/en-us/archive/msdn-magazine/2012/november/windows-with-c-the-evolution-of-synchronization-in-windows-and-c // [4]: Windows Internals, Part 1, ISBN 9780735671300 +use core::ffi::c_void; + use crate::pin::Pin; -use crate::sync::atomic::{ - AtomicI8, - Ordering::{Acquire, Release}, -}; +use crate::sync::atomic::AtomicI8; +use crate::sync::atomic::Ordering::{Acquire, Release}; use crate::sys::{c, dur2timeout}; use crate::time::Duration; -use core::ffi::c_void; pub struct Parker { state: AtomicI8, @@ -95,7 +94,7 @@ const NOTIFIED: i8 = 1; // Ordering::Release when writing NOTIFIED (the 'token') in unpark(), and using // Ordering::Acquire when reading this state in park() after waking up. impl Parker { - /// Construct the Windows parker. The UNIX parker implementation + /// Constructs the Windows parker. The UNIX parker implementation /// requires this to happen in-place. pub unsafe fn new_in_place(parker: *mut Parker) { parker.write(Self { state: AtomicI8::new(EMPTY) }); @@ -185,16 +184,15 @@ impl Parker { #[cfg(target_vendor = "win7")] mod keyed_events { - use super::{Parker, EMPTY, NOTIFIED}; - use crate::sys::c; use core::pin::Pin; use core::ptr; - use core::sync::atomic::{ - AtomicPtr, - Ordering::{Acquire, Relaxed}, - }; + use core::sync::atomic::AtomicPtr; + use core::sync::atomic::Ordering::{Acquire, Relaxed}; use core::time::Duration; + use super::{Parker, EMPTY, NOTIFIED}; + use crate::sys::c; + pub unsafe fn park(parker: Pin<&Parker>) { // Wait for unpark() to produce this event. c::NtWaitForKeyedEvent(keyed_event_handle(), parker.ptr(), 0, ptr::null_mut()); diff --git a/std/src/sys/sync/thread_parking/xous.rs b/std/src/sys/sync/thread_parking/xous.rs index 0bd0462d77d35..64b6f731f2377 100644 --- a/std/src/sys/sync/thread_parking/xous.rs +++ b/std/src/sys/sync/thread_parking/xous.rs @@ -2,10 +2,8 @@ use crate::os::xous::ffi::{blocking_scalar, scalar}; use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; use crate::pin::Pin; use crate::ptr; -use crate::sync::atomic::{ - AtomicI8, - Ordering::{Acquire, Release}, -}; +use crate::sync::atomic::AtomicI8; +use crate::sync::atomic::Ordering::{Acquire, Release}; use crate::time::Duration; const NOTIFIED: i8 = 1; diff --git a/std/src/sys/thread_local/guard/solid.rs b/std/src/sys/thread_local/guard/solid.rs index b65d00c5b5fb7..054b2d561c8b4 100644 --- a/std/src/sys/thread_local/guard/solid.rs +++ b/std/src/sys/thread_local/guard/solid.rs @@ -3,7 +3,8 @@ //! destructors for terminated tasks, we still keep our own list. use crate::cell::Cell; -use crate::sys::pal::{abi, itron::task}; +use crate::sys::pal::abi; +use crate::sys::pal::itron::task; use crate::sys::thread_local::destructors; pub fn enable() { diff --git a/std/src/sys/thread_local/guard/windows.rs b/std/src/sys/thread_local/guard/windows.rs index f6cd457046ffc..bf94f7d6e3d13 100644 --- a/std/src/sys/thread_local/guard/windows.rs +++ b/std/src/sys/thread_local/guard/windows.rs @@ -63,9 +63,10 @@ //! [1]: https://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way //! [2]: https://github.com/ChromiumWebApps/chromium/blob/master/base/threading/thread_local_storage_win.cc#L42 +use core::ffi::c_void; + use crate::ptr; use crate::sys::c; -use core::ffi::c_void; pub fn enable() { // When destructors are used, we don't want LLVM eliminating CALLBACK for any @@ -78,19 +79,6 @@ pub fn enable() { pub static CALLBACK: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = tls_callback; unsafe extern "system" fn tls_callback(_h: *mut c_void, dw_reason: u32, _pv: *mut c_void) { - // See comments above for what this is doing. Note that we don't need this - // trickery on GNU windows, just on MSVC. - #[cfg(all(target_env = "msvc", not(target_thread_local)))] - { - extern "C" { - static _tls_used: u8; - } - - unsafe { - ptr::from_ref(&_tls_used).read_volatile(); - } - } - if dw_reason == c::DLL_THREAD_DETACH || dw_reason == c::DLL_PROCESS_DETACH { #[cfg(target_thread_local)] unsafe { diff --git a/std/src/sys/thread_local/key/windows.rs b/std/src/sys/thread_local/key/windows.rs index 8b43e558d5d98..f4e0f25a476ee 100644 --- a/std/src/sys/thread_local/key/windows.rs +++ b/std/src/sys/thread_local/key/windows.rs @@ -26,10 +26,8 @@ use crate::cell::UnsafeCell; use crate::ptr; -use crate::sync::atomic::{ - AtomicPtr, AtomicU32, - Ordering::{AcqRel, Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; +use crate::sync::atomic::{AtomicPtr, AtomicU32}; use crate::sys::c; use crate::sys::thread_local::guard; diff --git a/std/src/sys/thread_local/key/xous.rs b/std/src/sys/thread_local/key/xous.rs index 5a837a33e190e..4fb2fdcc61925 100644 --- a/std/src/sys/thread_local/key/xous.rs +++ b/std/src/sys/thread_local/key/xous.rs @@ -36,14 +36,13 @@ // FIXME(joboet): implement support for native TLS instead. -use crate::mem::ManuallyDrop; -use crate::ptr; -use crate::sync::atomic::AtomicPtr; -use crate::sync::atomic::AtomicUsize; -use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use core::arch::asm; +use crate::mem::ManuallyDrop; use crate::os::xous::ffi::{map_memory, unmap_memory, MemoryFlags}; +use crate::ptr; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use crate::sync::atomic::{AtomicPtr, AtomicUsize}; pub type Key = usize; pub type Dtor = unsafe extern "C" fn(*mut u8); @@ -79,7 +78,7 @@ fn tls_ptr_addr() -> *mut *mut u8 { core::ptr::with_exposed_provenance_mut::<*mut u8>(tp) } -/// Create an area of memory that's unique per thread. This area will +/// Creates an area of memory that's unique per thread. This area will /// contain all thread local pointers. fn tls_table() -> &'static mut [*mut u8] { let tp = tls_ptr_addr(); diff --git a/std/src/sys/thread_local/native/eager.rs b/std/src/sys/thread_local/native/eager.rs index 99e5ae7fb9687..fd48c4f720216 100644 --- a/std/src/sys/thread_local/native/eager.rs +++ b/std/src/sys/thread_local/native/eager.rs @@ -1,7 +1,6 @@ use crate::cell::{Cell, UnsafeCell}; use crate::ptr::{self, drop_in_place}; -use crate::sys::thread_local::abort_on_dtor_unwind; -use crate::sys::thread_local::destructors; +use crate::sys::thread_local::{abort_on_dtor_unwind, destructors}; #[derive(Clone, Copy)] enum State { @@ -21,7 +20,7 @@ impl Storage { Storage { state: Cell::new(State::Initial), val: UnsafeCell::new(val) } } - /// Get a pointer to the TLS value. If the TLS variable has been destroyed, + /// Gets a pointer to the TLS value. If the TLS variable has been destroyed, /// a null pointer is returned. /// /// The resulting pointer may not be used after thread destruction has diff --git a/std/src/sys/thread_local/native/lazy.rs b/std/src/sys/thread_local/native/lazy.rs index 9d47e8ef68975..51294285ba013 100644 --- a/std/src/sys/thread_local/native/lazy.rs +++ b/std/src/sys/thread_local/native/lazy.rs @@ -1,8 +1,7 @@ use crate::cell::UnsafeCell; use crate::hint::unreachable_unchecked; use crate::ptr; -use crate::sys::thread_local::abort_on_dtor_unwind; -use crate::sys::thread_local::destructors; +use crate::sys::thread_local::{abort_on_dtor_unwind, destructors}; pub unsafe trait DestroyedState: Sized { fn register_dtor(s: &Storage); @@ -39,7 +38,7 @@ where Storage { state: UnsafeCell::new(State::Initial) } } - /// Get a pointer to the TLS value, potentially initializing it with the + /// Gets a pointer to the TLS value, potentially initializing it with the /// provided parameters. If the TLS variable has been destroyed, a null /// pointer is returned. /// diff --git a/std/src/sys/thread_local/os.rs b/std/src/sys/thread_local/os.rs index e06185f00690b..e27b47c3f4536 100644 --- a/std/src/sys/thread_local/os.rs +++ b/std/src/sys/thread_local/os.rs @@ -60,7 +60,7 @@ impl Storage { Storage { key: LazyKey::new(Some(destroy_value::)), marker: PhantomData } } - /// Get a pointer to the TLS value, potentially initializing it with the + /// Gets a pointer to the TLS value, potentially initializing it with the /// provided parameters. If the TLS variable has been destroyed, a null /// pointer is returned. /// diff --git a/std/src/sys/thread_local/statik.rs b/std/src/sys/thread_local/statik.rs index 0f08cab1ae4ff..a3451ab74e04f 100644 --- a/std/src/sys/thread_local/statik.rs +++ b/std/src/sys/thread_local/statik.rs @@ -63,7 +63,7 @@ impl LazyStorage { LazyStorage { value: UnsafeCell::new(None) } } - /// Get a pointer to the TLS value, potentially initializing it with the + /// Gets a pointer to the TLS value, potentially initializing it with the /// provided parameters. /// /// The resulting pointer may not be used after reentrant inialialization diff --git a/std/src/sys_common/io.rs b/std/src/sys_common/io.rs index 4a42ff3c618ce..e386c955f3767 100644 --- a/std/src/sys_common/io.rs +++ b/std/src/sys_common/io.rs @@ -5,12 +5,11 @@ pub const DEFAULT_BUF_SIZE: usize = if cfg!(target_os = "espidf") { 512 } else { #[cfg(test)] #[allow(dead_code)] // not used on emscripten pub mod test { - use crate::env; - use crate::fs; - use crate::path::{Path, PathBuf}; - use crate::thread; use rand::RngCore; + use crate::path::{Path, PathBuf}; + use crate::{env, fs, thread}; + pub struct TempDir(PathBuf); impl TempDir { diff --git a/std/src/sys_common/lazy_box.rs b/std/src/sys_common/lazy_box.rs index 63c3316bdeb28..b45b05f63baaa 100644 --- a/std/src/sys_common/lazy_box.rs +++ b/std/src/sys_common/lazy_box.rs @@ -5,10 +5,8 @@ use crate::marker::PhantomData; use crate::ops::{Deref, DerefMut}; use crate::ptr::null_mut; -use crate::sync::atomic::{ - AtomicPtr, - Ordering::{AcqRel, Acquire}, -}; +use crate::sync::atomic::AtomicPtr; +use crate::sync::atomic::Ordering::{AcqRel, Acquire}; pub(crate) struct LazyBox { ptr: AtomicPtr, diff --git a/std/src/sys_common/net.rs b/std/src/sys_common/net.rs index 95ca67fc2e0b6..25ebeb3502d20 100644 --- a/std/src/sys_common/net.rs +++ b/std/src/sys_common/net.rs @@ -1,19 +1,14 @@ #[cfg(test)] mod tests; -use crate::cmp; -use crate::fmt; +use crate::ffi::{c_int, c_void}; use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}; -use crate::mem; use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; -use crate::ptr; use crate::sys::common::small_c_string::run_with_cstr; -use crate::sys::net::netc as c; -use crate::sys::net::{cvt, cvt_gai, cvt_r, init, wrlen_t, Socket}; +use crate::sys::net::{cvt, cvt_gai, cvt_r, init, netc as c, wrlen_t, Socket}; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; - -use crate::ffi::{c_int, c_void}; +use crate::{cmp, fmt, mem, ptr}; cfg_if::cfg_if! { if #[cfg(any( @@ -42,6 +37,7 @@ cfg_if::cfg_if! { target_os = "hurd", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", + target_os = "solaris", target_os = "illumos", target_os = "haiku", target_os = "nto"))] { use libc::MSG_NOSIGNAL; } else { diff --git a/std/src/sys_common/process.rs b/std/src/sys_common/process.rs index 4d295cf0f09d5..5333ee146f7d6 100644 --- a/std/src/sys_common/process.rs +++ b/std/src/sys_common/process.rs @@ -2,12 +2,10 @@ #![unstable(feature = "process_internals", issue = "none")] use crate::collections::BTreeMap; -use crate::env; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::sys::pipe::read2; use crate::sys::process::{EnvKey, ExitStatus, Process, StdioPipes}; +use crate::{env, fmt, io}; // Stores a set of changes to an environment #[derive(Clone)] diff --git a/std/src/sys_common/wstr.rs b/std/src/sys_common/wstr.rs index 8eae160648502..f9a171fb7d8f5 100644 --- a/std/src/sys_common/wstr.rs +++ b/std/src/sys_common/wstr.rs @@ -15,7 +15,7 @@ pub struct WStrUnits<'a> { } impl WStrUnits<'_> { - /// Create the iterator. Returns `None` if `lpwstr` is null. + /// Creates the iterator. Returns `None` if `lpwstr` is null. /// /// SAFETY: `lpwstr` must point to a null-terminated wide string that lives /// at least as long as the lifetime of this struct. diff --git a/std/src/sys_common/wtf8.rs b/std/src/sys_common/wtf8.rs index 6aeeb6259285d..277c9506febbb 100644 --- a/std/src/sys_common/wtf8.rs +++ b/std/src/sys_common/wtf8.rs @@ -23,16 +23,12 @@ use core::str::next_code_point; use crate::borrow::Cow; use crate::collections::TryReserveError; -use crate::fmt; use crate::hash::{Hash, Hasher}; use crate::iter::FusedIterator; -use crate::mem; -use crate::ops; use crate::rc::Rc; -use crate::slice; -use crate::str; use crate::sync::Arc; use crate::sys_common::AsInner; +use crate::{fmt, mem, ops, slice, str}; const UTF8_REPLACEMENT_CHARACTER: &str = "\u{FFFD}"; diff --git a/std/src/thread/mod.rs b/std/src/thread/mod.rs index c8ee365392f85..59720f77465e1 100644 --- a/std/src/thread/mod.rs +++ b/std/src/thread/mod.rs @@ -159,25 +159,20 @@ mod tests; use crate::any::Any; -use crate::cell::{OnceCell, UnsafeCell}; -use crate::env; -use crate::ffi::{CStr, CString}; -use crate::fmt; -use crate::io; +use crate::cell::{Cell, OnceCell, UnsafeCell}; +use crate::ffi::CStr; use crate::marker::PhantomData; -use crate::mem::{self, forget}; +use crate::mem::{self, forget, ManuallyDrop}; use crate::num::NonZero; -use crate::panic; -use crate::panicking; use crate::pin::Pin; use crate::ptr::addr_of_mut; -use crate::str; use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sync::Arc; use crate::sys::sync::Parker; use crate::sys::thread as imp; use crate::sys_common::{AsInner, IntoInner}; use crate::time::{Duration, Instant}; +use crate::{env, fmt, io, panic, panicking, str}; #[stable(feature = "scoped_threads", since = "1.63.0")] mod scoped; @@ -192,22 +187,14 @@ pub use scoped::{scope, Scope, ScopedJoinHandle}; #[macro_use] mod local; -cfg_if::cfg_if! { - if #[cfg(test)] { - // Avoid duplicating the global state associated with thread-locals between this crate and - // realstd. Miri relies on this. - pub use realstd::thread::{local_impl, AccessError, LocalKey}; - } else { - #[stable(feature = "rust1", since = "1.0.0")] - pub use self::local::{AccessError, LocalKey}; - - // Implementation details used by the thread_local!{} macro. - #[doc(hidden)] - #[unstable(feature = "thread_local_internals", issue = "none")] - pub mod local_impl { - pub use crate::sys::thread_local::*; - } - } +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::local::{AccessError, LocalKey}; + +// Implementation details used by the thread_local!{} macro. +#[doc(hidden)] +#[unstable(feature = "thread_local_internals", issue = "none")] +pub mod local_impl { + pub use crate::sys::thread_local::*; } //////////////////////////////////////////////////////////////////////////////// @@ -487,11 +474,7 @@ impl Builder { amt }); - let my_thread = name.map_or_else(Thread::new_unnamed, |name| unsafe { - Thread::new( - CString::new(name).expect("thread name may not contain interior null bytes"), - ) - }); + let my_thread = name.map_or_else(Thread::new_unnamed, Thread::new); let their_thread = my_thread.clone(); let my_packet: Arc> = Arc::new(Packet { @@ -514,11 +497,10 @@ impl Builder { MaybeDangling(mem::MaybeUninit::new(x)) } fn into_inner(self) -> T { - // SAFETY: we are always initialized. - let ret = unsafe { self.0.assume_init_read() }; // Make sure we don't drop. - mem::forget(self); - ret + let this = ManuallyDrop::new(self); + // SAFETY: we are always initialized. + unsafe { this.0.assume_init_read() } } } impl Drop for MaybeDangling { @@ -699,17 +681,22 @@ where } thread_local! { + // Invariant: `CURRENT` and `CURRENT_ID` will always be initialized together. + // If `CURRENT` is initialized, then `CURRENT_ID` will hold the same value + // as `CURRENT.id()`. static CURRENT: OnceCell = const { OnceCell::new() }; + static CURRENT_ID: Cell> = const { Cell::new(None) }; } /// Sets the thread handle for the current thread. /// /// Aborts if the handle has been set already to reduce code size. pub(crate) fn set_current(thread: Thread) { + let tid = thread.id(); // Using `unwrap` here can add ~3kB to the binary size. We have complete // control over where this is called, so just abort if there is a bug. CURRENT.with(|current| match current.set(thread) { - Ok(()) => {} + Ok(()) => CURRENT_ID.set(Some(tid)), Err(_) => rtabort!("thread::set_current should only be called once per thread"), }); } @@ -719,7 +706,28 @@ pub(crate) fn set_current(thread: Thread) { /// In contrast to the public `current` function, this will not panic if called /// from inside a TLS destructor. pub(crate) fn try_current() -> Option { - CURRENT.try_with(|current| current.get_or_init(|| Thread::new_unnamed()).clone()).ok() + CURRENT + .try_with(|current| { + current + .get_or_init(|| { + let thread = Thread::new_unnamed(); + CURRENT_ID.set(Some(thread.id())); + thread + }) + .clone() + }) + .ok() +} + +/// Gets the id of the thread that invokes it. +#[inline] +pub(crate) fn current_id() -> ThreadId { + CURRENT_ID.get().unwrap_or_else(|| { + // If `CURRENT_ID` isn't initialized yet, then `CURRENT` must also not be initialized. + // `current()` will initialize both `CURRENT` and `CURRENT_ID` so subsequent calls to + // `current_id()` will succeed immediately. + current().id() + }) } /// Gets a handle to the thread that invokes it. @@ -836,7 +844,7 @@ pub fn panicking() -> bool { panicking::panicking() } -/// Use [`sleep`]. +/// Uses [`sleep`]. /// /// Puts the current thread to sleep for at least the specified amount of time. /// @@ -1107,7 +1115,7 @@ pub fn park() { forget(guard); } -/// Use [`park_timeout`]. +/// Uses [`park_timeout`]. /// /// Blocks unless or until the current thread's token is made available or /// the specified duration has been reached (may wake spuriously). @@ -1273,10 +1281,52 @@ impl ThreadId { /// The internal representation of a `Thread`'s name. enum ThreadName { Main, - Other(CString), + Other(ThreadNameString), Unnamed, } +// This module ensures private fields are kept private, which is necessary to enforce the safety requirements. +mod thread_name_string { + use core::str; + + use super::ThreadName; + use crate::ffi::{CStr, CString}; + + /// Like a `String` it's guaranteed UTF-8 and like a `CString` it's null terminated. + pub(crate) struct ThreadNameString { + inner: CString, + } + impl core::ops::Deref for ThreadNameString { + type Target = CStr; + fn deref(&self) -> &CStr { + &self.inner + } + } + impl From for ThreadNameString { + fn from(s: String) -> Self { + Self { + inner: CString::new(s).expect("thread name may not contain interior null bytes"), + } + } + } + impl ThreadName { + pub fn as_cstr(&self) -> Option<&CStr> { + match self { + ThreadName::Main => Some(c"main"), + ThreadName::Other(other) => Some(other), + ThreadName::Unnamed => None, + } + } + + pub fn as_str(&self) -> Option<&str> { + // SAFETY: `as_cstr` can only return `Some` for a fixed CStr or a `ThreadNameString`, + // which is guaranteed to be UTF-8. + self.as_cstr().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) }) + } + } +} +pub(crate) use thread_name_string::ThreadNameString; + /// The internal representation of a `Thread` handle struct Inner { name: ThreadName, // Guaranteed to be UTF-8 @@ -1316,25 +1366,20 @@ pub struct Thread { impl Thread { /// Used only internally to construct a thread object without spawning. - /// - /// # Safety - /// `name` must be valid UTF-8. - pub(crate) unsafe fn new(name: CString) -> Thread { - unsafe { Self::new_inner(ThreadName::Other(name)) } + pub(crate) fn new(name: String) -> Thread { + Self::new_inner(ThreadName::Other(name.into())) } pub(crate) fn new_unnamed() -> Thread { - unsafe { Self::new_inner(ThreadName::Unnamed) } + Self::new_inner(ThreadName::Unnamed) } // Used in runtime to construct main thread pub(crate) fn new_main() -> Thread { - unsafe { Self::new_inner(ThreadName::Main) } + Self::new_inner(ThreadName::Main) } - /// # Safety - /// If `name` is `ThreadName::Other(_)`, the contained string must be valid UTF-8. - unsafe fn new_inner(name: ThreadName) -> Thread { + fn new_inner(name: ThreadName) -> Thread { // We have to use `unsafe` here to construct the `Parker` in-place, // which is required for the UNIX implementation. // @@ -1457,15 +1502,11 @@ impl Thread { #[stable(feature = "rust1", since = "1.0.0")] #[must_use] pub fn name(&self) -> Option<&str> { - self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) }) + self.inner.name.as_str() } fn cname(&self) -> Option<&CStr> { - match &self.inner.name { - ThreadName::Main => Some(c"main"), - ThreadName::Other(other) => Some(&other), - ThreadName::Unnamed => None, - } + self.inner.name.as_cstr() } } diff --git a/std/src/thread/scoped.rs b/std/src/thread/scoped.rs index e2e22e5194f4a..ba27c9220aea5 100644 --- a/std/src/thread/scoped.rs +++ b/std/src/thread/scoped.rs @@ -1,10 +1,9 @@ use super::{current, park, Builder, JoinInner, Result, Thread}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::panic::{catch_unwind, resume_unwind, AssertUnwindSafe}; use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use crate::sync::Arc; +use crate::{fmt, io}; /// A scope to spawn scoped threads in. /// @@ -67,7 +66,7 @@ impl ScopeData { } } -/// Create a scope for spawning scoped threads. +/// Creates a scope for spawning scoped threads. /// /// The function passed to `scope` will be provided a [`Scope`] object, /// through which scoped threads can be [spawned][`Scope::spawn`]. diff --git a/std/src/thread/tests.rs b/std/src/thread/tests.rs index 1fb1333be0e45..aa464d56f95b2 100644 --- a/std/src/thread/tests.rs +++ b/std/src/thread/tests.rs @@ -1,16 +1,12 @@ use super::Builder; use crate::any::Any; -use crate::mem; use crate::panic::panic_any; -use crate::result; -use crate::sync::{ - atomic::{AtomicBool, Ordering}, - mpsc::{channel, Sender}, - Arc, Barrier, -}; +use crate::sync::atomic::{AtomicBool, Ordering}; +use crate::sync::mpsc::{channel, Sender}; +use crate::sync::{Arc, Barrier}; use crate::thread::{self, Scope, ThreadId}; -use crate::time::Duration; -use crate::time::Instant; +use crate::time::{Duration, Instant}; +use crate::{mem, result}; // !!! These tests are dangerous. If something is buggy, they will hang, !!! // !!! instead of exiting cleanly. This might wedge the buildbots. !!! diff --git a/std/src/time.rs b/std/src/time.rs index 6f1a354d28a85..ae46670c25e61 100644 --- a/std/src/time.rs +++ b/std/src/time.rs @@ -34,18 +34,17 @@ #[cfg(test)] mod tests; +#[stable(feature = "time", since = "1.3.0")] +pub use core::time::Duration; +#[stable(feature = "duration_checked_float", since = "1.66.0")] +pub use core::time::TryFromFloatSecsError; + use crate::error::Error; use crate::fmt; use crate::ops::{Add, AddAssign, Sub, SubAssign}; use crate::sys::time; use crate::sys_common::{FromInner, IntoInner}; -#[stable(feature = "time", since = "1.3.0")] -pub use core::time::Duration; - -#[stable(feature = "duration_checked_float", since = "1.66.0")] -pub use core::time::TryFromFloatSecsError; - /// A measurement of a monotonically nondecreasing clock. /// Opaque and useful only with [`Duration`]. /// diff --git a/std/src/time/tests.rs b/std/src/time/tests.rs index 6ed84806e6d37..de36dc4c9fd16 100644 --- a/std/src/time/tests.rs +++ b/std/src/time/tests.rs @@ -1,8 +1,10 @@ -use super::{Duration, Instant, SystemTime, UNIX_EPOCH}; use core::fmt::Debug; + #[cfg(not(target_arch = "wasm32"))] use test::{black_box, Bencher}; +use super::{Duration, Instant, SystemTime, UNIX_EPOCH}; + macro_rules! assert_almost_eq { ($a:expr, $b:expr) => {{ let (a, b) = ($a, $b); diff --git a/std/tests/common/mod.rs b/std/tests/common/mod.rs index 1aad6549e76c3..7cf70c725e411 100644 --- a/std/tests/common/mod.rs +++ b/std/tests/common/mod.rs @@ -1,10 +1,9 @@ #![allow(unused)] -use rand::RngCore; -use std::env; -use std::fs; use std::path::{Path, PathBuf}; -use std::thread; +use std::{env, fs, thread}; + +use rand::RngCore; /// Copied from `std::test_helpers::test_rng`, since these tests rely on the /// seed not being the same for every RNG invocation too. diff --git a/std/tests/create_dir_all_bare.rs b/std/tests/create_dir_all_bare.rs index 79c3c8f528efa..8becf713205ee 100644 --- a/std/tests/create_dir_all_bare.rs +++ b/std/tests/create_dir_all_bare.rs @@ -3,9 +3,8 @@ //! Note that this test changes the current directory so //! should not be in the same process as other tests. -use std::env; -use std::fs; use std::path::{Path, PathBuf}; +use std::{env, fs}; mod common; diff --git a/std/tests/env.rs b/std/tests/env.rs index a1ca85c2145f5..4e472b4ce9953 100644 --- a/std/tests/env.rs +++ b/std/tests/env.rs @@ -4,9 +4,10 @@ use std::ffi::{OsStr, OsString}; use rand::distributions::{Alphanumeric, DistString}; mod common; -use common::test_rng; use std::thread; +use common::test_rng; + #[track_caller] fn make_rand_name() -> OsString { let n = format!("TEST{}", Alphanumeric.sample_string(&mut test_rng(), 10)); diff --git a/std/tests/pipe_subprocess.rs b/std/tests/pipe_subprocess.rs new file mode 100644 index 0000000000000..1535742a83a21 --- /dev/null +++ b/std/tests/pipe_subprocess.rs @@ -0,0 +1,41 @@ +#![feature(anonymous_pipe)] + +fn main() { + #[cfg(all(not(miri), any(unix, windows)))] + { + use std::io::Read; + use std::pipe::pipe; + use std::{env, process}; + + if env::var("I_AM_THE_CHILD").is_ok() { + child(); + } else { + parent(); + } + + fn parent() { + let me = env::current_exe().unwrap(); + + let (rx, tx) = pipe().unwrap(); + assert!( + process::Command::new(me) + .env("I_AM_THE_CHILD", "1") + .stdout(tx) + .status() + .unwrap() + .success() + ); + + let mut s = String::new(); + (&rx).read_to_string(&mut s).unwrap(); + drop(rx); + assert_eq!(s, "Heloo,\n"); + + println!("Test pipe_subprocess.rs success"); + } + + fn child() { + println!("Heloo,"); + } + } +} diff --git a/std/tests/process_spawning.rs b/std/tests/process_spawning.rs index c56c111c37ded..d249eb7d50aa5 100644 --- a/std/tests/process_spawning.rs +++ b/std/tests/process_spawning.rs @@ -1,9 +1,6 @@ #![cfg(not(target_env = "sgx"))] -use std::env; -use std::fs; -use std::process; -use std::str; +use std::{env, fs, process, str}; mod common; diff --git a/std/tests/switch-stdout.rs b/std/tests/switch-stdout.rs index 0afe18088fa5f..42011a9b3da62 100644 --- a/std/tests/switch-stdout.rs +++ b/std/tests/switch-stdout.rs @@ -5,11 +5,10 @@ use std::io::{Read, Write}; mod common; -#[cfg(windows)] -use std::os::windows::io::OwnedHandle; - #[cfg(unix)] use std::os::fd::OwnedFd; +#[cfg(windows)] +use std::os::windows::io::OwnedHandle; #[cfg(unix)] fn switch_stdout_to(file: OwnedFd) -> OwnedFd { diff --git a/std/tests/windows.rs b/std/tests/windows.rs index 9f7596f1bc2c0..dab3182b81872 100644 --- a/std/tests/windows.rs +++ b/std/tests/windows.rs @@ -1,7 +1,9 @@ #![cfg(windows)] //! An external tests -use std::{ffi::OsString, os::windows::ffi::OsStringExt, path::PathBuf}; +use std::ffi::OsString; +use std::os::windows::ffi::OsStringExt; +use std::path::PathBuf; #[test] #[should_panic] diff --git a/stdarch b/stdarch index df3618d9f3516..47b929ddc521a 160000 --- a/stdarch +++ b/stdarch @@ -1 +1 @@ -Subproject commit df3618d9f35165f4bc548114e511c49c29e1fd9b +Subproject commit 47b929ddc521a78b0f699ba8d5c274d28593448a diff --git a/sysroot/Cargo.toml b/sysroot/Cargo.toml index 169eeeca8c2e8..7165c3e48af42 100644 --- a/sysroot/Cargo.toml +++ b/sysroot/Cargo.toml @@ -16,8 +16,8 @@ backtrace = ["std/backtrace"] compiler-builtins-c = ["std/compiler-builtins-c"] compiler-builtins-mem = ["std/compiler-builtins-mem"] compiler-builtins-no-asm = ["std/compiler-builtins-no-asm"] +compiler-builtins-no-f16-f128 = ["std/compiler-builtins-no-f16-f128"] compiler-builtins-mangled-names = ["std/compiler-builtins-mangled-names"] -compiler-builtins-weak-intrinsics = ["std/compiler-builtins-weak-intrinsics"] llvm-libunwind = ["std/llvm-libunwind"] system-llvm-libunwind = ["std/system-llvm-libunwind"] panic-unwind = ["std/panic_unwind"] diff --git a/test/src/bench.rs b/test/src/bench.rs index 9f34f54c3d60a..b71def3b03223 100644 --- a/test/src/bench.rs +++ b/test/src/bench.rs @@ -1,19 +1,16 @@ //! Benchmarking module. -use super::{ - event::CompletedTest, - options::BenchMode, - test_result::TestResult, - types::{TestDesc, TestId}, - Sender, -}; - -use crate::stats; -use std::cmp; -use std::io; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; +use std::{cmp, io}; + +use super::event::CompletedTest; +use super::options::BenchMode; +use super::test_result::TestResult; +use super::types::{TestDesc, TestId}; +use super::Sender; +use crate::stats; /// An identity function that *__hints__* to the compiler to be maximally pessimistic about what /// `black_box` could do. diff --git a/test/src/cli.rs b/test/src/cli.rs index b7d24405b775e..4ccd825bf8dd3 100644 --- a/test/src/cli.rs +++ b/test/src/cli.rs @@ -1,11 +1,11 @@ //! Module converting command-line arguments into test configuration. use std::env; +use std::io::{self, IsTerminal}; use std::path::PathBuf; use super::options::{ColorConfig, Options, OutputFormat, RunIgnored}; use super::time::TestTimeOptions; -use std::io::{self, IsTerminal}; #[derive(Debug)] pub struct TestOpts { diff --git a/test/src/console.rs b/test/src/console.rs index 7e224d60d9dc5..4d4cdcf4d7b6c 100644 --- a/test/src/console.rs +++ b/test/src/console.rs @@ -5,19 +5,19 @@ use std::io; use std::io::prelude::Write; use std::time::Instant; -use super::{ - bench::fmt_bench_samples, - cli::TestOpts, - event::{CompletedTest, TestEvent}, - filter_tests, - formatters::{JsonFormatter, JunitFormatter, OutputFormatter, PrettyFormatter, TerseFormatter}, - helpers::{concurrency::get_concurrency, metrics::MetricMap}, - options::{Options, OutputFormat}, - run_tests, term, - test_result::TestResult, - time::{TestExecTime, TestSuiteExecTime}, - types::{NamePadding, TestDesc, TestDescAndFn}, +use super::bench::fmt_bench_samples; +use super::cli::TestOpts; +use super::event::{CompletedTest, TestEvent}; +use super::formatters::{ + JsonFormatter, JunitFormatter, OutputFormatter, PrettyFormatter, TerseFormatter, }; +use super::helpers::concurrency::get_concurrency; +use super::helpers::metrics::MetricMap; +use super::options::{Options, OutputFormat}; +use super::test_result::TestResult; +use super::time::{TestExecTime, TestSuiteExecTime}; +use super::types::{NamePadding, TestDesc, TestDescAndFn}; +use super::{filter_tests, run_tests, term}; /// Generic wrapper over stdout. pub enum OutputLocation { diff --git a/test/src/formatters/json.rs b/test/src/formatters/json.rs index 6245aae17c4d7..aa1c50641cb54 100644 --- a/test/src/formatters/json.rs +++ b/test/src/formatters/json.rs @@ -1,12 +1,12 @@ -use std::{borrow::Cow, io, io::prelude::Write}; +use std::borrow::Cow; +use std::io; +use std::io::prelude::Write; use super::OutputFormatter; -use crate::{ - console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}, - test_result::TestResult, - time, - types::TestDesc, -}; +use crate::console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}; +use crate::test_result::TestResult; +use crate::time; +use crate::types::TestDesc; pub(crate) struct JsonFormatter { out: OutputLocation, diff --git a/test/src/formatters/junit.rs b/test/src/formatters/junit.rs index a211ebf1ded16..96b432008404b 100644 --- a/test/src/formatters/junit.rs +++ b/test/src/formatters/junit.rs @@ -1,13 +1,12 @@ -use std::io::{self, prelude::Write}; +use std::io::prelude::Write; +use std::io::{self}; use std::time::Duration; use super::OutputFormatter; -use crate::{ - console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}, - test_result::TestResult, - time, - types::{TestDesc, TestType}, -}; +use crate::console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}; +use crate::test_result::TestResult; +use crate::time; +use crate::types::{TestDesc, TestType}; pub struct JunitFormatter { out: OutputLocation, diff --git a/test/src/formatters/mod.rs b/test/src/formatters/mod.rs index bc6ffebc1d3b2..f1225fecfef1a 100644 --- a/test/src/formatters/mod.rs +++ b/test/src/formatters/mod.rs @@ -1,11 +1,10 @@ -use std::{io, io::prelude::Write}; +use std::io; +use std::io::prelude::Write; -use crate::{ - console::{ConsoleTestDiscoveryState, ConsoleTestState}, - test_result::TestResult, - time, - types::{TestDesc, TestName}, -}; +use crate::console::{ConsoleTestDiscoveryState, ConsoleTestState}; +use crate::test_result::TestResult; +use crate::time; +use crate::types::{TestDesc, TestName}; mod json; mod junit; diff --git a/test/src/formatters/pretty.rs b/test/src/formatters/pretty.rs index 22654a3400b44..7089eae4330a0 100644 --- a/test/src/formatters/pretty.rs +++ b/test/src/formatters/pretty.rs @@ -1,14 +1,12 @@ -use std::{io, io::prelude::Write}; +use std::io; +use std::io::prelude::Write; use super::OutputFormatter; -use crate::{ - bench::fmt_bench_samples, - console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}, - term, - test_result::TestResult, - time, - types::TestDesc, -}; +use crate::bench::fmt_bench_samples; +use crate::console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}; +use crate::test_result::TestResult; +use crate::types::TestDesc; +use crate::{term, time}; pub(crate) struct PrettyFormatter { out: OutputLocation, diff --git a/test/src/formatters/terse.rs b/test/src/formatters/terse.rs index 875c66e5fa32c..534aa2f33110c 100644 --- a/test/src/formatters/terse.rs +++ b/test/src/formatters/terse.rs @@ -1,15 +1,12 @@ -use std::{io, io::prelude::Write}; +use std::io; +use std::io::prelude::Write; use super::OutputFormatter; -use crate::{ - bench::fmt_bench_samples, - console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}, - term, - test_result::TestResult, - time, - types::NamePadding, - types::TestDesc, -}; +use crate::bench::fmt_bench_samples; +use crate::console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}; +use crate::test_result::TestResult; +use crate::types::{NamePadding, TestDesc}; +use crate::{term, time}; // We insert a '\n' when the output hits 100 columns in quiet mode. 88 test // result chars leaves 12 chars for a progress count like " 11704/12853". diff --git a/test/src/helpers/concurrency.rs b/test/src/helpers/concurrency.rs index 1854c6a76524d..b1545cbec438a 100644 --- a/test/src/helpers/concurrency.rs +++ b/test/src/helpers/concurrency.rs @@ -1,7 +1,8 @@ //! Helper module which helps to determine amount of threads to be used //! during tests execution. -use std::{env, num::NonZero, thread}; +use std::num::NonZero; +use std::{env, thread}; pub fn get_concurrency() -> usize { if let Ok(value) = env::var("RUST_TEST_THREADS") { diff --git a/test/src/helpers/shuffle.rs b/test/src/helpers/shuffle.rs index 2ac3bfbd4d6f2..14389eb0e37af 100644 --- a/test/src/helpers/shuffle.rs +++ b/test/src/helpers/shuffle.rs @@ -1,8 +1,9 @@ -use crate::cli::TestOpts; -use crate::types::{TestDescAndFn, TestId, TestName}; use std::hash::{DefaultHasher, Hasher}; use std::time::{SystemTime, UNIX_EPOCH}; +use crate::cli::TestOpts; +use crate::types::{TestDescAndFn, TestId, TestName}; + pub fn get_shuffle_seed(opts: &TestOpts) -> Option { opts.shuffle_seed.or_else(|| { if opts.shuffle { diff --git a/test/src/lib.rs b/test/src/lib.rs index 71cb796b93705..632f8d161affa 100644 --- a/test/src/lib.rs +++ b/test/src/lib.rs @@ -24,6 +24,9 @@ #![feature(panic_can_unwind)] #![feature(test)] #![allow(internal_features)] +#![warn(rustdoc::unescaped_backticks)] + +pub use cli::TestOpts; pub use self::bench::{black_box, Bencher}; pub use self::console::run_tests_console; @@ -31,39 +34,31 @@ pub use self::options::{ColorConfig, Options, OutputFormat, RunIgnored, ShouldPa pub use self::types::TestName::*; pub use self::types::*; pub use self::ColorConfig::*; -pub use cli::TestOpts; // Module to be used by rustc to compile tests in libtest pub mod test { - pub use crate::{ - assert_test_result, - bench::Bencher, - cli::{parse_opts, TestOpts}, - filter_tests, - helpers::metrics::{Metric, MetricMap}, - options::{Options, RunIgnored, RunStrategy, ShouldPanic}, - run_test, test_main, test_main_static, - test_result::{TestResult, TrFailed, TrFailedMsg, TrIgnored, TrOk}, - time::{TestExecTime, TestTimeOptions}, - types::{ - DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, TestDesc, - TestDescAndFn, TestId, TestName, TestType, - }, + pub use crate::bench::Bencher; + pub use crate::cli::{parse_opts, TestOpts}; + pub use crate::helpers::metrics::{Metric, MetricMap}; + pub use crate::options::{Options, RunIgnored, RunStrategy, ShouldPanic}; + pub use crate::test_result::{TestResult, TrFailed, TrFailedMsg, TrIgnored, TrOk}; + pub use crate::time::{TestExecTime, TestTimeOptions}; + pub use crate::types::{ + DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, TestDesc, + TestDescAndFn, TestId, TestName, TestType, }; + pub use crate::{assert_test_result, filter_tests, run_test, test_main, test_main_static}; } -use std::{ - collections::VecDeque, - env, io, - io::prelude::Write, - mem::ManuallyDrop, - panic::{self, catch_unwind, AssertUnwindSafe, PanicHookInfo}, - process::{self, Command, Termination}, - sync::mpsc::{channel, Sender}, - sync::{Arc, Mutex}, - thread, - time::{Duration, Instant}, -}; +use std::collections::VecDeque; +use std::io::prelude::Write; +use std::mem::ManuallyDrop; +use std::panic::{self, catch_unwind, AssertUnwindSafe, PanicHookInfo}; +use std::process::{self, Command, Termination}; +use std::sync::mpsc::{channel, Sender}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use std::{env, io, thread}; pub mod bench; mod cli; @@ -82,6 +77,7 @@ mod types; mod tests; use core::any::Any; + use event::{CompletedTest, TestEvent}; use helpers::concurrency::get_concurrency; use helpers::shuffle::{get_shuffle_seed, shuffle_tests}; diff --git a/test/src/stats.rs b/test/src/stats.rs index b33b080126131..71c944afde8d6 100644 --- a/test/src/stats.rs +++ b/test/src/stats.rs @@ -116,7 +116,7 @@ pub struct Summary { } impl Summary { - /// Construct a new summary of a sample set. + /// Constructs a new summary of a sample set. pub fn new(samples: &[f64]) -> Summary { Summary { sum: samples.sum(), diff --git a/test/src/stats/tests.rs b/test/src/stats/tests.rs index 3a6e8401bf1ab..4b209dcf214da 100644 --- a/test/src/stats/tests.rs +++ b/test/src/stats/tests.rs @@ -1,10 +1,11 @@ use super::*; extern crate test; -use self::test::test::Bencher; use std::io; use std::io::prelude::*; +use self::test::test::Bencher; + // Test vectors generated from R, using the script src/etc/stat-test-vectors.r. macro_rules! assert_approx_eq { diff --git a/test/src/term.rs b/test/src/term.rs index a14b0d4f5a962..e736e85d46966 100644 --- a/test/src/term.rs +++ b/test/src/term.rs @@ -12,7 +12,8 @@ #![deny(missing_docs)] -use std::io::{self, prelude::*}; +use std::io::prelude::*; +use std::io::{self}; pub(crate) use terminfo::TerminfoTerminal; #[cfg(windows)] diff --git a/test/src/term/terminfo/mod.rs b/test/src/term/terminfo/mod.rs index 67ba89410cd99..67eec3ca50f48 100644 --- a/test/src/term/terminfo/mod.rs +++ b/test/src/term/terminfo/mod.rs @@ -1,20 +1,18 @@ //! Terminfo database interface. use std::collections::HashMap; -use std::env; -use std::error; -use std::fmt; use std::fs::File; -use std::io::{self, prelude::*, BufReader}; +use std::io::prelude::*; +use std::io::{self, BufReader}; use std::path::Path; - -use super::color; -use super::Terminal; +use std::{env, error, fmt}; use parm::{expand, Param, Variables}; use parser::compiled::{msys_terminfo, parse}; use searcher::get_dbpath_for_term; +use super::{color, Terminal}; + /// A parsed terminfo database entry. #[allow(unused)] #[derive(Debug)] diff --git a/test/src/term/terminfo/parm.rs b/test/src/term/terminfo/parm.rs index c5b4ef01893c2..529ec0c36e4a5 100644 --- a/test/src/term/terminfo/parm.rs +++ b/test/src/term/terminfo/parm.rs @@ -1,10 +1,10 @@ //! Parameterized string expansion +use std::iter::repeat; + use self::Param::*; use self::States::*; -use std::iter::repeat; - #[cfg(test)] mod tests; diff --git a/test/src/term/terminfo/parser/compiled.rs b/test/src/term/terminfo/parser/compiled.rs index 5d40b7988b52d..e687b3be41fbf 100644 --- a/test/src/term/terminfo/parser/compiled.rs +++ b/test/src/term/terminfo/parser/compiled.rs @@ -2,11 +2,12 @@ //! ncurses-compatible compiled terminfo format parsing (term(5)) -use super::super::TermInfo; use std::collections::HashMap; use std::io; use std::io::prelude::*; +use super::super::TermInfo; + #[cfg(test)] mod tests; diff --git a/test/src/term/terminfo/searcher.rs b/test/src/term/terminfo/searcher.rs index 3e8ccc91ab051..1b29598cf804e 100644 --- a/test/src/term/terminfo/searcher.rs +++ b/test/src/term/terminfo/searcher.rs @@ -2,14 +2,13 @@ //! //! Does not support hashed database, only filesystem! -use std::env; -use std::fs; use std::path::PathBuf; +use std::{env, fs}; #[cfg(test)] mod tests; -/// Return path to database entry for `term` +/// Returns path to database entry for `term` #[allow(deprecated)] pub(crate) fn get_dbpath_for_term(term: &str) -> Option { let mut dirs_to_search = Vec::new(); diff --git a/test/src/term/win.rs b/test/src/term/win.rs index 65764c0ffc1b9..ce9cad37f306b 100644 --- a/test/src/term/win.rs +++ b/test/src/term/win.rs @@ -5,8 +5,7 @@ use std::io; use std::io::prelude::*; -use super::color; -use super::Terminal; +use super::{color, Terminal}; /// A Terminal implementation that uses the Win32 Console API. pub(crate) struct WinConsole { diff --git a/test/src/test_result.rs b/test/src/test_result.rs index bb32c70d66311..c5f4b03bfc96c 100644 --- a/test/src/test_result.rs +++ b/test/src/test_result.rs @@ -1,16 +1,14 @@ use std::any::Any; -use std::process::ExitStatus; - #[cfg(unix)] use std::os::unix::process::ExitStatusExt; +use std::process::ExitStatus; +pub use self::TestResult::*; use super::bench::BenchSamples; use super::options::ShouldPanic; use super::time; use super::types::TestDesc; -pub use self::TestResult::*; - // Return code for secondary process. // Start somewhere other than 0 so we know the return code means what we think // it means. @@ -19,7 +17,15 @@ pub const TR_OK: i32 = 50; // On Windows we use __fastfail to abort, which is documented to use this // exception code. #[cfg(windows)] -const STATUS_ABORTED: i32 = 0xC0000409u32 as i32; +const STATUS_FAIL_FAST_EXCEPTION: i32 = 0xC0000409u32 as i32; + +// On Zircon (the Fuchsia kernel), an abort from userspace calls the +// LLVM implementation of __builtin_trap(), e.g., ud2 on x86, which +// raises a kernel exception. If a userspace process does not +// otherwise arrange exception handling, the kernel kills the process +// with this return code. +#[cfg(target_os = "fuchsia")] +const ZX_TASK_RETCODE_EXCEPTION_KILL: i32 = -1028; #[derive(Debug, Clone, PartialEq)] pub enum TestResult { @@ -96,7 +102,7 @@ pub fn get_result_from_exit_code( let result = match status.code() { Some(TR_OK) => TestResult::TrOk, #[cfg(windows)] - Some(STATUS_ABORTED) => TestResult::TrFailed, + Some(STATUS_FAIL_FAST_EXCEPTION) => TestResult::TrFailed, #[cfg(unix)] None => match status.signal() { Some(libc::SIGABRT) => TestResult::TrFailed, @@ -105,6 +111,9 @@ pub fn get_result_from_exit_code( } None => unreachable!("status.code() returned None but status.signal() was None"), }, + // Upon an abort, Fuchsia returns the status code ZX_TASK_RETCODE_EXCEPTION_KILL. + #[cfg(target_os = "fuchsia")] + Some(ZX_TASK_RETCODE_EXCEPTION_KILL) => TestResult::TrFailed, #[cfg(not(unix))] None => TestResult::TrFailedMsg(format!("unknown return code")), #[cfg(any(windows, unix))] diff --git a/test/src/tests.rs b/test/src/tests.rs index 43a906ad298d1..ba2f35362c54f 100644 --- a/test/src/tests.rs +++ b/test/src/tests.rs @@ -1,5 +1,4 @@ use super::*; - use crate::{ console::OutputLocation, formatters::PrettyFormatter, @@ -237,8 +236,9 @@ fn test_should_panic_bad_message() { #[cfg(not(target_os = "emscripten"))] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn test_should_panic_non_string_message_type() { - use crate::tests::TrFailedMsg; use std::any::TypeId; + + use crate::tests::TrFailedMsg; fn f() -> Result<(), String> { std::panic::panic_any(1i32); } diff --git a/test/src/time.rs b/test/src/time.rs index 7fd69d7f7e73c..02ae050db55bd 100644 --- a/test/src/time.rs +++ b/test/src/time.rs @@ -5,10 +5,9 @@ //! - Provide helpers for `report-time` and `measure-time` options. //! - Provide newtypes for executions times. -use std::env; -use std::fmt; use std::str::FromStr; use std::time::{Duration, Instant}; +use std::{env, fmt}; use super::types::{TestDesc, TestType}; @@ -24,9 +23,10 @@ pub const TEST_WARN_TIMEOUT_S: u64 = 60; /// Example of the expected format is `RUST_TEST_TIME_xxx=100,200`, where 100 means /// warn time, and 200 means critical time. pub mod time_constants { - use super::TEST_WARN_TIMEOUT_S; use std::time::Duration; + use super::TEST_WARN_TIMEOUT_S; + /// Environment variable for overriding default threshold for unit-tests. pub const UNIT_ENV_NAME: &str = "RUST_TEST_TIME_UNIT"; diff --git a/test/src/types.rs b/test/src/types.rs index 6a7035a8e2918..c3be3466cb928 100644 --- a/test/src/types.rs +++ b/test/src/types.rs @@ -4,15 +4,14 @@ use std::borrow::Cow; use std::fmt; use std::sync::mpsc::Sender; -use super::__rust_begin_short_backtrace; -use super::bench::Bencher; -use super::event::CompletedTest; -use super::options; - pub use NamePadding::*; pub use TestFn::*; pub use TestName::*; +use super::bench::Bencher; +use super::event::CompletedTest; +use super::{__rust_begin_short_backtrace, options}; + /// Type of the test according to the [Rust book](https://doc.rust-lang.org/cargo/guide/tests.html) /// conventions. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] diff --git a/unwind/src/lib.rs b/unwind/src/lib.rs index 45a1c334a44dd..b3de71f29f394 100644 --- a/unwind/src/lib.rs +++ b/unwind/src/lib.rs @@ -2,7 +2,6 @@ #![unstable(feature = "panic_unwind", issue = "32837")] #![feature(link_cfg)] #![feature(staged_api)] -#![cfg_attr(bootstrap, feature(c_unwind))] #![feature(strict_provenance)] #![cfg_attr(target_arch = "wasm64", feature(simd_wasm64))] #![cfg_attr(not(target_env = "msvc"), feature(libc))] diff --git a/unwind/src/unwinding.rs b/unwind/src/unwinding.rs index 083acaeb56af2..b3460791ce5ca 100644 --- a/unwind/src/unwinding.rs +++ b/unwind/src/unwinding.rs @@ -28,9 +28,7 @@ pub enum _Unwind_Reason_Code { _URC_FAILURE = 9, // used only by ARM EHABI } pub use _Unwind_Reason_Code::*; - -pub use unwinding::abi::UnwindContext; -pub use unwinding::abi::UnwindException; +pub use unwinding::abi::{UnwindContext, UnwindException}; pub enum _Unwind_Context {} pub use unwinding::custom_eh_frame_finder::{