The final return value doesn't need to be tried at all -- we can just
return the checked option directly. The optimizer can probably figure
this out anyway, but there's no need to make it work here.
Clarify the possible return values of `len_utf16`
`char::len_utf16` always return 1 or 2. Clarify this in the docs, in the same way as `char::len_utf8`.
Add documentation about the memory layout of `UnsafeCell<T>`
The documentation for `UnsafeCell<T>` currently does not make any promises about its memory layout. This PR adds this documentation, namely that the memory layout of `UnsafeCell<T>` is the same as the memory layout of its inner `T`.
# Use case
Without this layout promise, the following cast would not be legally possible:
```rust
fn example<T>(ptr: *mut T) -> *const UnsafeCell<T> {
ptr as *const UnsafeCell<T>
}
```
A use case where this can come up involves FFI. If Rust receives a pointer over a FFI boundary which provides shared read-write access (with some form of custom synchronization), and this pointer is managed by some Rust struct with lifetime `'a`, then it would greatly simplify its (internal) API and safety contract if a `&'a UnsafeCell<T>` can be created from a raw FFI pointer `*mut T`. A lot of safety checks can be done when receiving the pointer for the first time through FFI (non-nullness, alignment, initialize uninit bytes, etc.) and these properties can then be encoded into the `&UnsafeCell<T>` type. Without this documentation guarantee, this is not legal today outside of the standard library.
# Caveats
Casting in the opposite direction is still not valid, even with this documentation change:
```rust
fn example2<T>(ptr: &UnsafeCell<T>) -> &mut T {
let t = ptr as *const UnsafeCell<T> as *mut T;
unsafe { &mut *t }
}
```
This is because the only legal way to obtain a mutable pointer to the contents of the shared reference is through [`UnsafeCell::get`](https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.get) and [`UnsafeCell::raw_get`](https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.raw_get). Although there might be a desire to also make this legal at some point in the future, that part is outside the scope of this PR. Also see this relevant [Zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-lang.2Fwg-unsafe-code-guidelines/topic/transmuting.20.26.20-.3E.20.26mut).
# Alternatives
Instead of adding a new documentation promise, it's also possible to add a new method to `UnsafeCell<T>` with signature `pub fn from_ptr_bikeshed(ptr: *mut T) -> *const UnsafeCell<T>` which indirectly only allows one-way casting to `*const UnsafeCell<T>`.
Fix `Duration::{try_,}from_secs_f{32,64}(-0.0)`
Make `Duration::{try_,}from_secs_f{32,64}(-0.0)` return `Duration::ZERO` (as they did before #90247) instead of erroring/panicking.
I'll update this PR to remove the `#![feature(duration_checked_float)]` if #102271 is merged before this PR.
Tracking issue for `try_from_secs_f{32,64}`: #83400
nicer errors from assert_unsafe_precondition
This makes the errors shown by cargo-careful nicer, and since `panic_no_unwind` is `nounwind noreturn` it hopefully doesn't have bad codegen impact. Thanks to `@bjorn3` for the hint!
Would be nice if we could somehow supply our own (static) message to print, currently it always prints `panic in a function that cannot unwind`. But still, this is better than before.
Warn about safety of `fetch_update`
Specifically as it relates to the ABA problem.
`fetch_update` is a useful function, and one that isn't provided by, say, C++. However, this does not mean the function is magic. It is implemented in terms of `compare_exchange_weak`, and in particular, suffers from the ABA problem. See the following code, which is a naive implementation of `pop` in a lock-free queue:
```rust
fn pop(&self) -> Option<i32> {
self.front.fetch_update(Ordering::Relaxed, Ordering::Acquire, |front| {
if front == ptr::null_mut() {
None
}
else {
Some(unsafe { (*front).next })
}
}.ok()
}
```
This code is unsound if called from multiple threads because of the ABA problem. Specifically, suppose nodes are allocated with `Box`. Suppose the following sequence happens:
```
Initial: Queue is X -> Y.
Thread A: Starts popping, is pre-empted.
Thread B: Pops successfully, twice, leaving the queue empty.
Thread C: Pushes, and `Box` returns X (very common for allocators)
Thread A: Wakes up, sees the head is still X, and stores Y as the new head.
```
But `Y` is deallocated. This is undefined behaviour.
Adding a note about this problem to `fetch_update` should hopefully prevent users from being misled, and also, a link to this common problem is, in my opinion, an improvement to our docs on atomics.
slice: #[inline] a couple iterator methods.
The one I care about and actually saw in the wild not getting inlined is
clone(). We ended up doing a whole function call for something that just
copies two pointers.
I ended up marking as_slice / as_ref as well because make_slice is
inline(always) itself, and is also the kind of think that can kill
performance in hot loops if you expect it to get inlined. But happy to
undo those.
Uplift `clippy::for_loops_over_fallibles` lint into rustc
This PR, as the title suggests, uplifts [`clippy::for_loops_over_fallibles`] lint into rustc. This lint warns for code like this:
```rust
for _ in Some(1) {}
for _ in Ok::<_, ()>(1) {}
```
i.e. directly iterating over `Option` and `Result` using `for` loop.
There are a number of suggestions that this PR adds (on top of what clippy suggested):
1. If the argument (? is there a better name for that expression) of a `for` loop is a `.next()` call, then we can suggest removing it (or rather replacing with `.by_ref()` to allow iterator being used later)
```rust
for _ in iter.next() {}
// turns into
for _ in iter.by_ref() {}
```
2. (otherwise) We can suggest using `while let`, this is useful for non-iterator, iterator-like things like [async] channels
```rust
for _ in rx.recv() {}
// turns into
while let Some(_) = rx.recv() {}
```
3. If the argument type is `Result<impl IntoIterator, _>` and the body has a `Result<_, _>` type, we can suggest using `?`
```rust
for _ in f() {}
// turns into
for _ in f()? {}
```
4. To preserve the original behavior and clear intent, we can suggest using `if let`
```rust
for _ in f() {}
// turns into
if let Some(_) = f() {}
```
(P.S. `Some` and `Ok` are interchangeable depending on the type)
I still feel that the lint wording/look is somewhat off, so I'll be happy to hear suggestions (on how to improve suggestions :D)!
Resolves#99272
[`clippy::for_loops_over_fallibles`]: https://rust-lang.github.io/rust-clippy/master/index.html#for_loops_over_fallibles
Remove empty core::lazy and std::lazy
PR #98165 with commits 7c360dc117 and c1a2db3372 has moved all of the components of these modules into different places, namely {std,core}::sync and {std,core}::cell. The empty modules remained. As they are unstable, we can simply remove them.
`EscapeAscii` is not an `ExactSizeIterator`
Fixes#99878
Do we want/need `EscapeAscii` to be an `ExactSizeIterator`? I guess we could precompute the length of the output if so?
add a few more assert_unsafe_precondition
Add debug-assertion checking for `ptr.read()`, `ptr.write(_)`, and `unreachable_unchecked.`
This is quite useful for [cargo-careful](https://github.com/RalfJung/cargo-careful).
PR #98165 with commits 7c360dc117 and c1a2db3372
has moved all of the components of these modules into different places,
namely {std,core}::sync and {std,core}::cell. The empty
modules remained. As they are unstable, we can simply remove them.
Use a macro to not have to copy-paste `ConstFnMutClosure::new(&mut fold, NeverShortCircuit::wrap_mut_2_imp)).0` everywhere
Also use that macro to replace a bunch of places that had custom closure-wrappers.
+35 -114 sounds good to me.
Implement `Ready::into_inner()`
Tracking issue: #101196.
This implements a method to unwrap the value inside a `Ready` outside an async context.
See https://docs.rs/futures/0.3.24/futures/future/struct.Ready.html#method.into_inner for previous work.
This was discussed in [Zulip beforehand](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/.60Ready.3A.3Ainto_inner.28.29.60):
> An example I'm hitting right now:
I have a cross-platform library that provides a functions that returns a `Future`. The only reason why it returns a `Future` is because the WASM platform requires it, but the native doesn't, to make a cross-platform API that is equal for all I just return a `Ready` on the native targets.
>
> Now I would like to expose native-only functions that aren't async, that users can use to avoid having to deal with async when they are targeting native. With `into_inner` that's easily solvable now.
>
> I want to point out that some internal restructuring could be used to solve that problem too, but in this case it's not that simple, the library uses internal traits that return the `Future` already and playing around with that would introduce unnecessary `cfg` in a lot more places. So it is really only a quality-of-life feature.
Change the parameter name of From::from to `value`
The `From` trait is currently defined as:
```rust
pub trait From<T>: Sized {
fn from(_: T) -> Self;
}
```
The name of the argument is `_`. I am proposing to change it to `value`, ie.
```rust
pub trait From<T>: Sized {
fn from(value: T) -> Self;
}
```
This would be more consistent with the `TryFrom`, which looks like this:
```rust
pub trait TryFrom<T>: Sized {
type Error;
fn try_from(value: T) -> Result<Self, Self::Error>;
}
```
The reason for this proposal is twofold:
1. Consistency with the rest of the standard library. The `TryFrom` trait uses `value`, and no `From` implementation uses the default name (as it is quite useless).
2. When generating trait implementations with rust-analyzer/IntelliJ, the parameter name is copied, and it always has to be changed.
Optionally, another name like `x` could be used. I only propose `value` for consistency with `TryFrom`.
Changing parameter names is not a breaking change.
Note: this was originally posted as an internals thread [here](https://internals.rust-lang.org/t/change-the-argument-name-of-from-from/17480)
Add T to PhantomData impl Debug
This add debug information for `PhantomData`, I believe it's make sense to add this to debug impl of `PhantomData` since `T` is what define what is the `PhantomData` just write `"PhantomData"` is not very useful for debugging.
Alternative:
* `PhantomData::<{}>`
* `PhantomData { t: "str_type" }`
`@rustbot` label +T-libs-api -T-libs
introduce `{char, u8}::is_ascii_octdigit`
This feature adds two new APIs: `char::is_ascii_octdigit` and `u8::is_ascii_octdigit`, under the feature gate `is_ascii_octdigit`. These methods are shorthands for `char::is_digit(self, 8)` and `u8::is_digit(self, 8)`:
```rust
// core::char
impl char {
pub fn is_ascii_octdigit(self) -> bool;
}
// core::num
impl u8 {
pub fn is_ascii_octdigit(self) -> bool;
}
```
---
Couple of things I need help understanding:
- `const`ness: have I used the right attribute in this case?
- is there a way to run the tests for `core::char` alone, instead of `./x.py test library/core`?
docs: Improve AsRef / AsMut docs on blanket impls
There are several issues with the current state of `AsRef` and `AsMut` as [discussed here on IRLO](https://internals.rust-lang.org/t/semantics-of-asref/17016). See also #39397, #45742, #73390, #98905, and the FIXMEs [here](https://github.com/rust-lang/rust/blob/1.62.0/library/core/src/convert/mod.rs#L509-L515) and [here](https://github.com/rust-lang/rust/blob/1.62.0/library/core/src/convert/mod.rs#L530-L536). These issues are difficult to fix. This PR aims to update the documentation to better reflect the status-quo and to give advice on how `AsRef` and `AsMut` should be used.
In particular:
- Explicitly mention that `AsRef` and `AsMut` do not auto-dereference generally for all dereferencable types (but only if inner type is a shared and/or mutable reference)
- Give advice to not use `AsRef` or `AsMut` for the sole purpose of dereferencing
- Suggest providing a transitive `AsRef` or `AsMut` implementation for types which implement `Deref`
- Add new section "Reflexivity" in documentation comments for `AsRef` and `AsMut`
- Provide better example for `AsMut`
- Added heading "Relation to `Borrow`" in `AsRef`'s docs to improve structure
Improve documentation of `slice::{from_ptr_range, from_ptr_range_mut}`
Document panic conditions (`T` is a ZST) and sync docs of shared/unique version.
cc `@wx-csy`
Improve `FromStr` example
The `from_str` implementation from the example had an `unwrap` that would make it panic on invalid input strings. Instead of panicking, it nows returns an error to better reflect the intented behavior of the `FromStr` trait.
The `from_str` implementation from the example had an `unwrap` that would make it panic on invalid input strings. Instead of panicking, it nows returns an error to better reflect the intented behavior of the `FromStr` trait.
Add negation methods for signed non-zero integers.
Performing negation with defined wrapping semantics (such as `wrapping_neg()`) on a non-zero integer currently requires unpacking to a primitive and re-wrapping. Since negation of non-zero signed integers always produces a non-zero result, it is safe to implement the various `*_neg()` methods for `NonZeroI{N}`.
I'm not sure what to do about the `#[unstable(..., issue = "none")]` here -- should I file a tracking issue, or is that handled by the Rust dev team?
ACP: https://github.com/rust-lang/libs-team/issues/105
Add a niche to `Duration`, unix `SystemTime`, and non-apple `Instant`
As the nanoseconds fields is always between `0` and `(NANOS_PER_SEC - 1)` inclusive, use the `rustc_layout_scalar_valid_range` attributes to create a niche in the nanosecond field of `Duration` and `Timespec` (which is used to implement unix `SystemTime` and non-apple unix `Instant`; windows `Instant` is implemented with `Duration` and therefore will also benefit). This change has the benefit of making `Option<T>` the same size as `T` for the previously mentioned types. Also shrinks the nanoseconds field of `Timespec` to a `u32` as nanoseconds do not need the extra range of an `i64`, shrinking `Timespec` by 4 bytes on 32-bit platforms.
r? ```@joshtriplett```
Add `#[rustc_safe_intrinsic]`
This PR adds the `#[rustc_safe_intrinsic]` attribute as mentionned on Zulip. The goal of this attribute is to avoid keeping a list of symbols as the source for stable intrinsics, and instead rely on an attribute. This is similar to `#[rustc_const_stable]` and `#[rustc_const_unstable]`, which among other things, are used to mark the constness of intrinsic functions.
Suggest unwrapping `???<T>` if a method cannot be found on it but is present on `T`.
This suggests various ways to get inside wrapper types if the method cannot be found on the wrapper type, but is present on the wrappee.
For this PR, those wrapper types include `Localkey`, `MaybeUninit`, `RefCell`, `RwLock` and `Mutex`.
Stabilize bench_black_box
This PR stabilize `feature(bench_black_box)`.
```rust
pub fn black_box<T>(dummy: T) -> T;
```
The FCP was completed in https://github.com/rust-lang/rust/issues/64102.
`@rustbot` label +T-libs-api -T-libs
Stabilize `#![feature(mixed_integer_ops)]`
Tracked and FCP completed in #87840.
````@rustbot```` label +T-libs-api +S-waiting-on-review +relnotes
r? rust-lang/t-libs-api
Constify Default impl's for Arrays and Tuples.
Allows to create arrays and tuples in const Context using the ~const Default implementation of the inner type.
Constify slice.split_at_mut(_unchecked)
Tracking Issue: [Tracking Issue for const_slice_split_at_mut](https://github.com/rust-lang/rust/issues/101804)
Feature gate: `#![feature(const_slice_split_at_mut)]`
Still requires const_mut_refs to be actually used, but this feature removes the need to manually re implement these functions in a user crate.
Clarify `[T]::select_nth_unstable*` return values
In cases where the nth element is not unique within the slice, it is not
correct to say that the values in the returned triplet include ones for
"all elements" less/greater than that at the given index: indeed one (or
more) such values would then also contain elements equal to that at
the given index.
The text proposed here clarifies exactly what is returned, but in so
doing it is also documenting an implementation detail that previously
wasn't detailed: namely that the returned slices are slices into the
reordered slice. I don't think this can be contentious, because the
lifetimes of those returned slices are bound to that of the original
(now reordered) slice—so there really isn't any other reasonable
implementation that could have this behaviour; but nevertheless it's
probably best if `@rust-lang/libs-api` give it a nod?
Fixes#97982
r? `@m-ou-se`
`@rustbot` label +A-docs +C-bug +T-libs-api -T-libs
Make ZST checks in core/alloc more readable
There's a bunch of these checks because of special handing for ZSTs in various unsafe implementations of stuff.
This lets them be `T::IS_ZST` instead of `mem::size_of::<T>() == 0` every time, making them both more readable and more terse.
*Not* proposed for stabilization. Would be `pub(crate)` except `alloc` wants to use it too.
(And while it doesn't matter now, if we ever get something like #85836 making it a const can help codegen be simpler.)
Add const_closure, Constify Try trait
Adds a struct for creating const `FnMut` closures (for now just copy pasted form my [const_closure](https://crates.io/crates/const_closure) crate).
I'm not sure if this way is how it should be done.
The `ConstFnClosure` and `ConstFnOnceClosure` structs can probably also be entirely removed.
This is then used to constify the try trait.
Not sure if i should add const_closure in its own pr and maybe make it public behind a perma-unstable feature gate.
cc ```@fee1-dead``` ```@rust-lang/wg-const-eval```
Refactor some `std` code that works with pointer offstes
This PR replaces `pointer::offset` in standard library with `pointer::add` and `pointer::sub`, [re]moving some casts and using `.addr()` while we are at it.
This is a more complicated refactor than all other sibling PRs, so take a closer look when reviewing, please 😃 (though I've checked this multiple times and it looks fine).
r? ````@scottmcm````
_split off from #100746, continuation of #100822_
Add `#[inline]` to trivial functions on `core::sync::Exclusive`
When optimizing for size things like these sometimes don't inlined even though they're generic. This is bad because they're no-ops.
Only dodgy one is poll I guess since it forwards to the inner poll, but it's not like we're doing `#[inline(always)]` here.
Use internal iteration in `Iterator` comparison methods
Updates the `Iterator` methods `cmp_by`, `partial_cmp_by`, and `eq_by` to use internal iteration on `self`. I've also extracted their shared logic into a private helper function `iter_compare`, which will either short-circuit once the comparison result is known or return the comparison of the lengths of the iterators.
This change also indirectly benefits calls to `cmp`, `partial_cmp`, `eq`, `lt`, `le`, `gt`, and `ge`.
Unsurprising benchmark results: iterators that benefit from internal iteration (like `Chain`) see a speedup, while other iterators are unaffected.
```
name before ns/iter after ns/iter diff ns/iter diff % speedup
iter::bench_chain_partial_cmp 208,301 54,978 -153,323 -73.61% x 3.79
iter::bench_partial_cmp 55,527 55,702 175 0.32% x 1.00
iter::bench_lt 55,502 55,322 -180 -0.32% x 1.00
```
Add examples to `bool::then` and `bool::then_some`
Added examples to `bool::then` and `bool::then_some` to show the distinction between the eager evaluation of `bool::then_some` and the lazy evaluation of `bool::then`.
There's a bunch of these checks because of special handing for ZSTs in various unsafe implementations of stuff.
This lets them be `T::IS_ZST` instead of `mem::size_of::<T>() == 0` every time, making them both more readable and more terse.
*Not* proposed for stabilization at this time. Would be `pub(crate)` except `alloc` wants to use it too.
(And while it doesn't matter now, if we ever get something like 85836 making it a const can help codegen be simpler.)
Extend const_convert with const {FormResidual, Try} for ControlFlow.
Very small change so I just used the existing `const_convert` feature flag. #88674
Newly const API:
```
impl<B, C> const ops::Try for ControlFlow<B, C>;
impl<B, C> const ops::FromResidual for ControlFlow<B, C>;
```
`@usbalbin` I hope it is ok that I added to your feature.
Added examples to `bool::then` and `bool::then_some` to show the distinction between the eager evaluation of `bool::then_some` and the lazy evaluation of `bool::then`.
Optimize `array::IntoIter`
`.into_iter()` on arrays was slower than it needed to be (especially compared to slice iterator) since it uses `Range<usize>`, which needs to handle degenerate ranges like `10..4`.
This PR adds an internal `IndexRange` type that's like `Range<usize>` but with a safety invariant that means it doesn't need to worry about those cases -- it only handles `start <= end` -- and thus can give LLVM more information to optimize better.
I added one simple demonstration of the improvement as a codegen test.
(`vec::IntoIter` uses pointers instead of indexes, so doesn't have this problem, but that only works because its elements are boxed. `array::IntoIter` can't use pointers because that would keep it from being movable.)
`.into_iter()` on arrays was slower than it needed to be (especially compared to slice iterator) since it uses `Range<usize>`, which needs to handle degenerate ranges like `10..4`.
This PR adds an internal `IndexRange` type that's like `Range<usize>` but with a safety invariant that means it doesn't need to worry about those cases -- it only handles `start <= end` -- and thus can give LLVM more information to optimize better.
I added one simple demonstration of the improvement as a codegen test.
Make `from_waker`, `waker` and `from_raw` unstably `const`
Make
- `Context::from_waker`
- `Context::waker`
- `Waker::from_raw`
`const`.
Also added a small test.
Tone down explanation on RefCell::get_mut
The language around `RefCell::get_mut` is remarkably sketchy and especially to the novice seems to quite strongly discourage using the method ("be cautious", "Also, please be aware", "special circumstances", "usually not what you want"). It was added six years ago in #40634 due to confusion about when to use `get_mut` and `borrow_mut`.
While its signature limits the use-cases for `get_mut`, there is no chance for a safety footgun, and readers can be made aware of `borrow_mut` more softly. I've also just sent a [PR](https://github.com/rust-lang/rust-clippy/issues/9044) to lint situations where `get_mut` could be used to improve ergonomics and performance.
So this PR tones down the language around `get_mut` and also brings it more in line with [`std::sync::Mutex::get_mut()`](https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html#method.get_mut).
array docs - advertise how to get array from slice
On my first Rust project, I spent more time than I care to admit figuring out how to efficiently get an array from a slice. Update the array documentation to explain this a bit more clearly.
(As a side note, it's a bit unfortunate that get-array-from-slice is only available via trait since that means it can't be used from const functions yet.)
Constify impl Fn* &(mut) Fn*
Tracking Issue: [101803](https://github.com/rust-lang/rust/issues/101803)
Feature gate: `#![feature(const_fn_trait_ref_impls)]`
This feature allows using references to Fn* Items as Fn* Items themself in a const context.
Fix naming format of IEEE 754 standard
Currently the documentation of f64::min refers to "IEEE-754 2008" while the documentation of f64::minimum refers to "IEEE 754-2019".
Note that one has the format IEEE,hyphen,number,space,year while the other is IEEE,space,number,hyphen,year. The official IEEE site [1] uses the later format and it is also the one most commonly used throughout the codebase.
Update all comments and - more importantly - documentation to consistently use the official format.
[1] https://standards.ieee.org/ieee/754/4211/
On my first Rust project, I spent more time than I care to admit
figuring out how to efficiently get an array from a slice. Update the
array documentation to explain this a bit more clearly.
(As a side note, it's a bit unfortunate that get-array-from-slice is
only available via trait since that means it can't be used from const
functions yet.)
Currently the documentation of f64::min refers to "IEEE-754 2008" while the documentation of
f64::minimum refers to "IEEE 754-2019".
Note that one has the format IEEE,hyphen,number,space,year while the other is
IEEE,space,number,hyphen,year. The official IEEE site [1] uses the later format and it is also the
one most commonly used throughout the codebase.
Update all comments and - more importantly - documentation to consistently use the official format.
[1] https://standards.ieee.org/ieee/754/4211/
The `<*const T>::guaranteed_*` methods now return an option for the unknown case
cc https://github.com/rust-lang/rust/issues/53020#issuecomment-1236932443
I chose `0` for "not equal" and `1` for "equal" and left `2` for the unknown case so backends can just forward to raw pointer equality and it works ✨
r? `@fee1-dead` or `@lcnr`
cc `@rust-lang/wg-const-eval`
Fix the example code and doctest for Formatter::sign_plus
The provided example to the `sign_plus` method on `fmt` was broken, it displays the `-` sign twice for negative numbers.
This pull request should fix the issue by `.abs()` ing the number so that the negative sign appears only once. It is just one possible solution to the issue, not sure if it's the best. However, this one will behave as expected when combined with fill and alignment operators.
Compile spin_loop_hint as pause on x86 even without sse2 enabled
The x86 `pause` instruction was introduced with sse2, but because it is encoded as `rep nop`, it works just fine on cpu's without sse2 support. It just doesn't do anything.
Tweak future opaque ty pretty printing
1. The `Return` type of a generator doesn't need to be a lang item just for diagnostic printing of types
2. We shouldn't suppress the `Output = Ty` of a opaque future if the type is a int or float var.
Reimplement `carrying_add` and `borrowing_sub` for signed integers.
As per the discussion in #85532, this PR reimplements `carrying_add` and `borrowing_sub` for signed integers.
It also adds unit tests for both unsigned and signed integers, emphasing on the behaviours of the methods.
The x86 `pause` instruction was introduced with sse2, but because it is encoded as `rep nop`, it works just fine on cpu's without sse2 support. It just doesn't do anything.
Document eager evaluation of `bool::then_some` argument
I encountered this earlier today and thought maybe `bool::then_some` could use a little addition to the documentation.
It's pretty obvious with familiarity and from looking at the implementation, but the argument for `then_some` is eagerly evaluated, which means if you do the following (as I did), you can have a problem:
```rust
// Oops!
let _ = something
.has_another_thing()
.then_some(something.another_thing_or_panic());
```
A note, similar to other methods with eagerly-evaluated arguments and a lazy alternative (`Option::or`, for example), could help point this out to people who forget (like me)!
Make `const_eval_select` a real intrinsic
This fixes issues where `track_caller` functions do not have nice panic
messages anymore when there is a call to the function, and uses the
MIR system to replace the call instead of dispatching via lang items.
Fixes#100696.
safe transmute: use `Assume` struct to provide analysis options
This task was left as a TODO in #92268; resolving it brings [`BikeshedIntrinsicFrom`](https://doc.rust-lang.org/nightly/core/mem/trait.BikeshedIntrinsicFrom.html) more in line with the API defined in [MCP411](https://github.com/rust-lang/compiler-team/issues/411).
**Before:**
```rust
pub unsafe trait BikeshedIntrinsicFrom<
Src,
Context,
const ASSUME_ALIGNMENT: bool,
const ASSUME_LIFETIMES: bool,
const ASSUME_VALIDITY: bool,
const ASSUME_VISIBILITY: bool,
> where
Src: ?Sized,
{}
```
**After:**
```rust
pub unsafe trait BikeshedIntrinsicFrom<Src, Context, const ASSUME: Assume = { Assume::NOTHING }>
where
Src: ?Sized,
{}
```
`Assume::visibility` has also been renamed to `Assume::safety`, as library safety invariants are what's actually being assumed; visibility is just the mechanism by which it is currently checked (and that may change).
r? `@oli-obk`
---
Related:
- https://github.com/rust-lang/compiler-team/issues/411
- https://github.com/rust-lang/rust/issues/99571
Fix a bunch of typo
This PR will fix some typos detected by [typos].
I only picked the ones I was sure were spelling errors to fix, mostly in
the comments.
[typos]: https://github.com/crate-ci/typos
This PR will fix some typos detected by [typos].
I only picked the ones I was sure were spelling errors to fix, mostly in
the comments.
[typos]: https://github.com/crate-ci/typos
Before, the text simply asked people to use a symbol which is hard to
search for. Now the text links back to the chapter on error
propagation in The Book. That should help people find the relevant
keywords for further searches.