Default `RawOsError` to `i16` for 16-bit targets
ACP: https://github.com/rust-lang/libs-team/issues/755
Tracking issue: rust-lang/rust#154046 & rust-lang/rust#107792Fixesrust-lang/rust#160541
# Description
As noted by @tgross35, it's likely desirable for `RawOsError` to default to `i16` for 16-bit platforms. Practically, this only affects AVR and MSP430. Since `c_int` is defined as:
```rust
crate::cfg_select! {
any(target_arch = "avr", target_arch = "msp430") => {
pub(super) type c_int = i16;
pub(super) type c_uint = u16;
}
_ => {
pub(super) type c_int = i32;
pub(super) type c_uint = u32;
}
}
```
This also ensures for all platforms (excluding UEFI), `RawOsError` is equivalent to `c_int`. Since neither sets of targets had an implementation of `std`, this hasn't yet been litigated. While `RawOsError` is unstable, it seems reasonable to choose a default more likely to align with the underlying OS (if any).
---
## Notes
- No AI tooling of any kind was used during the creation of this PR.
Hint that memchr returns an in-bounds index
`memchr_aligned` always returns an index within the input slice, but that fact was not visible to callers after inlining. Record the invariant with `assert_unchecked` so LLVM can simplify callers such as `str::find(char)`
In x86_64 codegen, `find(char)` shrank from 463 to 377 bytes.
Various steps in moving away from the big reflection enum to reflection functions
tracking issue: rust-lang/rust#146922
Some more of these and we can turn the big TyKind enum into one without any data, but I think these are enough steps for one PR, don't wanna turn it into a mega PR
Optimize slice::contains for bytewise types
generalize the SliceContains implementation from u8 to all types implementing UnsignedBytewiseOrd since these types have a one byte representation compatible with the
memchr implementation
Fix an edge case with `StepBy::nth` on non-fused iterators
Fixesrust-lang/rust#159965.
From the `nth` documentation as pointed out by theemathas:
> `nth()` will return `None` if `n` is greater than or equal to the length of the iterator.
Currently, there is an edge case for non-fused iterator where it's able to return `Some` through `StepBy::nth` iterator even though the first item from the non-fused iterator returns `None` (it is logically an empty iterator).
The issue came from how in the first take block it advances the underlying iterator forward using `.next()` and does not check if what it returns is a `None` value or not. This wouldn't be a problem for fused iterators because all the values that it would return after reaching the `None` point will also be `None`. However since non-fused iterators do not have to abide by continuously yielding `None` after reaching a `None`, it allows for a case, where after falling down from `first_take` block it can return `Some(_)` from a `self.iter.nth()` call in there.
In the `first_take` block we should definitely check if the first item we got from `self.iter.next()` is `None` item, and return `None` if it is so.
stabilize size_of_val_raw, align_of_val_raw, Layout::for_value_raw
Stabilizes versions of `size_of_val_raw` and friends that can be invoked on raw pointers, which means they can be used even if one does not have a pointer to a "valid value". This was held up for a while because figuring out the exact safety requirements is tricky, but I think the ones we now have had for a while (plus the minor clarifications in this PR) are "good enough": we basically do case distinction on the unsized tail of the type, and spell out the appropriate requirement for each case. This avoids making blanket statements about future kinds of DST that we may introduce eventually.
These are the requirements I should we should stabilize:
```
/// - If `T` is `Sized`, this function is always safe to call.
/// - If the unsized tail of `T` is:
/// - a [slice] `[U]`, `str`, or a [trait object] `dyn Trait`, then the size of the *entire value*
/// (dynamic tail length + statically sized prefix) must fit in `isize`.
/// For the special case where the dynamic tail length is 0, this function
/// is safe to call.
// NOTE: the reason this is safe is that if an overflow were to occur already with size 0,
// then we would stop compilation as even the "statically known" part of the type would
// already be too big (or the call may be in dead code and optimized away, but then it
// doesn't matter).
/// - No other kind of unsized tail currently exists that satisfies the trait bounds for this
/// function. If more kinds of unsized tails get introduced in the future, the documentation
/// of this function will have to be extended before it can be used for such types.
```
Going over the open questions from the [tracking issue](https://github.com/rust-lang/rust/issues/69835):
- What should the exact safety requirements of these functions be? -> the currently documented requirement look good to me.
- How should this interact with extern types? -> what we document looks good here; we can still adjust this until extern types are stabilized.
- Are the functions sound to call on invalid data pointers? -> for the unsized tails that currently exist: yes; that's kind of the only reason to use them.
Cc @rust-lang/opsem @rust-lang/lang
(FCP should probably include both teams, unless lang is okay with fully delegating this to t-opsem)
I'll nominate the tracking issue for libs-api so we can get their approval as well for how the operation is exposed.
Fixes https://github.com/rust-lang/rust/issues/69835
Don't escape U+FF9E and U+FF9F in `escape_debug_ext`
The two characters `゙` U+FF9E HALFWIDTH KATAKANA VOICED SOUND MARK and `゚` U+FF9F HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK are the odd ones out when it comes to grapheme extenders, in that *graphically* they are not combining at all. See https://github.com/microsoft/terminal/issues/18087 for more background on these characters.
I think this needs FCP? It affects `char::escape_debug`, and various `Debug` impls for characters and strings.
@rustbot labels T-libs-api needs-fcp A-Unicode
Rename splat to avoid stable name collisions
Tracking issue: rust-lang/rust#153629
This PR renames `#[splat]` to `#[rustc_splat]`, in a mostly automated way (using `fastmod`).
The rename commands I used were:
```sh
fastmod --fixed-strings '#[splat]' '#[rustc_splat]'
fastmod --fixed-strings '`splat` attribute' '`rustc_splat` attribute'
# I'm pretty sure the symbol demangling commands are no-ops on beta
# Legacy symbol demangling
fastmod --fixed-strings '$splat$' '$rustc_splat$'
# Revert some changes that aren't in rustc_demangle yet
fastmod 'v0(.*)#\[rustc_splat\]' 'v0${1}#[splat]' tests/ui/splat/splat-mangling.rs
```
Part of rust-lang/rust#159428
#### Backport Advice
Cherry-pick the first commit to the beta branch, then run the fastmod commands above.
I've tested this locally (with a slightly different name), and it works, see my [`splat-rename-beta` branch](https://github.com/teor2345/rust/tree/splat-rename-beta).
#### Remaining Work
rustc_demangle needs an update to the attribute name, a release, and then a version bump in rust-lang/rust. I'll do that separately. It doesn't need to be backported, because the last version bump was after beta branched.
There's also some external code that needs updates, the full list is in the ticket: https://github.com/rust-lang/rust/issues/159428#issuecomment-5040163201
@rustbot label +beta-nominated +A-attributes +A-macros +A-resolve +C-bug +F-splat +P-high +T-compiler
Lint against iterator functions that panic when `N` is zero
This PR extends the deny-by-default `unconditional_panic` lint, by linting on iterator functions that panics when `N` (chunks/windows size) is zero[^attr].
Those methods are [documented](https://doc.rust-lang.org/std/primitive.slice.html#panics-11) to panic if `N` is zero.
```
error: this operation will panic at runtime
--> $DIR/const-n-is-zero.rs:11:13
|
LL | let _ = s.array_windows::<0>();
| ^^^^^^^^^^^^^^^^^^^^^^ const parameter `N` is zero
|
= note: `#[deny(unconditional_panic)]` on by default
```
cc @rust-lang/libs-api
[^attr]: this is done by introducing a new internal attribute on the const parameter: `#[rustc_panics_when_zero]`
feat: Update method signature of int_from_ascii
* Tracking issue: rust-lang/rust#134821
Following [discussion on Zulip](https://rust-lang.zulipchat.com/#narrow/channel/327149-t-libs-api.2Fapi-changes/topic/How.20to.20proceed.20with.20int_from_ascii/with/611508226) it appears the preference is to change the API for this feature as follows:
```rust
// core::num
impl X {
pub const fn from_ascii_bytes<T>(src: T) -> Result<X, ParseIntError>
where
T: [const] AsRef<[u8]> + [const] core::marker::Destruct;
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32) -> Result<X, ParseIntError>
where
T: [const] AsRef<[u8]> + [const] core::marker::Destruct;
}
```
and similarly for `NonZero<X>`.
Reasons behind the change:
* Future-proof the naming convention for future string-like types
* Support the upcoming `ByteStr`/`ByteString` types: rust-lang/rust#134915
This pull request applies this change. The const-ness of these functions is now feature gated behind rust-lang/rust#143773
iter: extend step_by specialization to cover StepBy<RangeIter<{integer}>>
`StepBy<Range<{integer}>>` already has a fast path that converts the range
into a yield-count before iteration, avoiding per-step overflow checks and
enabling better loop structure for the optimizer. `StepBy<RangeIter<{integer}>>`
did not benefit from the same optimization even though `RangeIter<T>` is a thin
newtype wrapper around `legacy::Range<T>`.
## Changes
- `library/core/src/range/iter.rs`: make `RangeIter<A>.0` `pub(crate)` so the
step_by adapter can access the inner legacy range's start/end fields.
- `library/core/src/iter/adapters/step_by.rs`: add `spec_int_ranges_new!` and
`spec_int_ranges_new_r!` macros that mirror the existing `spec_int_ranges!` /
`spec_int_ranges_r!` implementations. Forward specialization covers `u8 u16
u32 u64 usize` (pointer-width-gated for u32/u64); backward specialization is
limited to `u8 u16 usize` since `RangeIter<u32>` / `RangeIter<u64>` do not
implement `ExactSizeIterator`.
- `library/coretests/tests/iter/adapters/step_by.rs`: add
`test_step_by_new_range_iter` covering forward, backward, and interleaved
iteration via the new-range iterator.
## Motivation
Fixesrust-lang/rust#157754. The inner loop for `core::range::Range::from(0..n).into_iter().step_by(2)` currently generates noticeably worse assembly than the equivalent `(0..n).step_by(2)` because specialization did not cover `RangeIter`.
r? libs
and optimize the RangeInclusive iterator implementation with them
This changes the `exhausted` field to represent an overflow flag
for the bounds, essentially acting as an extra bit for `Idx`.
This was found to enable optimizations previously only applicable
to the exclusive-ended Range type.
- change end_bound to return Excluded(start) when exhausted
- add contains to tests
- make into_bounds panic when exhausted
matches From<legacy::RangeInclusive<T>> for RangeInclusive<T>
- add tests for new Step impls
Update `transmute_copy` to ub_checks and `?Sized`
The `assert!` in `transmute_copy` is from rust-lang/rust#98839. However, it was controversial at the time because it's possible to write `transmute_copy`s that were UB by the description but didn't pass the documented conditions. It's also sub-optimal to have possible `panic`s in unsafe code where the panic can actually make things worse by dropping things in the middle of what the programmer expected to be panic-free. Now that we have the `UbChecks` possibility, though, we can do this better: this PR makes it a *non-unwinding* panic when not meeting the documented condition when UB checks are enabled, but which very clearly emphasizes that said check isn't a documented behaviour of the function.
Also, I was staring at the signature and couldn't figure out why it needs `Src: Sized`. Since it *always* takes a reference, there seems to be no downside to accepting `Src: ?Sized`. That would also give it more of a reason to exist even if <https://doc.rust-lang.org/nightly/std/mem/fn.transmute_prefix.html> exists (as `transmute_prefix(x)` existing will no longer need the `transmute_copy(&ManuallyDrop::new(x))` polyfill, cc https://github.com/rust-lang/rfcs/pull/3844). That definitely needs an FCP, though.
(The change to `assert_unsafe_precondition` here doesn't technically need libs-api assent, but I'd still like to hear your thoughts since it's different from the "promise the assert" that IIRC you were also asked to consider elsewhere.)
A partial replacement for rust-lang/rust#154665
Implement `DoubleEndedIterator::next_chunk_back`
This PR builds off on @vinDelphini's [PR](https://github.com/rust-lang/rust/pull/151668) on introducing `DoubleEndedIterator::next_chunk_back` (which will be used in a follow up PR to optimize `ArrayChunks::try_rfold` once merged). This was in the works since late Jan and I thought to pick it up and get this over the finish line as vinDelphini has been away from the PR for a couple of months. I've made sure to pull from vinDelphini's branch to keep him authored on the commits he made.
Other things introduced from this PR is specialization like done for `Iterator::next_chunk`, constifying some stuff, making a custom `DoubleEndedIterator::next_chunk_back` for `IntoIter` (since it also has a custom impl of `Iterator::next_chunk`), and a bunch of tests mirroring that of `Iterator::next_chunk`.
There's no tracking issue for this yet, but the ACP for this introduction is [here](https://github.com/rust-lang/libs-team/issues/734). I'll create the tracking issue for this soon.
----
Actually, can we have `DoubleEndedIterator::next_chunk_back` underneath [`Iterator::next_chunk` tracking issue](https://github.com/rust-lang/rust/issues/98326)?
Optimize network address parser
Motivated by working with datasets of IP addresses.
First commit adds more examples for each case in the benchmark suite.
Second commit splits `read_number()` into seperate methods for the the `max_digits` `Some(_)` and `None` cases, which by itself significantly helps code generation.
Hoist reading the first digit which is always required.
The path for unlimited digits then no longer has to count digits at all.
Drive-by "fixes" the 10 digit debug assertion (which would be insufficient in base 16). Not actually used anywhere near the limit.
`./x bench library/coretests --test-args addr_parser` before -> after on AMD Ryzen 9 9950X:
net::addr_parser::bench_parse_ipaddr_v4 81.73ns/iter +/- 0.60 -> 62.36ns/iter +/- 0.12
net::addr_parser::bench_parse_ipaddr_v6_compress 303.70ns/iter +/- 1.29 -> 212.80ns/iter +/- 1.25
net::addr_parser::bench_parse_ipaddr_v6_full 453.06ns/iter +/- 7.89 -> 294.88ns/iter +/- 0.91
net::addr_parser::bench_parse_ipaddr_v6_v4 301.41ns/iter +/- 1.52 -> 224.82ns/iter +/- 0.99
net::addr_parser::bench_parse_ipv4 87.24ns/iter +/- 0.32 -> 52.94ns/iter +/- 0.33
net::addr_parser::bench_parse_ipv6_compress 277.92ns/iter +/- 3.29 -> 195.98ns/iter +/- 1.10
net::addr_parser::bench_parse_ipv6_full 402.48ns/iter +/- 22.20 -> 276.37ns/iter +/- 4.05
net::addr_parser::bench_parse_ipv6_v4 276.78ns/iter +/- 1.18 -> 216.04ns/iter +/- 1.20
net::addr_parser::bench_parse_socket_v4 105.18ns/iter +/- 0.79 -> 69.20ns/iter +/- 0.46
net::addr_parser::bench_parse_socket_v6 378.69ns/iter +/- 5.25 -> 274.82ns/iter +/- 0.95
net::addr_parser::bench_parse_socket_v6_scope_id 336.61ns/iter +/- 2.36 -> 258.56ns/iter +/- 0.89
net::addr_parser::bench_parse_socketaddr_v4 118.20ns/iter +/- 0.66 -> 78.86ns/iter +/- 0.22
net::addr_parser::bench_parse_socketaddr_v6 429.17ns/iter +/- 5.70 -> 315.69ns/iter +/- 1.48
stabilize feature `float_algebraic`
Closesrust-lang/rust#136469
Thanks to @RalfJung for getting the stabilization process started and asking me to draft the stabilization PR for the `float_algebraic` feature. This will be my first contribution to rust! I've done my best to follow the various guides for stabilization PRs, but this is my first one, so do give it a careful look. The only place left that includes "float_algebraic" is line 8202 of "src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs", but I'm assuming that's fine.
Make `BorrowedBuf` and `BorrowedCursor` generic over the data
Replace uses of `u8` with a generic type. This will allow reusing
`BorrowedBuf` elsewhere in the standard library, for purposes other than
byte buffers.
This currently requires `T: Copy`, to prevent `T: Drop`, which would require additional careful handling. We can consider relaxing that restriction in the future if we make `T: Drop` work (without pessimizing `Copy` types like `u8`).
`ensure_init` currently continues to require `u8`. We could potentially generalize it to `T: Default`, but we'd need to ensure it produced the same or better assembly for `u8`.
-----
As discussed in libs-api; cc @Amanieu.