Add #[must_use] to remaining std functions (O-Z)
I've run out of compelling reasons to group functions together across crates so I'm just going to go module-by-module. This is half of the remaining items from the `std` crate, from O-Z.
`panicking::take_hook` has a side effect: it unregisters the current panic hook, returning it. I almost ignored it, but the documentation example shows `let _ = panic::take_hook();`, so following suit I went ahead and added a `#[must_use]`.
```rust
std::panicking fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>;
```
I added these functions that clippy did not flag:
```rust
std::path::Path fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool;
std::path::Path fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool;
std::path::Path fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf;
std::path::Path fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf;
```
Parent issue: #89692
r? `@joshtriplett`
Add #[must_use] to alloc functions that would leak memory
As [requested](https://github.com/rust-lang/rust/pull/89899#issuecomment-955600779) by `@joshtriplett.`
> Please do go ahead and add the ones whose only legitimate use for ignoring the return value is leaking memory. (In a separate PR please.) I think it's sufficiently error-prone to call something like alloc and ignore the result that it's legitimate to require `let _ =` for that.
I added `realloc` myself. Clippy ignored it because of its `mut` argument.
```rust
alloc/src/alloc.rs:123:1 alloc unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8;
```
Parent issue: #89692
r? `@joshtriplett`
Add #[must_use] to remaining core functions
I've run out of compelling reasons to group functions together across crates so I'm just going to go module-by-module. This is everything remaining from the `core` crate.
Ignored by clippy for reasons unknown:
```rust
core::alloc::Layout unsafe fn for_value_raw<T: ?Sized>(t: *const T) -> Self;
core::any const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str;
```
Ignored by clippy because of `mut`:
```rust
str fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
```
<del>
Ignored by clippy presumably because a caller might want `f` called for side effects. That seems like a bad usage of `map` to me.
```rust
core::cell::Ref<'b, T> fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, T>;
core::cell::Ref<'b, T> fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>);
```
</del>
Parent issue: #89692
r? ```@joshtriplett```
Add #[must_use] to mem/ptr functions
There's a lot of low-level / unsafe stuff here. Are there legit use cases for ignoring any of these return values?
* No regressions in `./x.py test --stage 1 library/std src/tools/clippy`.
* One regression in `./x.py test --stage 1 src/test/ui`. Fixed.
* I am unable to run `./x.py doc` on my machine so I'll need to wait for the CI to verify doctests pass. I eyeballed all the adjacent tests and they all look okay.
Parent issue: #89692
r? ```@joshtriplett```
Add #[must_use] to expensive computations
The unifying theme for this commit is weak, admittedly. I put together a list of "expensive" functions when I originally proposed this whole effort, but nobody's cared about that criterion. Still, it's a decent way to bite off a not-too-big chunk of work.
Given the grab bag nature of this commit, the messages I used vary quite a bit. I'm open to wording changes.
For some reason clippy flagged four `BTreeSet` methods but didn't say boo about equivalent ones on `HashSet`. I stared at them for a while but I can't figure out the difference so I added the `HashSet` ones in.
```rust
// Flagged by clippy.
alloc::collections::btree_set::BTreeSet<T> fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T>;
alloc::collections::btree_set::BTreeSet<T> fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>) -> SymmetricDifference<'a, T>
alloc::collections::btree_set::BTreeSet<T> fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T>;
alloc::collections::btree_set::BTreeSet<T> fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T>;
// Ignored by clippy, but not by me.
std::collections::HashSet<T, S> fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S>;
std::collections::HashSet<T, S> fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, S>) -> SymmetricDifference<'a, T, S>
std::collections::HashSet<T, S> fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S>;
std::collections::HashSet<T, S> fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S>;
```
Parent issue: #89692
r? ```@joshtriplett```
Stabilize `is_symlink()` for `Metadata` and `Path`
I'm not fully sure about `since` version, correct me if I'm wrong
Needs update after stabilization: [cargo-test-support](8063672238/crates/cargo-test-support/src/paths.rs (L202))
Linked issue: #85748
track_caller for slice length assertions
`clone_from_slice` was missing `#[track_caller]`, and its assert did not report a useful location.
These are small generic methods, so hopefully track_caller gets inlined into nothingness, but it may be worth running a benchmark on this.
Use libc::sched_getaffinity and count the number of CPUs in the returned
mask. This handles cases where the process doesn't have access to all
CPUs, such as when limited via taskset or similar.
Repace use of `static_nobundle` with `native_link_modifiers` within Rust codebase
This fixes warnings when building Rust and running tests:
```
warning: library kind `static-nobundle` has been superseded by specifying `-bundle` on library kind `static`. Try `static:-bundle`
warning: `rustc_llvm` (lib) generated 2 warnings (1 duplicate)
```
Make `core::slice::from_raw_parts[_mut]` const
Responses to #90012 seem to allow ``@rust-lang/wg-const-eval`` to decide on use of `const_eval_select`, so we can make `core::slice::from_raw_parts[_mut]` const :)
---
This PR marks the following APIs as const:
```rust
// core::slice
pub const unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T];
pub const unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T];
```
---
Resolves#90011
r? ``@oli-obk``
Make most std::ops traits const on numeric types
This PR makes existing implementations of `std::ops` traits (`Add`, `Sub`, etc) [`impl const`](https://github.com/rust-lang/rust/issues/67792) where possible.
This affects:
- All numeric primitives (`u*`, `i*`, `f*`)
- `NonZero*`
- `Wrapping`
This is under the `rustc_const_unstable` feature `const_ops`.
I will write tests once I know what can and can't be kept for the final version of this PR.
Since this is my first PR to rustc (and hopefully one of many), please give me feedback on how to better handle the PR process wherever possible. Thanks
[Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Const.20std.3A.3Aops.20traits.20PR)
Automatically convert paths to verbatim for filesystem operations that support it
This allows using longer paths without the user needing to `canonicalize` or manually prefix paths. If the path is already verbatim then this has no effect.
Fixes: #32689
Replace some operators in libcore with their short-circuiting equivalents
In libcore there are a few occurrences of bitwise operators used in boolean expressions instead of their short-circuiting equivalents. This makes it harder to perform some kinds of source code analysis over libcore, for example [MC/DC] code coverage (a requirement in safety-critical environments).
This PR aims to remove as many bitwise operators in boolean expressions from libcore as possible, without any performance regression and without other changes. This means not all bitwise operators are removed, only the ones that don't have any difference with their short-circuiting counterparts. This already simplifies achieving MC/DC coverage, and the other functions can be changed in future PRs.
The PR is best reviewed commit-by-commit, and each commit has the resulting assembly in the message.
## Checked integer methods
These methods recently switched to bitwise operators in PRs https://github.com/rust-lang/rust/pull/89459 and https://github.com/rust-lang/rust/pull/89351. I confirmed bitwise operators are needed in most of the functions, except these two:
* `{integer}::checked_div` ([Godbolt link (nightly)](https://rust.godbolt.org/z/17efh5jPc))
* `{integer}::checked_rem` ([Godbolt link (nightly)](https://rust.godbolt.org/z/85qGWc94K))
`@tspiteri` already mentioned this was the case in https://github.com/rust-lang/rust/pull/89459#issuecomment-932728384, but opted to also switch those two to bitwise operators for consistency. As that makes MC/DC analysis harder this PR proposes switching those two back to short-circuiting operators.
## `{unsigned_ints}::carrying_add`
[Godbolt link (1.56.0)](https://rust.godbolt.org/z/vG9vx8x48)
In this instance replacing the `|` with `||` produces the exact same assembly when optimizations are enabled, so switching to the short-circuiting operator shouldn't have any impact.
## `{unsigned_ints}::borrowing_sub`
[Godbolt link (1.56.0)](https://rust.godbolt.org/z/asEfKaGE4)
In this instance replacing the `|` with `||` produces the exact same assembly when optimizations are enabled, so switching to the short-circuiting operator shouldn't have any impact.
## String UTF-8 validation
[Godbolt link (1.56.0)](https://rust.godbolt.org/z/a4rEbTvvx)
In this instance replacing the `|` with `||` produces practically the same assembly, with the two operands for the "or" swapped:
```asm
; Old
mov rax, qword ptr [rdi + rdx + 8]
or rax, qword ptr [rdi + rdx]
test rax, r9
je .LBB0_7
; New
mov rax, qword ptr [rdi + rdx]
or rax, qword ptr [rdi + rdx + 8]
test rax, r8
je .LBB0_7
```
[MC/DC]: https://en.wikipedia.org/wiki/Modified_condition/decision_coverage
Revert "Add rustc lint, warning when iterating over hashmaps"
Fixes perf regressions introduced in https://github.com/rust-lang/rust/pull/90235 by temporarily reverting the relevant PR.
Remove extra lines in examples for `Duration::try_from_secs_*`
None of the other examples have extra lines below the `#![feature(...)]` statements, so I thought it appropriate that these examples shouldn't either.
Rollup of 5 pull requests
Successful merges:
- #90239 (Consistent big O notation in map.rs)
- #90267 (fix: inner attribute followed by outer attribute causing ICE)
- #90288 (Add hint for people missing `TryFrom`, `TryInto`, `FromIterator` import pre-2021)
- #90304 (Add regression test for #75961)
- #90344 (Add tracking issue number to const_cstr_unchecked)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Add tracking issue number to const_cstr_unchecked
Also created a tracking issue, see #90343.
I think it makes sense to stabilize this somewhat soon considering abuse of `transmute` to have this feature in constants, see https://crates.io/crates/cstr for an example. Code can be rewritten to use `mem::transmute` to work on stable.
Clean up special function const checks
Mark them as const and `#[rustc_do_not_const_check]` instead of hard-coding them in const-eval checks.
r? `@oli-obk`
`@rustbot` label A-const-eval T-compiler
Using short-circuit operators makes it easier to perform some kinds of
source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86 assembly is the same
between the old and new versions:
```
xor eax, eax
test esi, esi
je .LBB0_1
cmp edi, -2147483648
jne .LBB0_4
cmp esi, -1
jne .LBB0_4
ret
.LBB0_1:
ret
.LBB0_4:
mov eax, edi
cdq
idiv esi
mov eax, 1
ret
```
Using short-circuit operators makes it easier to perform some kinds of
source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86 assembly is the same
between the old and new versions:
```
xor eax, eax
test esi, esi
je .LBB0_1
cmp edi, -2147483648
jne .LBB0_4
cmp esi, -1
jne .LBB0_4
ret
.LBB0_1:
ret
.LBB0_4:
mov eax, edi
cdq
idiv esi
mov edx, eax
mov eax, 1
ret
```
Using short-circuiting operators makes it easier to perform some kinds
of source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86_64 assembly is
equivalent between the old and new versions.
Old assembly of that condition:
```
mov rax, qword ptr [rdi + rdx + 8]
or rax, qword ptr [rdi + rdx]
test rax, r9
je .LBB0_7
```
New assembly of that condition:
```
mov rax, qword ptr [rdi + rdx]
or rax, qword ptr [rdi + rdx + 8]
test rax, r8
je .LBB0_7
```
Using short-circuiting operators makes it easier to perform some kinds
of source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86_64 assembly is the same
between the old and new versions:
```
mov eax, edi
add dl, -1
sbb eax, esi
setb dl
ret
```
Using short-circuiting operators makes it easier to perform some kinds
of source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86_64 assembly is the same
between the old and new versions:
```
mov eax, edi
add dl, -1
adc eax, esi
setb dl
ret
```
Remove fNN::lerp
Lerp is [surprisingly complex with multiple tradeoffs depending on what guarantees you want to provide](https://github.com/rust-lang/rust/issues/86269#issuecomment-869108301) (and what you're willing to drop for raw speed), so we don't have consensus on what implementation to use, let alone what signature - `t.lerp(a, b)` nicely puts `a, b` together, but makes dispatch to lerp custom types with the same signature basically impossible, and major ecosystem crates (e.g. nalgebra, glium) use `a.lerp(b, t)`, which is easily confusable. It was suggested to maybe provide a `Lerp<T>` trait and `t.lerp([a, b])`, which _could_ be implemented by downstream math libraries for their types, but also significantly raises the bar from a simple fNN method to a full trait, and does nothing to solve the implementation question. (It also raises the question of whether we'd support higher-order bezier interpolation.)
The only consensus we have is the lack of consensus, and the [general temperature](https://github.com/rust-lang/rust/issues/86269#issuecomment-951347135) is that we should just remove this method (giving the method space back to 3rd party libs) and revisit this if (and likely only if) IEEE adds lerp to their specification.
If people want a lerp, they're _probably_ already using (or writing) a math support library, which provides a lerp function for its custom math types and can provide the same lerp implementation for the primitive types via an extension trait.
See also [previous Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/lerp.20API.20design)
cc ``@clarfonthey`` (original PR author), ``@m-ou-se`` (original r+), ``@scottmcm`` (last voice in tracking issue, prompted me to post this)
Closes#86269 (removed)
Fix copy-paste error in String::as_mut_vec() docs
Did not expect the comments to be perfectly justified... can't wait to be told to change it to `Vec<u8>`, which destroys the justification 😼
Fix and extent ControlFlow `traverse_inorder` example
Fix and extent ControlFlow `traverse_inorder` example
1. The existing example compiles on its own, but any usage fails to be monomorphised and so doesn't compile. Fix that by using Fn trait instead of FnMut.
2. Added an example usage of `traverse_inorder` showing how we can terminate the traversal early.
Fixes#90063
1. The existing example compiles on its own, but any usage fails
to be monomorphised and so doesn't compile. Fix that by using
a mutable reference as an input argument.
2. Added an example usage of `traverse_inorder` showing how we
can terminate the traversal early.
Fixes#90063
This fixes warning when building Rust and running tests:
```
warning: library kind `static-nobundle` has been superseded by specifying `-bundle` on library kind `static`. Try `static:-bundle`
warning: `rustc_llvm` (lib) generated 2 warnings (1 duplicate)
```
Fix and extent ControlFlow `traverse_inorder` example
1. The existing example compiles on its own, but any usage fails to be monomorphised and so doesn't compile. Fix that by using Fn trait instead of FnMut.
2. Added an example usage of `traverse_inorder` showing how we can terminate the traversal early.
Fixes#90063
Make RSplit<T, P>: Clone not require T: Clone
This addresses a TODO comment. The behavior of `#[derive(Clone)]` *does* result in a `T: Clone` requirement. Playground example:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a8b1a9581ff8893baf401d624a53d35b
Add a manual `Clone` implementation, mirroring `Split` and `SplitInclusive`.
`(R)?SplitN(Mut)?` don't have any `Clone` implementations, but I'll leave that for its own pull request.
Stabilise unix_process_wait_more, extra ExitStatusExt methods
This stabilises the feature `unix_process_wait_more`. Tracking issue #80695, FCP needed.
This was implemented in #79982 and merged in January.
Implement split_array and split_array_mut
This implements `[T]::split_array::<const N>() -> (&[T; N], &[T])` and `[T; N]::split_array::<const M>() -> (&[T; M], &[T])` and their mutable equivalents. These are another few “missing” array implementations now that const generics are a thing, similar to #74373, #75026, etc. Fixes#74674.
This implements `[T; N]::split_array` returning an array and a slice. Ultimately, this is probably not what we want, we would want the second return value to be an array of length N-M, which will likely be possible with future const generics enhancements. We need to implement the array method now though, to immediately shadow the slice method. This way, when the slice methods get stabilized, calling them on an array will not be automatic through coercion, so we won't have trouble stabilizing the array methods later (cf. into_iter debacle).
An unchecked version of `[T]::split_array` could also be added as in #76014. This would not be needed for `[T; N]::split_array` as that can be compile-time checked. Edit: actually, since split_at_unchecked is internal-only it could be changed to be split_array-only.
My change to use `Type::def_id()` (formerly `Type::def_id_full()`) in
more places caused some docs to show up that used to be missed by
rustdoc. Those docs contained unescaped square brackets, which triggered
linkcheck errors. This commit escapes the square brackets and adds this
particular instance to the linkcheck exception list.
Inline CStr::from_ptr
Inlining this function is valuable, as it allows LLVM to apply `strlen`-specific optimizations without having to enable LTO.
For instance, the following function:
```rust
pub fn f(p: *const c_char) -> Option<u8> {
unsafe { CStr::from_ptr(p) }.to_bytes().get(0).copied()
}
```
Looks like this if `CStr::from_ptr` is allowed to be inlined.
```asm
before:
push rax
call qword ptr [rip + std::ffi::c_str::CStr::from_ptr@GOTPCREL]
mov rcx, rax
cmp rdx, 1
sete dl
test rax, rax
sete al
or al, dl
jne .LBB1_2
mov dl, byte ptr [rcx]
.LBB1_2:
xor al, 1
pop rcx
ret
after:
mov dl, byte ptr [rdi]
test dl, dl
setne al
ret
```
Note that optimization turned this from O(N) to O(1) in terms of performance, as LLVM knows that it doesn't really need to call `strlen` to determine whether a string is empty or not.
Stabilize feature `saturating_div` for rust 1.58.0
The tracking issue is #89381
This seems like a reasonable simple change(?). The feature `saturating_div` was added as part of the ongoing effort to implement a `Saturating` integer type (see #87921). The implementation has been discussed [here](https://github.com/rust-lang/rust/pull/87921#issuecomment-899357720) and [here](https://github.com/rust-lang/rust/pull/87921#discussion_r691888556). It extends the list of saturating operations on integer types (like `saturating_add`, `saturating_sub`, `saturating_mul`, ...) by the function `fn saturating_div(self, rhs: Self) -> Self`.
The stabilization of the feature `saturating_int_impl` (for the `Saturating` type) needs to have this stabilized first.
Closes#89381
This addresses a TODO comment. The behavior of #[derive(Clone)]
*does* result in a T: Clone requirement.
Add a manual Clone implementation, matching Split and SplitInclusive.
Previously, it wasn't clear whether "This could include" was referring
to logic errors, or undefined behaviour. Tweak wording to clarify this
sentence does not relate to UB.
Fix MIRI UB in `Vec::swap_remove`
Fixes#90055
I find it weird that `Vec::swap_remove` read the last element to the stack just to immediately put it back in the `Vec` in place of the one at index `index`. It seems much more natural to me to just read the element at position `index` and then move the last element in its place. I guess this might also slightly improve codegen.
Make `From` impls of NonZero integer const.
I also changed the feature gate added to `From` impls of Atomic integer to `const_num_from_num` from `const_convert`.
Tracking issue: #87852
Avoid overflow in `VecDeque::with_capacity_in()`.
The overflow only happens if alloc is compiled with overflow checks enabled and the passed capacity is greater or equal 2^(usize::BITS-1). The overflow shadows the expected "capacity overflow" panic leading to a test failure if overflow checks are enabled for std in the CI.
Unblocks [CI: Enable overflow checks for test (non-dist) builds #89776](https://github.com/rust-lang/rust/pull/89776).
For some reason the overflow is only observable with optimization turned off, but that is a separate issue.
Stabilize CString::from_vec_with_nul[_unchecked]
Closes the tracking issue #73179. I am keeping this in _draft_ mode until the FCP has ended.
This is my first time stabilizing a feature, so I would appreciate any guidance on things I should do differently.
Closes#73179
Remove unnecessary condition in Barrier::wait()
This is my first pull request for Rust, so feel free to call me out if anything is amiss.
After some examination, I realized that the second condition of the "spurious-wakeup-handler" loop in ``std::sync::Barrier::wait()`` should always evaluate to ``true``, making it redundant in the ``&&`` expression.
Here is the affected function before the fix:
```rust
#[stable(feature = "rust1", since = "1.0.0")]
pub fn wait(&self) -> BarrierWaitResult {
let mut lock = self.lock.lock().unwrap();
let local_gen = lock.generation_id;
lock.count += 1;
if lock.count < self.num_threads {
// We need a while loop to guard against spurious wakeups.
// https://en.wikipedia.org/wiki/Spurious_wakeup
while local_gen == lock.generation_id && lock.count < self.num_threads { // fixme
lock = self.cvar.wait(lock).unwrap();
}
BarrierWaitResult(false)
} else {
lock.count = 0;
lock.generation_id = lock.generation_id.wrapping_add(1);
self.cvar.notify_all();
BarrierWaitResult(true)
}
}
```
At first glance, it seems that the check that ``lock.count < self.num_threads`` would be necessary in order for a thread A to detect when another thread B has caused the barrier to reach its thread count, making thread B the "leader".
However, the control flow implicitly results in an invariant that makes observing ``!(lock.count < self.num_threads)``, i.e. ``lock.count >= self.num_threads`` impossible from thread A.
When thread B, which will be the leader, calls ``.wait()`` on this shared instance of the ``Barrier``, it locks the mutex in the first line and saves the ``MutexGuard`` in the ``lock`` variable. It then increments the value of ``lock.count``. However, it then proceeds to check if ``lock.count < self.num_threads``. Since it is the leader, it is the case that (after the increment of ``lock.count``), the lock count is *equal* to the number of threads. Thus, the second branch is immediately taken and ``lock.count`` is zeroed. Additionally, the generation ID is incremented (with wrap). Then, the condition variable is signalled. But, the other threads are waiting at the line ``lock = self.cvar.wait(lock).unwrap();``, so they cannot resume until thread B's call to ``Barrier::wait()`` returns, which drops the ``MutexGuard`` acquired in the first ``let`` statement and unlocks the mutex.
The order of events is thus:
1. A thread A calls `.wait()`
2. `.wait()` acquires the mutex, increments `lock.count`, and takes the first branch
3. Thread A enters the ``while`` loop since the generation ID has not changed and the count is less than the number of threads for the ``Barrier``
3. Spurious wakeups occur, but both conditions hold, so the thread A waits on the condition variable
4. This process repeats for N - 2 additional times for non-leader threads A'
5. *Meanwhile*, Thread B calls ``Barrier::wait()`` on the same barrier that threads A, A', A'', etc. are waiting on. The thread count reaches the number of threads for the ``Barrier``, so all threads should now proceed, with B being the leader. B acquires the mutex and increments the value ``lock.count`` only to find that it is not less than ``self.num_threads``. Thus, it immediately clamps ``self.num_threads`` back down to 0 and increments the generation. Then, it signals the condvar to tell the A (prime) threads that they may continue.
6. The A, A', A''... threads wake up and attempt to re-acquire the ``lock`` as per the internal operation of a condition variable. When each A has exclusive access to the mutex, it finds that ``lock.generation_id`` no longer matches ``local_generation`` **and the ``&&`` expression short-circuits -- and even if it were to evaluate it, ``self.count`` is definitely less than ``self.num_threads`` because it has been reset to ``0`` by thread B *before* B dropped its ``MutexGuard``**.
Therefore, it my understanding that it would be impossible for the non-leader threads to ever see the second boolean expression evaluate to anything other than ``true``. This PR simply removes that condition.
Any input would be appreciated. Sorry if this is terribly verbose. I'm new to the Rust community and concurrency can be hard to explain in words. Thanks!
Reject octal zeros in IPv4 addresses
This fixes#86964 by rejecting octal zeros in IP addresses, such that `192.168.00.00000000` is rejected with a parse error, since having leading zeros in front of another zero indicates it is a zero written in octal notation, which is not allowed in the strict mode specified by RFC 6943 3.1.1. Octal rejection was implemented in #83652, but due to the way it was implemented octal zeros were still allowed.
Make more `From` impls `const` (libcore)
Adding `const` to `From` implementations in the core. `rustc_const_unstable` attribute is not added to unstable implementations.
Tracking issue: #88674
<details>
<summary>Done</summary><div>
- `T` from `T`
- `T` from `!`
- `Option<T>` from `T`
- `Option<&T>` from `&Option<T>`
- `Option<&mut T>` from `&mut Option<T>`
- `Cell<T>` from `T`
- `RefCell<T>` from `T`
- `UnsafeCell<T>` from `T`
- `OnceCell<T>` from `T`
- `Poll<T>` from `T`
- `u32` from `char`
- `u64` from `char`
- `u128` from `char`
- `char` from `u8`
- `AtomicBool` from `bool`
- `AtomicPtr<T>` from `*mut T`
- `AtomicI(bits)` from `i(bits)`
- `AtomicU(bits)` from `u(bits)`
- `i(bits)` from `NonZeroI(bits)`
- `u(bits)` from `NonZeroU(bits)`
- `NonNull<T>` from `Unique<T>`
- `NonNull<T>` from `&T`
- `NonNull<T>` from `&mut T`
- `Unique<T>` from `&mut T`
- `Infallible` from `!`
- `TryIntError` from `!`
- `TryIntError` from `Infallible`
- `TryFromSliceError` from `Infallible`
- `FromResidual for Option<T>`
</div></details>
<details>
<summary>Remaining</summary><dev>
- `NonZero` from `NonZero`
These can't be made const at this time because these use Into::into.
https://github.com/rust-lang/rust/blob/master/library/core/src/convert/num.rs#L393
- `std`, `alloc`
There may still be many implementations that can be made `const`.
</div></details>
remove unnecessary bound on Zip specialization impl
I originally added this bound in an attempt to make the specialization
sound for owning iterators but it was never correct here and the correct
and [already implemented](497ee321af/library/alloc/src/vec/into_iter.rs (L220-L232)) solution is is to place it on the IntoIter
implementation.
Alloc features cleanup
This sorts and categorizes the `#![features]` in `alloc` and removes unused ones.
This is part of #87766
The following feature attributes were unnecessary and are removed:
```diff
// Library features:
-#![feature(cow_is_borrowed)]
-#![feature(maybe_uninit_uninit_array)]
-#![feature(slice_partition_dedup)]
// Language features:
-#![feature(arbitrary_self_types)]
-#![feature(auto_traits)]
-#![feature(box_patterns)]
-#![feature(decl_macro)]
-#![feature(nll)]
```
Automatic exponential formatting in Debug
Context: See [this comment from the libs team](https://github.com/rust-lang/rfcs/pull/2729#issuecomment-853454204)
---
Makes `"{:?}"` switch to exponential for floats based on magnitude. The libs team suggested exploring this idea in the discussion thread for RFC rust-lang/rfcs#2729. (**note:** this is **not** an implementation of the RFC; it is an implementation of one of the alternatives)
Thresholds chosen were 1e-4 and 1e16. Justification described [here](https://github.com/rust-lang/rfcs/pull/2729#issuecomment-864482954).
**This will require a crater run.**
---
As mentioned in the commit message of 8731d4dfb4, this behavior will not apply when a precision is supplied, because I wanted to preserve the following existing and useful behavior of `{:.PREC?}` (which recursively applies `{:.PREC}` to floats in a struct):
```rust
assert_eq!(
format!("{:.2?}", [100.0, 0.000004]),
"[100.00, 0.00]",
)
```
I looked around and am not sure where there are any tests that actually use this in the test suite, though?
All things considered, I'm surprised that this change did not seem to break even a single existing test in `x.py test --stage 2`. (even when I tried a smaller threshold of 1e6)
Rollup of 8 pull requests
Successful merges:
- #89766 (RustWrapper: adapt for an LLVM API change)
- #89867 (Fix macro_rules! duplication when reexported in the same module)
- #89941 (removing TLS support in x86_64-unknown-none-hermitkernel)
- #89956 (Suggest a case insensitive match name regardless of levenshtein distance)
- #89988 (Do not promote values with const drop that need to be dropped)
- #89997 (Add test for issue #84957 - `str.as_bytes()` in a `const` expression)
- #90002 (⬆️ rust-analyzer)
- #90034 (Tiny tweak to Iterator::unzip() doc comment example.)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Tiny tweak to Iterator::unzip() doc comment example.
It's easier to figure out what it's doing and which output elements map to which input ones if the matrix we are dealing with is rectangular 2x3 rather than square 2x2.
removing TLS support in x86_64-unknown-none-hermitkernel
HermitCore's kernel itself doesn't support TLS. Consequently, the entries in x86_64-unknown-none-hermitkernel should be removed. This commit should help to finalize #89062.
Revert "Auto merge of #89709 - clemenswasser:apply_clippy_suggestions…
…_2, r=petrochenkov"
The PR had some unforseen perf regressions that are not as easy to find.
Revert the PR for now.
This reverts commit 6ae8912a3e, reversing
changes made to 86d6d2b738.
It's easier to figure out what it's doing and which output
elements map to which input ones if the matrix we are dealing
with is rectangular 2x3 rather than square 2x2.
Remove a mention to `copy_from_slice` from `clone_from_slice` doc
Fixes#84736
I think removing it would be the best but I'm happy to clarify it instead if someone would like.
linux/aarch64 Now() should be actually_monotonic()
While issues have been seen on arm64 platforms the Arm architecture requires
that the counter monotonically increases and that it must provide a uniform
view of system time (e.g. it must not be possible for a core to receive a
message from another core with a time stamp and observe time going backwards
(ARM DDI 0487G.b D11.1.2). While there have been a few 64bit SoCs that have
bugs (#49281, #56940) which cause time to not monotonically increase, these have
been fixed in the Linux kernel and we shouldn't penalize all Arm SoCs for those
who refuse to update their kernels:
SUN50I_ERRATUM_UNKNOWN1 - Allwinner A64 / Pine A64 - fixed in 5.1
FSL_ERRATUM_A008585 - Freescale LS2080A/LS1043A - fixed in 4.10
HISILICON_ERRATUM_161010101 - Hisilicon 1610 - fixed in 4.11
ARM64_ERRATUM_858921 - Cortex A73 - fixed in 4.12
255a3f3e18 std: Force `Instant::now()` to be monotonic added a Mutex to work around
this problem and a small test program using glommio shows the majority of time spent
acquiring and releasing this Mutex. 3914a7b0da tries to improve this, but actually
makes it worse on big systems as for 128b atomics a ldxp/stxp pair (and successful loop)
for v8.4 systems that don't support FEAT_LSE2 is required which is expensive as a lock
and because of how the load/store-exclusives scale on large Arm systems is both unfair
to threads and tends to go backwards in performance.
A small sample program using glommio improves by 70x on a 32 core Graviton2
system with this change.
Add `#[repr(i8)]` to `Ordering`
Followup to #89491 to allow `Ordering` to auto-derive `AsRepr` once the proposal to add `AsRepr` (#81642) lands.
cc ``@joshtriplett``
updating docs to mention usage of AtomicBool
Mouse mentioned we should point out that atomic bool is used by the std lib these days. ( https://github.com/m-ou-se/getrandom/pull/1 )
[fuchsia] Update process info struct
The fuchsia platform is in the process of softly transitioning over to
using a new value for ZX_INFO_PROCESS with a new corresponding struct.
This change migrates libstd.
See [fxrev.dev/510478](https://fxrev.dev/510478) and [fxbug.dev/30751](https://fxbug.dev/30751) for more detail.
Stabilize `unreachable_unchecked` as `const fn`
Closes#53188
This PR stabilizes `core::hint::unreachable_unchecked` as `const fn`. MIRI is able to detect when this method is called. Stabilization was delayed until `const_panic` was stabilized so as to avoid users calling this method in its place (thus resulting in runtime UB). With #89508, that is no longer an issue.
````@rustbot```` label +A-const-eval +A-const-fn +T-lang +S-blocked
(not sure why it's T-lang, but that's what the tracking issue is)
Add abstract namespace support for Unix domain sockets
Hello! The other day I wanted to mess around with UDS in Rust and found that abstract namespaces ([unix(7)](https://man7.org/linux/man-pages/man7/unix.7.html)) on Linux still needed development. I took the approach of adding `_addr` specific public functions to reduce conflicts.
Feature name: `unix_socket_abstract`
Tracking issue: #85410
Further context: #42048
## Non-platform specific additions
`UnixListener::bind_addr(&SocketAddr) -> Result<UnixListener>`
`UnixStream::connect_addr(&SocketAddr) -> Result<()>`
`UnixDatagram::bind_addr(&SocketAddr) -> Result<UnixDatagram>`
`UnixDatagram::connect_addr(&SocketAddr) -> Result<()>`
`UnixDatagram::send_to_addr(&self, &[u8], &SocketAddr) -> Result<usize>`
## Platform-specific (Linux) additions
`SocketAddr::from_abstract_namespace(&[u8]) -> SocketAddr`
`SockerAddr::as_abstract_namespace() -> Option<&[u8]>`
## Example
```rust
#![feature(unix_socket_abstract)]
use std::os::unix::net::{UnixListener, SocketAddr};
fn main() -> std::io::Result<()> {
let addr = SocketAddr::from_abstract_namespace(b"namespace")?; // Linux only
let listener = match UnixListener::bind_addr(&addr) {
Ok(sock) => sock,
Err(err) => {
println!("Couldn't bind: {:?}", err);
return Err(err);
}
};
Ok(())
}
```
## Further Details
The main inspiration for the implementation came from the [nix-rust](https://github.com/nix-rust/nix/blob/master/src/sys/socket/addr.rs#L558) crate but there are also other [historical](c4db0685b1) [attempts](https://github.com/tormol/uds/blob/master/src/addr.rs#L324) with similar approaches.
A comment I did have was with this change, we now allow a `SocketAddr` to be constructed explicitly rather than just used almost as a handle for the return of `peer_addr` and `local_addr`. We could consider adding other explicit constructors (e.g. `SocketAddr::from_pathname`, `SockerAddr::from_unnamed`).
Cheers!
Use BCryptGenRandom instead of RtlGenRandom on Windows.
This removes usage of RtlGenRandom on Windows, in favour of BCryptGenRandom.
BCryptGenRandom isn't available on XP, but we dropped XP support a while ago.
The fuchsia platform is in the process of softly transitioning over to
using a new value for ZX_INFO_PROCESS with a new corresponding struct.
This change migrates libstd.
See fxrev.dev/510478 and fxbug.dev/30751 for more detail.
Avoid allocations and copying in Vec::leak
The [`Vec::leak`] method (#62195) is currently implemented by calling `Vec::into_boxed_slice` and `Box::leak`. This shrinks the vector before leaking it, which potentially causes a reallocation and copies the vector's contents.
By avoiding the conversion to `Box`, we can instead leak the vector without any expensive operations, just by returning a slice reference and forgetting the `Vec`. Users who *want* to shrink the vector first can still do so by calling `shrink_to_fit` explicitly.
**Note:** This could break code that uses `Box::from_raw` to “un-leak” the slice returned by `Vec::leak`. However, the `Vec::leak` docs explicitly forbid this, so such code is already incorrect.
[`Vec::leak`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.leak
Optimize VecDeque::append
Optimize `VecDeque::append` to do unsafe copy rather than iterating through each element.
On my `Intel(R) Xeon(R) CPU E5-2630 v4 @ 2.20GHz`, the benchmark shows 37% improvements:
```
Master:
custom-bench vec_deque_append 583164 ns/iter
custom-bench vec_deque_append 550040 ns/iter
Patched:
custom-bench vec_deque_append 349204 ns/iter
custom-bench vec_deque_append 368164 ns/iter
```
Additional notes on the context: this is the third attempt to implement a non-trivial version of `VecDeque::append`, the last two are reverted due to unsoundness or regression, see:
- https://github.com/rust-lang/rust/pull/52553, reverted in https://github.com/rust-lang/rust/pull/53571
- https://github.com/rust-lang/rust/pull/53564, reverted in https://github.com/rust-lang/rust/pull/54851
Both cases are covered by existing tests.
Signed-off-by: tabokie <xy.tao@outlook.com>
The PR had some unforseen perf regressions that are not as easy to find.
Revert the PR for now.
This reverts commit 6ae8912a3e, reversing
changes made to 86d6d2b738.
Fix ctrl-c causing reads of stdin to return empty on Windows.
Pressing ctrl+c (or ctrl+break) on Windows caused a blocking read of stdin to unblock and return empty, unlike other platforms which continue to block.
On ctrl-c, `ReadConsoleW` will return success, but also set `LastError` to `ERROR_OPERATION_ABORTED`.
This change detects this case, and re-tries the call to `ReadConsoleW`.
Fixes#89177. See issue for further details.
Tested on Windows 7 and Windows 10 with both MSVC and GNU toolchains
Add `const_eval_select` intrinsic
Adds an intrinsic that calls a given function when evaluated at compiler time, but generates a call to another function when called at runtime.
See https://github.com/rust-lang/const-eval/issues/7 for previous discussion.
r? `@oli-obk.`
Improve `std:🧵:available_parallelism` docs
_Tracking issue: https://github.com/rust-lang/rust/issues/74479_
This PR reworks the documentation of `std:🧵:available_parallelism`, as requested [here](https://github.com/rust-lang/rust/pull/89324#issuecomment-934343254).
## Changes
The following changes are made:
- We've removed prior mentions of "hardware threads" and instead centers the docs around "parallelism" as a resource available to a program.
- We now provide examples of when `available_parallelism` may return numbers that differ from the number of CPU cores in the host machine.
- We now mention that the amount of available parallelism may change over time.
- We make note of which platform components we don't take into account which more advanced users may want to take note of.
- The example has been updated, which should be a bit easier to use.
- We've added a docs alias to `num-cpus` which provides similar functionality to `available_parallelism`, and is one of the most popular crates on crates.io.
---
Thanks!
r? `@BurntSushi`
The unifying theme for this commit is weak, admittedly. I put together a
list of "expensive" functions when I originally proposed this whole
effort, but nobody's cared about that criterion. Still, it's a decent
way to bite off a not-too-big chunk of work.
Given the grab bag nature of this commit, the messages I used vary quite
a bit.
fix minor spelling error in Poll::ready docs
Fixes minor spelling error in the proposed `Poll::ready` docs. Not that my opinion matters, but +1 on the original PR (#89651), it reads much nicer to me than the `ready!` macro.
Add #[must_use] to is_condition tests
I threw in `std::path::Path::has_root` for funsies.
A continuation of #89718.
Parent issue: #89692
r? ```@joshtriplett```
Add #[must_use] to non-mutating verb methods
These are methods that could be misconstrued to mutate their input, similar to #89694. I gave each one a different custom message.
I wrote that `upgrade` and `downgrade` don't modify the input pointers. Logically they don't, but technically they do...
Parent issue: #89692
r? ```@joshtriplett```
Add #[must_use] to From::from and Into::into
Risk of churn: **High**
Magic 8-Ball says: **Outlook not so good**
I figured I'd put this out there. If we don't do it now maybe we save it for a rainy day.
Parent issue: #89692
r? `@joshtriplett`
Speedup int log10 branchless
This is achieved with a branchless bit-twiddling implementation of the case x < 100_000, and using this as building block.
Benchmark on an Intel i7-8700K (Coffee Lake):
```
name old ns/iter new ns/iter diff ns/iter diff % speedup
num::int_log::u8_log10_predictable 165 169 4 2.42% x 0.98
num::int_log::u8_log10_random 438 423 -15 -3.42% x 1.04
num::int_log::u8_log10_random_small 438 423 -15 -3.42% x 1.04
num::int_log::u16_log10_predictable 633 417 -216 -34.12% x 1.52
num::int_log::u16_log10_random 908 471 -437 -48.13% x 1.93
num::int_log::u16_log10_random_small 945 471 -474 -50.16% x 2.01
num::int_log::u32_log10_predictable 1,496 1,340 -156 -10.43% x 1.12
num::int_log::u32_log10_random 1,076 873 -203 -18.87% x 1.23
num::int_log::u32_log10_random_small 1,145 874 -271 -23.67% x 1.31
num::int_log::u64_log10_predictable 4,005 3,171 -834 -20.82% x 1.26
num::int_log::u64_log10_random 1,247 1,021 -226 -18.12% x 1.22
num::int_log::u64_log10_random_small 1,265 921 -344 -27.19% x 1.37
num::int_log::u128_log10_predictable 39,667 39,579 -88 -0.22% x 1.00
num::int_log::u128_log10_random 6,456 6,696 240 3.72% x 0.96
num::int_log::u128_log10_random_small 4,108 3,903 -205 -4.99% x 1.05
```
Benchmark on an M1 Mac Mini:
```
name old ns/iter new ns/iter diff ns/iter diff % speedup
num::int_log::u8_log10_predictable 143 130 -13 -9.09% x 1.10
num::int_log::u8_log10_random 375 325 -50 -13.33% x 1.15
num::int_log::u8_log10_random_small 376 325 -51 -13.56% x 1.16
num::int_log::u16_log10_predictable 500 322 -178 -35.60% x 1.55
num::int_log::u16_log10_random 794 405 -389 -48.99% x 1.96
num::int_log::u16_log10_random_small 1,035 405 -630 -60.87% x 2.56
num::int_log::u32_log10_predictable 1,144 894 -250 -21.85% x 1.28
num::int_log::u32_log10_random 832 786 -46 -5.53% x 1.06
num::int_log::u32_log10_random_small 832 787 -45 -5.41% x 1.06
num::int_log::u64_log10_predictable 2,681 2,057 -624 -23.27% x 1.30
num::int_log::u64_log10_random 1,015 806 -209 -20.59% x 1.26
num::int_log::u64_log10_random_small 1,004 795 -209 -20.82% x 1.26
num::int_log::u128_log10_predictable 56,825 56,526 -299 -0.53% x 1.01
num::int_log::u128_log10_random 9,056 8,861 -195 -2.15% x 1.02
num::int_log::u128_log10_random_small 1,528 1,527 -1 -0.07% x 1.00
```
The 128 bit case remains ridiculously slow because llvm fails to optimize division by a constant 128-bit value to multiplications. This could be worked around but it seems preferable to fix this in llvm.
From u32 up, table lookup (like suggested [here](https://github.com/rust-lang/rust/issues/70887#issuecomment-881099813)) is still faster, but requires a hardware `leading_zeros` to be viable, and might clog up the cache.
Fix ICE when compiling nightly std/rustc on beta compiler
Fix#89775#89479 renames a lot of diagnostic items, but it happens that the beta compiler assumes that there must be DefId with `rustc_diagnostic_item = "send_trait"`, causing an ICE when compiling stage 0 std or stage 1 compiler. So gate it with `cfg(bootstrap)`.
The unwrap is also removed, so that existence of the diagnostic item is not required. I ripgreped the code base and this seems the only place where `unwrap` is called on the return value of `get_diagnostic_item`.
Add `Poll::ready` and revert stabilization of `task::ready!`
This PR adds an inherent `ready` method to `Poll` that can be used with the `?` operator as an alternative to the `task::ready!` macro:
```rust
let val = ready!(fut.poll(cx));
let val = fut.poll(cx).ready()?;
```
I think this form is a nice, non-breaking middle ground between changing the `impl Try for Poll`, and adding a separate macro. It looks better than `ready!` in my opinion, and it composes well:
```rust
let elem = ready!(fut.poll(cx)).pop().unwrap();
let elem = fut.poll(cx).ready()?.pop().unwrap();
```
The planned stabilization of `ready!` in 1.56 has been reverted because I think this alternate approach is worth considering.
r? rust-lang/libs