io: Use `NonNull` for all `Custom` API related to `Box`, update documentation for `Custom`
Use `NonNull` a few more places to avoid the need to convert to and from `*mut T`. Also document the invariants for `Custom`.
Enforce more library clippy lints in CI
Best reviewed commit by commit.
This is testing the waters for enforcing more clippy lints. I've chosen these ones because we mostly adhere to them already (at least in core/alloc/std) so we can reduce the noise in `./x clippy` by fixing or allowing the relatively few violations.
Arc: Remove unnecessary fmt::Display use for overflow assertion
- [x] I did not use an LLM to create a change in this PR.
- [ ] I used an LLM to create a change in this PR, and I have explained below how it was used.
This PR removes unnecessary `fmt::Display` generated assembly because of use of formatting in the overflow check assertion(`assert!(n <= MAX_REFCOUNT, "{}", INTERNAL_OVERFLOW_ERROR);`).
This reduces generated x64 assembly for counter increment(simplified) from:
```asm
increase_counter:
test rdi, rdi
js .LBB1_2
inc rdi
mov rax, rdi
ret
.LBB1_2:
sub rsp, 24
lea rax, [rip + .Lanon.642d46026bcfa00bfed8baf8cdbf502d.2]
mov qword ptr [rsp + 8], rax
lea rax, [rip + <&str as core[4e7ceada952a6ea0]::fmt::Display>::fmt]
mov qword ptr [rsp + 16], rax
lea rdi, [rip + .Lanon.642d46026bcfa00bfed8baf8cdbf502d.0]
lea rdx, [rip + .Lanon.642d46026bcfa00bfed8baf8cdbf502d.4]
lea rsi, [rsp + 8]
call qword ptr [rip + core[4e7ceada952a6ea0]::panicking::panic_fmt@GOTPCREL]
.Lanon.642d46026bcfa00bfed8baf8cdbf502d.0:
.asciz "\300"
.Lanon.642d46026bcfa00bfed8baf8cdbf502d.1:
.ascii "Arc counter overflow"
```
To:
```asm
increase_counter:
test rdi, rdi
js .LBB0_2
inc rdi
mov rax, rdi
ret
.LBB0_2:
push rax
lea rdi, [rip + .Lanon.642d46026bcfa00bfed8baf8cdbf502d.0]
lea rdx, [rip + .Lanon.642d46026bcfa00bfed8baf8cdbf502d.2]
mov esi, 41
call qword ptr [rip + core[4e7ceada952a6ea0]::panicking::panic_fmt@GOTPCREL]
.Lanon.642d46026bcfa00bfed8baf8cdbf502d.0:
.ascii "Arc counter overflow"
```
Godbolt link:
https://godbolt.org/z/3qjxooYWM
I expect bors to report a binary size reduction for all programs using Arc. There might also be performance improvements as a byproduct of CPU cache hit increase.
Fix perf regression in `Read::read_to_end` on short reads due to not checking if the cursor has initialized bytes
This PR fixesrust-lang/rust#158008.
In particular, in rust-lang/rust#150129, it refactored some code within `library/std/io/mod.rs` to utilize `BorrowedBuf::is_init` instead of manually checking `read_buf.init_len() == buf_len` to see if the read buffer had initialized bytes. However, the `BorrowedBuf` is never marked or set as init within this function, and I think this portion of the code:
```rust
// SAFETY: These bytes were initialized but not filled in the previous loop
unsafe {
read_buf.set_init(initialized);
}
```
was removed by mistake. This PR reverts the changes made by rust-lang/rust#150129, so that we can mark the `BorrowedBuf`/`read_buf` as initialized using `BorrowedBuf::set_init` if in a previous iteration the cursor has initialized bytes. This would allow `max_read_size` to not be marked as `usize::max` if the read buffer contains initialized bytes.
Closes: rust-lang/rust#142872
Add an inherent `to_string()` method to `ByteStr` and `ByteString` that returns
`Result<String, Utf8Error>`, overriding the `to_string()` method made available
by the blanket implementation of `ToString` for all types that implement
`Display`.
Gate the new `to_string()` methods, and the existing `Display` implementations,
behind a new feature flag, `bstr_to_string`.
yk what we can do btree later
raaaaagh
pain and suffering
*unleaks your box* whats thiSegmentation fault (core dumped)
straight up testing it. and by it,
well, let's just say. "my allocator"
linked and listed
the unnecesary bits? gone. reduced to atoms
Introduce a `PinSafePointer` trait that generalizes `PinCoerceUnsized`
This PR renames `PinCoerceUnsized` to `PinSafePointer` and adds several new safety requirements about the implementations of various safe traits.
Closes: rust-lang/rust#152667Closes: rust-lang/rust#147794
~~With this merged, the only remaining soundness issues with `Pin` are:~~
* rust-lang/rust#134407
* The fact that `CoercePointee` may be implemented on `Pin<LocalType>` in downstream crates. (unstable only)
For your convenience here are the docs for the new trait:
# `PinSafePointer`
Trait that indicates that this is a pointer that does not misbehave when combined with `Pin`.
Note that for backwards compatibility reasons, it is possible to create a `Pin<P>` for pointer types `P` that do not implement this trait. However, this can only be done safely if `<P as Deref>::Target` implements `Unpin`, which means that pinning has no effect.
# Safety
Types that implement this trait must not provide "malicious" implementations of any safe traits used by `Pin`.
## The pointer must always reference the same object
Calls to [`deref`]/[`deref_mut`] on the same `Pin<P>` instance must always refer to the same object. That is, the address returned by these methods must not change. This applies even if the pointer type is moved.
Furthermore, if the pointer type can participate in unsizing coercions or dynamic dispatch, then these coercions must also not change the underlying concrete type. Here, the concrete type of a trait object is the type that the vtable corresponds to. The concrete type of a slice is an array of the same element type and the length specified in the metadata. The concrete type of a sized type is the type itself.
As an example, after unsizing coercing a pinned pointer, `deref_mut` must not return a `#[repr(transparent)]` wrapper around the value it referenced before being unsized, even if the address is unchanged.
## The pointer must not move its pointee
The [`deref_mut`] method and the pointer type's destructor are called with a `&mut self` receiver, but they must behave as-if it was a `self: Pin<&mut Self>` receiver. That is, they must not move out of the underlying value.
As an example, `deref_mut` must not invoke `swap` on the inner value.
## Shared access to the pointer
If this pointer type uses `&P` references as evidence that this value is not pinned, then it must not treat the `&self` argument passed to [`Clone`] or the formatting traits (`fmt::Debug`, `fmt::Display`, `fmt::Pointer`) as such evidence.
As an example, given a `Pin<Arc<T>>` there is no way to obtain an `&Arc<T>` (note that `Deref` just gives a `&T`). Because of this, the [`Arc`] type can assume that an `&Arc<T>` value can only exist if the `T` is not pinned, which justifies the soundness of the [`Arc::get_mut`] method.
## Cloning pinned pointers
When a `Pin<P>` is cloned, the `P` pointer value returned by `clone` is passed to [`Pin::new_unchecked`]. The implementation of [`Clone`] must return a value such that this is sound.
For example, when a `Pin<&T>` is cloned, the resulting `&T` points at the same value. The value is known to be pinned since a `Pin<&T>` to it exists, so it is safe to wrap the `&T` returned by `clone` in `Pin`.
[`deref`]: https://doc.rust-lang.org/stable/core/ops/trait.Deref.html#tymethod.deref
[`deref_mut`]: https://doc.rust-lang.org/stable/core/ops/trait.DerefMut.html#tymethod.deref_mut
[`clone`]: https://doc.rust-lang.org/stable/core/clone/trait.Clone.html#tymethod.clone
[`Clone`]: https://doc.rust-lang.org/stable/core/clone/trait.Clone.html
[`Arc`]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
[`Arc::get_mut`]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.get_mut
[`Pin::new_unchecked`]: https://doc.rust-lang.org/stable/std/pin/struct.Pin.html#method.new_unchecked
r? lcnr
Reorder the methods in `#[rustc_must_implement_one_of]`
So that their order will be the preferred order for implementations (assuming implementing `read_buf()` is better), like @joshtriplett said in https://github.com/rust-lang/rust/pull/106643#issuecomment-5187934543.
r? libs
Single-pass ASCII lower/upper case conversion
Current algorithm is cloning whole string/vector once, then rereads and rewrites it in-place once again which is sub-optimal and waste of CPU cycles and cache.
This one creates it in a single-pass while copying the data from the original vector.
In my benchmarks this one is about 1.2x-2x to 10x(KBs long strings) faster.
Add doc aliases for transpositions `read_exact_buf` and `read_exact_buf_at`
When fingers really want to type `read_exact`, that naturally leads to
the typo `read_exact_buf` instead of `read_buf_exact`, and
`read_exact_buf_at` instead of `read_buf_exact_at`.
Add doc aliases.
These will help people find them in rustdoc, and once
https://github.com/rust-lang/rust/pull/160369 goes in, it'll also help
people find them as rustfix suggestions.
Allow only implementing `Read::read_buf`
This PR allows users to only implement `Read::read_buf`, without the need for implementing `Read::read`. `rustc_must_implement_one_of` annotation ensures that **at least** one of the methods is implemented, so that the default impls don't create infinite recursion.
Note that `Read::read_buf` is unstable, so this doesn't change anything on stable, there you still need to implement `Read::read`, since you can't implement `Read::read_buf`. Thus, we don't expose `rustc_must_implement_one_of` to stable.
r? @thomcc
When fingers really want to type `read_exact`, that naturally leads to
the typo `read_exact_buf` instead of `read_buf_exact`, and
`read_exact_buf_at` instead of `read_buf_exact_at`.
Add doc aliases.
These will help people find them in rustdoc, and once
https://github.com/rust-lang/rust/pull/160369 goes in, it'll also help
people find them as rustfix suggestions.
Move `std::io::copy` to `alloc::io`
ACP: https://github.com/rust-lang/libs-team/issues/755
Tracking issue: https://github.com/rust-lang/rust/issues/154046
Split From: https://github.com/rust-lang/rust/pull/156527
~~Blocked On: https://github.com/rust-lang/rust/pull/158547~~
## Description
Moves `std::io::copy` into `alloc::io`. Blocked on rust-lang/rust#158547.
This relies on specialization to allow `std` to provide optimised copy implementations for its types where appropriate. The exact technique involves defining a new trait, `alloc::io::SpecCopy`:
```rust
#[doc(hidden)]
#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
#[rustc_specialization_trait]
pub trait SpecCopy: Read {
/// Attempt to copy from this reader to the provided writer using a specialized
/// process.
fn copy<R: Read + ?Sized, W: Write + ?Sized>(
_reader: &mut R,
_writer: &mut W,
) -> Result<CopyState>;
}
```
Since optimised copying requires both the reader and writer to support the operation between each other, we can choose one of them to be the implementer of the copy algorithm, and delegate specialization to it. In this case, I've chosen the reader to be the provider of the specialized copy implementation arbitrarily. Note that the `SpecCopy::copy` function is generic over the reader specifically to allow wrappers like `Take<R>` to be visible to the implementation of `copy`.
Because this introduces a new layer of specialization to `io::copy`, I think this PR should be benchmarked to make sure performance characteristics aren't too different. I am expecting compilation time to be slightly worse, since there's just more specialization happening, but the actual code run _should_ be the same.
---
## Notes
* No AI tooling of any kind was used during the creation of this PR.
* Please see https://github.com/rust-lang/rust/issues/154046#issuecomment-4416678427 for a review order and broader context for this PR.
Box::leak: tell people to avoid unleaking
r? @nia-e
Cc @rust-lang/opsem
Note that this goes against the advice given by clippy in https://github.com/rust-lang/rust-clippy/pull/17336. I think clippy should be adjusted to recommend `Box::into_non_null` instead. @ArhanChaudhary wold be great if you could make a clippy PR for that. :)
Remove final use of sealed traits from stdlib
Now that stdarch has been updated, this vestigial trait is no longer needed. Since I last touched this, there was one additional usage of it added. This has been removed in favor of the native `impl(self)` syntax.
r? libs
Replace unsafe usage of `NonNull::new_unchecked` with `Box::into_non_null`
~~We can avoid unsafe by replacing `unsafe { NonNull::new_unchecked(Box::into_raw(..)) }` with `NonNull::from_mut(Self::leak(..))`. A simple test to demonstrate the code generation is equivalent: https://godbolt.org/z/P5q9bzPPK~~
We can avoid unsafe by replacing `unsafe { NonNull::new_unchecked(Box::into_raw(..)) }` with the (soon-to-be-stable) `Box::into_non_null(..)`
Additionally, slightly tweak documentation.
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
Report "capacity overflow" for oversized Rc<[T]>/Arc<[T]>
Fixesrust-lang/rust#136797.
Building an Rc<[T]>/Arc<[T]> whose header + payload layout exceeds
isize::MAX unwrapped a LayoutError and panicked with "called
Result::unwrap() on an Err value: LayoutError". Vec and Box report
"capacity overflow" here; this makes Rc/Arc do the same.
Used an inline panic!("capacity overflow") rather than raw_vec's
capacity_overflow(), since that helper is cfg'd out under
no_global_oom_handling while these two layout fns still compile there.
https://github.com/rust-lang/rust/pull/158547 moved `std::io::BufWriter` to
`alloc::io::BufWriter`. That allows it to be used in `no-std` configurations,
and in particular on platforms where unwinding isn't supported.
However one of the doc tests uses `catch_unwind`, which fails on platforms
which cannot unwind. Fix this by copying the magic incantation from a similar
doctest in library/core/src/range.rs
Partially stabilize `box_vec_non_null`
Closesrust-lang/rust#130364
r? libs-api
### What's being stabilized
The following is being stabilized in this PR:
```rust
impl<T: ?Sized> Box<T> {
pub unsafe fn from_non_null(ptr: NonNull<T>) -> Self { .... }
pub fn into_non_null(b: Self) -> NonNull<T> { .... }
}
impl<T> Vec<T> {
pub const unsafe fn from_parts(ptr: NonNull<T>, length: usize, capacity: usize) -> Self { .... }
pub const fn into_parts(self) -> (NonNull<T>, usize, usize) { .... }
}
```
Note that `Vec::from_parts` and `Vec::into_parts` remain const-unstable behind the `const_heap` feature (like `Vec::from_raw_parts` and `Vec::into_raw_parts`).
The following APIs remain gated behind `allocator_api`
```rust
impl<T: ?Sized, A: Allocator> Box<T, A> {
pub unsafe fn from_non_null_in(raw: NonNull<T>, alloc: A) -> Self { .... }
pub fn into_non_null_with_allocator(b: Self) -> (NonNull<T>, A) { .... }
}
impl<T, A: Allocator> Vec<T, A> {
pub const unsafe fn from_parts_in(ptr: NonNull<T>, length: usize, capacity: usize, alloc: A) -> Self { .... }
pub const fn into_parts_with_alloc(self) -> (NonNull<T>, usize, usize, A) { .... }
}
```
The following API is split into a new unstable feature in rust-lang/rust#157843, and remains unstable:
```rust
impl<T, A: Allocator> Vec<T, A> {
pub const fn as_non_null(&mut self) -> NonNull<T> { .... }
}
```
### Implementation History
Most of this feature was ACP'ed in https://github.com/rust-lang/libs-team/issues/418, and implemented in https://github.com/rust-lang/rust/pull/130061. `Vec::as_non_null` was ACP'ed separately in https://github.com/rust-lang/libs-team/issues/440, and implemented in https://github.com/rust-lang/rust/pull/130624.
### Potential issues
* Should `Vec::from_parts` and `Vec::into_parts` be the name used for this? Or should those names be used for functions that take/return `Box<[MaybeUninit<T>]>`? (Raised at https://github.com/rust-lang/rust/issues/130364#issuecomment-2357276951)
* Should these function names be named `non_null` or `nonnull`? (Raised at https://github.com/rust-lang/rust/issues/130364#issuecomment-4525680948. See https://github.com/rust-lang/rust/issues/154237#issuecomment-4120073976.)
* Will the methods on `Vec` collide with anything via autoderef?