Update emscripten std tests
This disables a bunch of emscripten tests that test things emscripten doesn't support and re-enables a whole bunch of tests which now work just fine on emscripten.
Tested with `EMCC_CFLAGS="-s MAXIMUM_MEMORY=2GB" ./x.py test library/ --target wasm32-unknown-emscripten`.
Fix `FormattingOptions` instantiation with `Default`
The `fill` value by default should be set to `' '` (space), but the current implementation uses `#[derive(Default)]` which sets it to `\0`.
Note that `FormattingOptions` is being released as part of 1.85 (unstable) - so this might warrant a backport to that branch.
Tracking issue: https://github.com/rust-lang/rust/issues/118117
Follow up from https://github.com/rust-lang/rust/pull/118159
CC: ``@EliasHolzmann`` ``@programmerjake``
r? ``@m-ou-se``
Add memory layout documentation to generic NonZero<T>
The documentation I've added is based on the same Layout documentation that appears on the other `NonZero*` types. For example see [the Layout docs on `NonZeroI8`](https://doc.rust-lang.org/std/num/type.NonZeroI8.html#layout-1).
remove pointless allowed_through_unstable_modules on TryFromSliceError
This got added in https://github.com/rust-lang/rust/pull/132482 but the PR does not explain why. `@lukas-code` do you still remember? Also Cc `@Noratrieb` as reviewer of that PR.
If I understand the issue description correctly, all paths under which this type is exported are stable now: `core::array::TryFromSliceError` and `std::array::TryFromSliceError`. If that is the case, we shouldn't have the attribute; it's a terrible hack that should only be used when needed to maintain backward compatibility. Getting some historic information right is IMO *not* sufficient justification to risk accidentally exposing this type via more unstable paths today or in the future.
Implement `ByteStr` and `ByteString` types
Approved ACP: https://github.com/rust-lang/libs-team/issues/502
Tracking issue: https://github.com/rust-lang/rust/issues/134915
These types represent human-readable strings that are conventionally,
but not always, UTF-8. The `Debug` impl prints non-UTF-8 bytes using
escape sequences, and the `Display` impl uses the Unicode replacement
character.
This is a minimal implementation of these types and associated trait
impls. It does not add any helper methods to other types such as `[u8]`
or `Vec<u8>`.
I've omitted a few implementations of `AsRef`, `AsMut`, and `Borrow`,
when those would be the second implementation for a type (counting the
`T` impl), to avoid potential inference failures. We can attempt to add
more impls later in standalone commits, and run them through crater.
In addition to the `bstr` feature, I've added a `bstr_internals` feature
for APIs provided by `core` for use by `alloc` but not currently
intended for stabilization.
This API and its implementation are based *heavily* on the `bstr` crate
by Andrew Gallant (`@BurntSushi).`
r? `@BurntSushi`
Add an example of using `carrying_mul_add` to write wider multiplication
Just the basic quadratic version that you wouldn't actually use for really-big integers, but it's nice and short so is useful as for a demonstration of why you might find `carrying_mul_add` useful :)
cc #85532 ``````@clarfonthey``````
Enable `unreachable_pub` lint in core
This PR enables the [`unreachable_pub`](https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html#unreachable-pub) as warn in `core`, `rtstartup` and `panic_unwind`.
The motivation is similar to the compiler [MCP: Enable deny(unreachable_pub) on `rustc_*` crates](https://github.com/rust-lang/compiler-team/issues/773#issue-2467219005) :
> "Where is this thing used?" is a question I ask all the time when reading unfamiliar code. Because of this, I generally find it annoying when things are marked with a more permissive visibility than necessary. "This thing marked pub, which other crates is it used in? Oh, it's not used in any other crates."
Another motivation is to help to lint by utilizing it in-tree and seeing it's limitation in more complex scenarios.
The diff was mostly generated with `./x.py fix --stage 1 library/core/ -- --broken-code`, as well as manual edits for code in macros, generated code and other targets.
r? libs
Reexport likely/unlikely in std::hint
Since `likely`/`unlikely` should be working now, we could reexport them in `std::hint`. I'm not sure if this is already approved or if it requires approval
Tracking issue: #26179
Improve `select_nth_unstable` documentation clarity
* Instead uses `before` and `after` variable names in the example
where `greater` and `lesser` are flipped.
* Uses `<=` and `>=` instead of "less than or equal to" and "greater
than or equal to" to make the docs more concise.
* General attempt to remove unnecessary words and be more precise. For
example it seems slightly wrong to say "its final sorted position",
since this implies there is only one sorted position for this element.
[cfg_match] Adjust syntax
A year has passed since the creation of #115585 and the feature, as expected, is not moving forward. Let's change that.
This PR proposes changing the arm's syntax from `cfg(SOME_CONDITION) => { ... }` to `SOME_CODITION => {}`.
```rust
match_cfg! {
unix => {
fn foo() { /* unix specific functionality */ }
}
target_pointer_width = "32" => {
fn foo() { /* non-unix, 32-bit functionality */ }
}
_ => {
fn foo() { /* fallback implementation */ }
}
}
```
Why? Because after several manual migrations in https://github.com/rust-lang/rust/pull/116342 it became clear, at least for me, that `cfg` prefixes are unnecessary, verbose and redundant.
Again, everything is just a proposal to move things forward. If the shown syntax isn't ideal, feel free to close this PR or suggest other alternatives.
Rollup of 5 pull requests
Successful merges:
- #135497 (fix typo in typenames of pin documentation)
- #135522 (add incremental test for issue 135514)
- #135523 (const traits: remove some known-bug that do not seem to make sense)
- #135535 (Add GUI test for #135499)
- #135541 (Methods of const traits are const)
r? `@ghost`
`@rustbot` modify labels: rollup
fix typo in typenames of pin documentation
I noticed this whilst reading the documentation for pin.
Basically there was just one to many closing angle brackets on the type parameters in the documentation where instead of being `Pin<&mut T>` it was `Pin<&mut T>>`
deprecate `std::intrinsics::transmute` etc, use `std::mem::*` instead
The `rustc_allowed_through_unstable_modules` attribute lets users call `std::mem::transmute` as `std::intrinsics::transmute`. The former is a reexport of the latter, and for a long time we didn't properly check stability for reexports, so making this a hard error now would be a breaking change for little gain. But at the same time, `std::intrinsics::transmute` is not the intended path for this function, so I think it is a good idea to show a deprecation warning when that path is used. This PR implements that, for all the functions in `std::intrinsics` that carry the attribute.
I assume this will need ``@rust-lang/libs-api`` FCP.
Rollup of 7 pull requests
Successful merges:
- #132397 (Make missing_abi lint warn-by-default.)
- #133807 (ci: Enable opt-dist for dist-aarch64-linux builds)
- #134143 (Convert `struct FromBytesWithNulError` into enum)
- #134338 (Use a C-safe return type for `__rust_[ui]128_*` overflowing intrinsics)
- #134678 (Update `ReadDir::next` in `std::sys::pal::unix::fs` to use `&raw const (*p).field` instead of `p.byte_offset().cast()`)
- #135424 (Detect unstable lint docs that dont enable their feature)
- #135520 (Make sure we actually use the right trivial lifetime substs when eagerly monomorphizing drop for ADTs)
r? `@ghost`
`@rustbot` modify labels: rollup
Convert `struct FromBytesWithNulError` into enum
This PR renames the former `kind` enum from `FromBytesWithNulErrorKind` to `FromBytesWithNulError`, and removes the original struct.
See https://github.com/rust-lang/libs-team/issues/493
## Possible Changes - TBD
* [x] should the new `enum FromBytesWithNulError` derive `Copy`?
* [ ] should there be any new/changed attributes?
* [x] add some more tests
## Problem
One of `CStr` constructors, `CStr::from_bytes_with_nul(bytes: &[u8])` handles 3 cases:
1. `bytes` has one NULL as the last value - creates CStr
2. `bytes` has no NULL - error
3. `bytes` has a NULL in some other position - error
The 3rd case is error that may require lossy conversion, but the 2nd case can easily be handled by the user code. Unfortunately, this function returns an opaque `FromBytesWithNulError` error in both 2nd and 3rd case, so the user cannot detect just the 2nd case - having to re-implement the entire function and bring in the `memchr` dependency.
## Motivating examples or use cases
In [this code](f86d7a8768/varnish-sys/src/vcl/ws.rs (L158)), my FFI code needs to copy user's `&[u8]` into a C-allocated memory blob in a NUL-terminated `CStr` format. My code must first validate if `&[u8]` has a trailing NUL (case 1), no NUL (adds one on the fly - case 2), or NUL in the middle (3rd case - error). I had to re-implement `from_bytes_with_nul` and add `memchr`dependency just to handle the 2nd case.
r? `@Amanieu`
Add #[inline] to copy_from_slice
I'm doing cooked things to CGU partitioning for compiler-builtins (https://github.com/rust-lang/rust/pull/135395) and this was the lone symbol in my compiler-builtins rlib that wasn't an intrinsic. Adding `#[inline]` makes it go away.
Perf report indicates a marginal but chaotic effect on compile time, marginal improvement in codegen. As expected.
update and clarify StructuralPartialEq docs
This apparently hasn't been updated when we finalized the current const pattern matching behavior.
Fixes https://github.com/rust-lang/rust/issues/92454 by providing rationale and context in the docs linked from that error message.
One of `CStr` constructors, `CStr::from_bytes_with_nul(bytes: &[u8])` handles 3 cases:
1. `bytes` has one NULL as the last value - creates CStr
2. `bytes` has no NULL - error
3. `bytes` has a NULL in some other position - error
The 3rd case is error that may require lossy conversion, but the 2nd case can easily be handled by the user code. Unfortunately, this function returns an opaque `FromBytesWithNulError` error in both 2nd and 3rd case, so the user cannot detect just the 2nd case - having to re-implement the entire function and bring in the `memchr` dependency.
In [this code](f86d7a8768/varnish-sys/src/vcl/ws.rs (L158)), my FFI code needs to copy user's `&[u8]` into a C-allocated memory blob in a NUL-terminated `CStr` format. My code must first validate if `&[u8]` has a trailing NUL (case 1), no NUL (adds one on the fly - case 2), or NUL in the middle (3rd case - error). I had to re-implement `from_bytes_with_nul` and add `memchr`dependency just to handle the 2nd case.
This PR renames the former `kind` enum from `FromBytesWithNulErrorKind` to `FromBytesWithNulError`, and removes the original struct.
Use `NonNull::without_provenance` within the standard library
This API removes the need for several `unsafe` blocks, and leads to clearer code. It uses feature `nonnull_provenance` (#135243).
Close#135343
Update a bunch of library types for MCP807
This greatly reduces the number of places that actually use the `rustc_layout_scalar_valid_range_*` attributes down to just 3:
```
library/core\src\ptr\non_null.rs
68:#[rustc_layout_scalar_valid_range_start(1)]
library/core\src\num\niche_types.rs
19: #[rustc_layout_scalar_valid_range_start($low)]
20: #[rustc_layout_scalar_valid_range_end($high)]
```
Everything else -- PAL Nanoseconds, alloc's `Cap`, niched FDs, etc -- all just wrap those `niche_types` types.
r? ghost
Approved ACP: https://github.com/rust-lang/libs-team/issues/502
Tracking issue: https://github.com/rust-lang/rust/issues/134915
These types represent human-readable strings that are conventionally,
but not always, UTF-8. The `Debug` impl prints non-UTF-8 bytes using
escape sequences, and the `Display` impl uses the Unicode replacement
character.
This is a minimal implementation of these types and associated trait
impls. It does not add any helper methods to other types such as `[u8]`
or `Vec<u8>`.
I've omitted a few implementations of `AsRef`, `AsMut`, `Borrow`,
`From`, and `PartialOrd`, when those would be the second implementation
for a type (counting the `T` impl) or otherwise may cause inference
failures. These impls are important, but we can attempt to add them
later in standalone commits, and run them through crater.
In addition to the `bstr` feature, I've added a `bstr_internals` feature
for APIs provided by `core` for use by `alloc` but not currently
intended for stabilization.
This API and its implementation are based *heavily* on the `bstr` crate
by Andrew Gallant (@BurntSushi).
This greatly reduces the number of places that actually use the `rustc_layout_scalar_valid_range_*` attributes down to just 3:
```
library/core\src\ptr\non_null.rs
68:#[rustc_layout_scalar_valid_range_start(1)]
library/core\src\num\niche_types.rs
19: #[rustc_layout_scalar_valid_range_start($low)]
20: #[rustc_layout_scalar_valid_range_end($high)]
```
Everything else -- PAL Nanoseconds, alloc's `Cap`, niched FDs, etc -- all just wrap those `niche_types` types.
Fix `ptr::from_ref` documentation example comment
The comment says that the expression involves no function call, but that was only true for the example above, the example here _does_ contain a function call.
``@rustbot`` label A-docs
Improve prose around `as_slice` example of IterMut
I've removed the cryptic message about not being able to call `&mut self` methods while retaining a shared borrow of the iterator, such as `as_slice` produces. This is just normal borrowing rules and does not seem especially relevant here. I can whip up a replacement if someone thinks it has value.
[generic_assert] Constify methods used by the formatting system
cc #44838
Starts the "constification" of all the elements required to allow the execution of the formatting system in constant environments.
```rust
const _: () = { panic!("{:?}", 1i32); };
```
Further stuff is blocked by #133999.
The implementation is unsound when a partially consumed iterator has
some elements buffered in the front/back parts and cloning the Iterator
removes the capacity from the backing vec::IntoIter.
char to_digit: avoid unnecessary casts to u64
Hello,
in the `char::to_digit` method there are a few `as u64` casts that are not strictly necessary.
I assume that the reason behind these casts is to avoid possible overflows in the `+ 10` add.
This PR removes the aforementioned casts, avoiding the overflow issue by slightly modifying the ASCII letter to int mapping.
Thanks,
Happy new year.
* Instead uses `before` and `after` variable names in the example
where `greater` and `lesser` are flipped.
* Uses `<=` and `>=` instead of "less than or equal to" and "greater
than or equal to" to make the docs more concise.
* General attempt to remove unnecessary words and be more precise. For
example it seems slightly wrong to say "its final sorted position",
since this implies there is only one sorted position for this element.
Tidy up bigint multiplication methods
This tidies up the library version of the bigint multiplication methods after the addition of the intrinsics in #133663. It follows [this summary](https://github.com/rust-lang/rust/issues/85532#issuecomment-2403442775) of what's desired for these methods.
Note that, if `2H = N`, then `uH::MAX * uH::MAX + uH::MAX + uH::MAX` is `uN::MAX`, and that we can effectively add two "carry" values without overflowing.
For ease of terminology, the "low-order" or "least significant" or "wrapping" half of multiplication will be called the low part, and the "high-order" or "most significant" or "overflowing" half of multiplication will be called the high part. In all cases, the return convention is `(low, high)` and left unchanged by this PR, to be litigated later.
## API Changes
The original API:
```rust
impl uN {
// computes self * rhs
pub const fn widening_mul(self, rhs: uN) -> (uN, uN);
// computes self * rhs + carry
pub const fn carrying_mul(self, rhs: uN, carry: uN) -> (uN, uN);
}
```
The added API:
```rust
impl uN {
// computes self * rhs + carry1 + carry2
pub const fn carrying2_mul(self, rhs: uN, carry: uN, add: uN) -> (uN, uN);
}
impl iN {
// note that the low part is unsigned
pub const fn widening_mul(self, rhs: iN) -> (uN, iN);
pub const fn carrying_mul(self, rhs: iN, carry: iN) -> (uN, iN);
pub const fn carrying_mul_add(self, rhs: iN, carry: iN, add: iN) -> (uN, iN);
}
```
Additionally, a naive implementation has been added for `u128` and `i128` since there are no double-wide types for those. Eventually, an intrinsic will be added to make these more efficient, but rather than doing this all at once, the library changes are added first.
## Justifications for API
The unsigned parts are done to ensure consistency with overflowing addition: for a two's complement integer, you want to have unsigned overflow semantics for all parts of the integer except the highest one. This is because overflow for unsigned integers happens on the highest bit (from `MAX` to zero), whereas overflow for signed integers happens on the second highest bit (from `MAX` to `MIN`). Since the sign information only matters in the highest part, we use unsigned overflow for everything but that part.
There is still discussion on the merits of signed bigint *addition* methods, since getting the behaviour right is very subtle, but at least for signed bigint *multiplication*, the sign of the operands does make a difference. So, it feels appropriate that at least until we've nailed down the final API, there should be an option to do signed versions of these methods.
Additionally, while it's unclear whether we need all three versions of bigint multiplication (widening, carrying-1, and carrying-2), since it's possible to have up to two carries without overflow, there should at least be a method to allow that. We could potentially only offer the carry-2 method and expect that adding zero carries afterword will optimise correctly, but again, this can be litigated before stabilisation.
## Note on documentation
While a lot of care was put into the documentation for the `widening_mul` and `carrying_mul` methods on unsigned integers, I have not taken this same care for `carrying_mul_add` or the signed versions. While I have updated the doc tests to be more appropriate, there will likely be many documentation changes done before stabilisation.
## Note on tests
Alongside this change, I've added several tests to ensure that these methods work as expected. These are alongside the codegen tests for the intrinsics.
Fix doc for read&write unaligned in zst operation
### PR Description
This PR addresses an inconsistency in the Rust documentation regarding `read_unaligned ` and `write_unaligned` on zero-sized types (ZSTs). The current documentation for [pointer validity](https://doc.rust-lang.org/nightly/std/ptr/index.html#safety) states that for zero-sized types (ZSTs), null pointers are valid:
> For zero-sized types (ZSTs), every pointer is valid, including the null pointer.
However, there is an inconsistency in the documentation for the unaligned read operation in the function [ptr::read_unaligned](https://doc.rust-lang.org/nightly/std/ptr/fn.read_unaligned.html)(as well as `write_unaligned`), which states:
> Note that even if T has size 0, the pointer must be non-null.
This change is also supported by [PR #134912](https://github.com/rust-lang/rust/pull/134912)
> the _unaligned method docs should be fixed.