Override PartialOrd methods for bool
I noticed that `PartialOrd` implementation for `bool` does not override the individual operator methods, unlike the other primitive types like `char` and integers.
This commit extracts these `PartialOrd` overrides shared by the other primitive types into a macro and calls it on `bool` too.
CC `@scottmcm` for our recent adventures in `PartialOrd` land
I noticed that `PartialOrd` implementation for `bool` does not override the
individual operator methods, unlike the other primitive types like `char`
and integers.
This commit extracts these `PartialOrd` overrides shared by the other
primitive types into a macro and calls it on `bool` too.
Simplify `PartialOrd` on tuples containing primitives
We noticed in https://github.com/rust-lang/rust/pull/133984#issuecomment-2704011800 that currently the tuple comparison code, while it [does optimize down](https://github.com/rust-lang/rust/blob/master/tests/codegen/comparison-operators-2-tuple.rs) today, is kinda huge: <https://rust.godbolt.org/z/xqMoeYbhE>
This PR changes the tuple code to go through an overridable "chaining" version of the comparison functions, so that for simple things like `(i16, u16)` and `(f32, f32)` (as seen in the new MIR pre-codegen test) we just directly get the
```rust
if lhs.0 == rhs.0 { lhs.0 OP rhs.0 }
else { lhs.1 OP rhs.1 }
```
version in MIR, rather than emitting a mess for LLVM to have to clean up.
Test added in the first commit, so you can see the MIR diff in the second one.
core: optimize `RepeatN`
...by adding an optimized implementation of `try_fold` and `fold` as well as replacing some unnecessary `mem::replace` calls with `MaybeUninit` helper methods.
...by adding an optimized implementation of `try_fold` and `fold` as well as replacing some unnecessary `mem::replace` calls with `MaybeUninit` helper methods.
Reduce FormattingOptions to 64 bits
This is part of https://github.com/rust-lang/rust/issues/99012
This reduces FormattingOptions from 6-7 machine words (384 bits on 64-bit platforms, 224 bits on 32-bit platforms) to just 64 bits (a single register on 64-bit platforms).
Before:
```rust
pub struct FormattingOptions {
flags: u32, // only 6 bits used
fill: char,
align: Option<Alignment>,
width: Option<usize>,
precision: Option<usize>,
}
```
After:
```rust
pub struct FormattingOptions {
/// Bits:
/// - 0-20: fill character (21 bits, a full `char`)
/// - 21: `+` flag
/// - 22: `-` flag
/// - 23: `#` flag
/// - 24: `0` flag
/// - 25: `x?` flag
/// - 26: `X?` flag
/// - 27: Width flag (if set, the width field below is used)
/// - 28: Precision flag (if set, the precision field below is used)
/// - 29-30: Alignment (0: Left, 1: Right, 2: Center, 3: Unknown)
/// - 31: Always set to 1
flags: u32,
/// Width if width flag above is set. Otherwise, always 0.
width: u16,
/// Precision if precision flag above is set. Otherwise, always 0.
precision: u16,
}
```
Add an attribute that makes the spans from a macro edition 2021, and fix pin on edition 2024 with it
Fixes a regression, see issue below. This is a temporary fix, super let is the real solution.
Closes#138596
This commit adds the 5f00::/16 range defined by RFC9602 to those ranges which Ipv6Addr::is_global recognises as a non-global IP. This range is used for Segment Routing (SRv6) SIDs.
Optimize `io::Write::write_fmt` for constant strings
When the formatting args to `fmt::Write::write_fmt` are a statically known string, it simplifies to only calling `write_str` without a runtime branch. Do the same in `io::Write::write_fmt` with `write_all`.
Also, match the convention of `fmt::Write` for the name of `args`.
`MaybeUninit` inherent slice methods part 2
These were moved out of #129259 since they require additional libs-api approval. Tracking issue: #117428.
New API surface:
```rust
impl<T> [MaybeUninit<T>] {
// replacing fill; renamed to avoid conflict
pub fn write_filled(&mut self, value: T) -> &mut [T] where T: Clone;
// replacing fill_with; renamed to avoid conflict
pub fn write_with<F>(&mut self, value: F) -> &mut [T] where F: FnMut() -> T;
// renamed to remove "fill" terminology, since this is closer to the write_*_of_slice methods
pub fn write_iter<I>(&mut self, iter: I) -> (&mut [T], &mut Self) where I: Iterator<Item = T>;
}
```
Relevant motivation for these methods; see #129259 for earlier methods' motiviations.
* I chose `write_filled` since `filled` is being used as an object here, whereas it's being used as an action in `fill`.
* I chose `write_with` instead of `write_filled_with` since it's shorter and still matches well.
* I chose `write_iter` because it feels completely different from the fill methods, and still has the intent clear.
In all of the methods, it felt appropriate to ensure that they contained `write` to clarify that they are effectively just special ways of doing `MaybeUninit::write` for each element of a slice.
Tracking issue: https://github.com/rust-lang/rust/issues/117428
r? libs-api
When the formatting args to `fmt::Write::write_fmt` are a statically
known string, it simplifies to only calling `write_str` without a
runtime branch. Do the same in `io::Write::write_fmt` with `write_all`.
Also, match the convention of `fmt::Write` for the name of `args`.
Denote `ControlFlow` as `#[must_use]`
I've repeatedly hit bugs in the compiler due to `ControlFlow` not being marked `#[must_use]`. There seems to be an accepted ACP to make the type `#[must_use]` (https://github.com/rust-lang/libs-team/issues/444), so this PR implements that part of it.
Most of the usages in the compiler that trigger this new warning are "root" usages (calling into an API that uses control-flow internally, but for which the callee doesn't really care) and have been suppressed by `let _ = ...`, but I did legitimately find one instance of a missing `?` and one for a never-used `ControlFlow` value in #137448.
Presumably this needs an FCP too, so I'm opening this and nominating it for T-libs-api.
This PR also touches the tools (incl. rust-analyzer), but if this went into FCP, I'd split those out into separate PRs which can land before this one does.
r? libs-api
`@rustbot` label: T-libs-api I-libs-api-nominated
Rollup of 5 pull requests
Successful merges:
- #136293 (document capacity for ZST as example)
- #136359 (doc all differences of ptr:copy(_nonoverlapping) with memcpy and memmove)
- #136816 (refactor `notable_traits_button` to use iterator combinators instead of for loop)
- #138552 (Misc print request handling cleanups + a centralized test for print request stability gating)
- #138573 (Make `_Unwind_Action` a type alias, not enum)
r? `@ghost`
`@rustbot` modify labels: rollup
Add `From<{integer}>` for `f16`/`f128` impls
This PR adds `impl From<{bool,i8,u8}> for f16` and `impl From<{bool,i8,u8,i16,u16,i32,u32}> for f128`.
The `From<{i64,u64}> for f128` impls are left commented out as adding them would allow using `f128` on stable before it is stabilised like in the following example:
```rust
fn f<T: From<u64>>(x: T) -> T { x }
fn main() {
let x = f(1.0); // the type of the literal is inferred to be `f128`
}
```
None of the impls added in this PR have this issue as they are all, at minimum, also implemented by `f64`.
This PR will need a crater run for the `From<{i32,u32}>` impls, as `f64` is no longer the only float type to implement them (similar to the cause of #125198).
cc `@bjoernager`
r? `@tgross35`
Tracking issue: #116909
Optimize multi-char string patterns
Uses specialization for `[T]::contains` from #130991 to optimize multi-char patterns in string searches.
Requesting a perf run to see if this actually has an effect 🙏
(I think that adding `char` to the list of types for which the `SliceContains` is specialized is a good idea, even if it doesn't show up on perf - might be helpful for downstream users)
core: Make `Debug` impl of raw pointers print metadata if present
Make Rust pointers appear less magic by including metadata information in their `Debug` output.
This does not break Rust stability guarantees because `Debug` impl are explicitly exempted from stability:
https://doc.rust-lang.org/std/fmt/trait.Debug.html#stability
> ## Stability
>
> Derived `Debug` formats are not stable, and so may change with future Rust versions. Additionally, `Debug` implementations of types provided by the standard library (`std`, `core`, `alloc`, etc.) are not stable, and may also change with future Rust versions.
Note that a regression test is added as a separate commit to make it clear what impact the last commit has on the output.
Closes#128684 because the output of that code now becomes:
```
thread 'main' panicked at src/main.rs:5:5:
assertion `left == right` failed
left: Pointer { addr: 0x7ffd45c6fc6b, metadata: 5 }
right: Pointer { addr: 0x7ffd45c6fc6b, metadata: 3 }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
debug-assert that the size_hint is well-formed in `collect`
Closes#137919
In the hopes of helping to catch any future accidentally-incorrect rustc or stdlib iterators (like the ones #137908 accidentally found), this has `Iterator::collect` call `size_hint` and check its `low` doesn't exceed its `Some(high)`.
There's of course a bazillion more places this *could* be checked, but the hope is that this one is a good tradeoff of being likely to catch lots of things while having minimal maintenance cost (especially compared to putting it in *every* container's `from_iter`).
Expand and organize `offset_of!` documentation.
* Give example of how to get the offset of an unsized tail field (prompted by discussion <https://github.com/rust-lang/rust/pull/133055#discussion_r1986422206>).
* Specify the return type.
* Add section headings.
* Reduce “Visibility is respected…”, to a single sentence.
* Move `offset_of_enum` documentation to unstable book (with link to it).
* Add `offset_of_slice` documentation in unstable book.
r? Mark-Simulacrum
Add missing doc for intrinsic (Fix PR135334)
The previous [PR135334](https://github.com/rust-lang/rust/pull/135334) mentioned that some of the intrinsic APIs were missing safety descriptions.
Among intrinsic APIs that miss safety specifications, most are related to numerical operations. They might need to be discussed and then seen how to organize.
Apart from them, only a few intrinsics lack safety. So this PR deals with the APIs with non-numerical operations in priority.
Remove `#[cfg(not(test))]` gates in `core`
These gates are unnecessary now that unit tests for `core` are in a separate package, `coretests`, instead of in the same files as the source code. They previously prevented the two `core` versions from conflicting with each other.
Expand `CloneToUninit` documentation.
* Clarify relationship to `dyn` after #133003.
* Add an example of using it with `dyn` as #133003 enabled.
* Replace parameter name `dst` with `dest` to avoid confusion between abbreviations for “DeSTination” and “Dynamically-Sized Type”.
* Add an example of implementing it.
* Add links to Rust Reference for the mentioned concepts.
* Mention that its method should rarely be called.
* Various small corrections.
Please review the `unsafe` code closely, as I am not an expert in the best possible ways to express these operations. (It might also be better to omit the implementation example entirely.)
cc `@zachs18` #126799
remove must_use from <*const T>::expose_provenance
`<*mut T>::expose_provenance` does not have this attribute, and in fact the function is documented to have a side-effect, so there are perfectly legitimate use-cases where the return value would be ignored.
atomic intrinsics: clarify which types are supported and (if applicable) what happens with provenance
The provenance semantics match what Miri implements and what the `AtomicPtr` API expects.
Reword incorrect documentation about SocketAddr having varying layout
This has no longer been the case since these types were moved to `core`. The note on portability remains, but it is reworded to not imply that the size varies by target.
Allow more top-down inlining for single-BB callees
This means that things like `<usize as Step>::forward_unchecked` and `<PartialOrd for f32>::le` will inline even if
we've already done a bunch of inlining to find the calls to them.
Fixes#138136
~~Draft as it's built atop #138135, which adds a mir-opt test that's a nice demonstration of this. To see just this change, look at <48f63e3be5>~~ Rebased to be just the inlining change, as the other existing tests show it great.