Commit graph

3527 commits

Author SHA1 Message Date
bors
74fd7516da Auto merge of #147893 - fee1-dead-contrib:constheapheapheap, r=oli-obk
`Vec::push` in consts MVP

Example:

```rust
const X: &'static [u32] = {
    let mut v = Vec::with_capacity(6);
    let mut x = 1;
    while x < 42 {
        v.push(x);
        x *= 2;
    }
    assert!(v.len() == 6);
    v.const_make_global()
};

assert_eq!([1, 2, 4, 8, 16, 32], X);
```

Oh this is fun...

* We split out the implementation of `Global` such that it calls `intrinsics::const_allocate` and `intrinsics::const_deallocate` during compile time. This is achieved using `const_eval_select`
* This allows us to `impl const Allocator for Global`
* We then constify everything necessary for `Vec::with_capacity` and `Vec::push`.
* Added `Vec::const_make_global` to leak and intern the final value via `intrinsics::const_make_global`. If we see any pointer in the final value of a `const` that did not call `const_make_global`, we error as implemented in rust-lang/rust#143595.

r? `@rust-lang/wg-const-eval`

To-do for me:
* [x] Assess the rustdoc impact of additional bounds in the method
* [x] ~~Increase test coverage~~ I think this is enough for an unstable feature.
2026-01-06 11:39:17 +00:00
bors
bd33b83cfd Auto merge of #149784 - fereidani:retain_mut, r=joboet
Improve alloc `Vec::retain_mut` performance

Hi,

While reading the rustc source code, I noticed it uses `smallvec` and `thin-vec` in many places. I started reviewing those crates, optimized their `retain_mut` implementation, and then realized they were using the exact same algorithm as `alloc::vec::Vec` with less unsafe  So now I’m back here with a PR for the standard library 😂.

In my benchmarks, this version is noticeably faster when `retain_mut` actually removes elements (thanks to fewer pointer operations, it just advances `write_index`), while performing identically to the current implementation when nothing is removed.

Let’s see if bors likes this change or not.
2026-01-05 14:55:14 +00:00
Khashayar Fereidani
bd79ea1b74 Improve and optimize retain_mut implementation 2026-01-05 13:18:41 +03:30
Khashayar Fereidani
0330cc2446 Add feature flag likely/unlikely for alloc 2026-01-05 13:14:11 +03:30
bors
e29fcf45e4 Auto merge of #150674 - matthiaskrgr:rollup-tnkgbcx, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - rust-lang/rust#150554 (test: add regression cases for valtree hashing ICE)
 - rust-lang/rust#150597 (make specialization of `Vec::extend` and `VecDeque::extend_front` work for vec::IntoIter with any `Allocator`, not just `Global`)
 - rust-lang/rust#150619 (alloc: Move Cow impl to existing ones)
 - rust-lang/rust#150660 (THIR pattern building: Pass HIR nodes instead of loose types/spans)
 - rust-lang/rust#150671 (miri subtree update)

r? `@ghost`
`@rustbot` modify labels: rollup
2026-01-04 16:58:33 +00:00
Matthias Krüger
18910b7353
Rollup merge of #150619 - cvengler:move-cow-impl, r=Mark-Simulacrum
alloc: Move Cow impl to existing ones

Right now, the `borrow.rs` module starts with a `Cow` impl, although most of them can be found below.

This hurts code readability because there is `ToOwned` alongside its impl directly below it.

Moving it to the others down below makes sense here, given that the entire enum depends on `ToOwned` anyways.
2026-01-04 16:16:10 +01:00
Matthias Krüger
9dd3b2358e
Rollup merge of #150597 - antonilol:extend-from-vec-any-allocator, r=jhpratt
make specialization of `Vec::extend` and `VecDeque::extend_front` work for vec::IntoIter with any `Allocator`, not just `Global`

These functions consume all the elements from the respective collection, but do not care about the `Allocator` they use. Without specifying one (like in `vec::IntoIter<T>`) the specialization is only chosen when `A=Global`.

(extra context: `VecDeque::extend_front` is unstable and tracked by rust-lang/rust#146975)
2026-01-04 16:16:10 +01:00
Stuart Cook
f63ab49598
Rollup merge of #150643 - hkBst:cast-slice-from-raw-parts-1, r=tgross35
vec in-place-drop: avoid creating an intermediate slice

Avoids clippy warning:
```text
warning: implicitly casting the result of `from_raw_parts_mut` to `*mut [T]`
  --> library/alloc/src/vec/in_place_drop.rs:25:32
   |
25 |             ptr::drop_in_place(slice::from_raw_parts_mut(self.inner, self.len()));
   |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace_with: `core::ptr::slice_from_raw_parts_mut(self.inner, self.len())`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_slice_from_raw_parts
   = note: `-W clippy::cast-slice-from-raw-parts` implied by `-W clippy::suspicious`
   = help: to override `-W clippy::suspicious` add `#[allow(clippy::cast_slice_from_raw_parts)]`
```
2026-01-04 21:37:03 +11:00
bors
f280e764d5 Auto merge of #150595 - antonilol:deque_extend_front_prepend_drain_spec, r=jhpratt
Add specialization for `deque1.prepend(deque2.drain(range))` (VecDeque::prepend and extend_front)

Tracking issue: rust-lang/rust#146975

This specialization makes sure `deque1.prepend(deque2.drain(..))` gets similar speed to `deque1.append(&mut deque2)`. `deque1.prepend(deque2.drain(..))` is the equivalent of `deque1.append(&mut deque2)` but appending to the front (see the [second example of prepend](https://doc.rust-lang.org/nightly/std/collections/struct.VecDeque.html#method.prepend), prepend is from the same tracking issue).
2026-01-04 05:21:49 +00:00
Marijn Schouten
47798e261e vec in-place-drop: avoid creating an intermediate slice 2026-01-03 12:08:40 +00:00
Clara Engler
9a675c09cf
alloc: Move Cow impl to existing ones
Right now, the `borrow.rs` module starts with a `Cow` impl, although
most of them can be found below.

This hurts code readability because there is `ToOwned` alongside its
impl directly below it.

Moving it to the others down below makes sense here, given that the
entire enum depends on `ToOwned` anyways.
2026-01-02 20:40:04 +01:00
Antoni Spaanderman
9a170fedd7
make specialization of Vec::extend and VecDeque::extend_front work for vec::IntoIter with any Allocator, not just Global 2026-01-02 16:15:40 +01:00
Antoni Spaanderman
7e425b8985
Add specialization for deque1.prepend(deque2.drain(range))
This is used when moving elements between `VecDeque`s
This pattern is also used in examples of `VecDeque::prepend`. (see its docs)
2026-01-02 16:05:42 +01:00
Alessio
bfe591aac4
library: Fix typo in the documentatio of Cstring::from_vec_with_nul
Fixes the sentence "Attempts to converts a Vec<u8> to a CString.", where "converts" should be in the base form as it is part of the to-infinitive form.
2026-01-02 14:54:36 +01:00
Deadbeef
a913065d80 fix rustfmt and bless tidy/tests 2026-01-01 19:17:11 -05:00
Deadbeef
cf61cbcb07 Move into const impl blocks 2026-01-01 19:17:11 -05:00
Deadbeef
47864e80cb address review comments; fix CI 2026-01-01 19:17:11 -05:00
Deadbeef
3982d3e706 Vec::push in consts MVP 2026-01-01 19:17:11 -05:00
bors
0e89999425 Auto merge of #147247 - Qelxiros:vecdeque_splice, r=Mark-Simulacrum
add VecDeque::splice

Tracking issue: rust-lang/rust#146975
2025-12-30 19:18:37 +00:00
Jonathan Brouwer
596e1e3f88
Rollup merge of #150344 - hkBst:cleanup-linked-list, r=jhpratt
Cleanup linked list

 - Replaces some checked_sub().unwrap_or(0) with saturating_sub().
 - Replaces NonNull::from(Box::leak(node)) with Box::into_non_null(node)
2025-12-30 10:42:28 +01:00
bors
67944d6bec Auto merge of #149694 - lolbinarycat:alloc-extend-slice-of-str-spec, r=Mark-Simulacrum
alloc: specialize String::extend for slices of str

Here's a small optimization via specialization that can potentially eliminate a fair few reallocations when building strings using specific patterns, unsure if this justifies the use of unsafe, but I had the code implemented from rust-lang/rust#148604, so I thought it was worth submitting to see.
2025-12-29 22:07:30 +00:00
Marijn Schouten
eea3d794ff LinkedList: use Box::into_non_null_with_allocator 2025-12-29 19:08:34 +00:00
Jeremy Smart
0763954226
add VecDeque::splice 2025-12-29 13:25:56 -05:00
bors
21cf7fb3ff Auto merge of #150463 - JonathanBrouwer:rollup-ietend4, r=JonathanBrouwer
Rollup of 5 pull requests

Successful merges:

 - rust-lang/rust#147499 (Implement round-ties-to-even for Duration Debug for consistency with f64)
 - rust-lang/rust#149447 (Rewrite `String::replace_range`)
 - rust-lang/rust#149469 (Leverage &mut in OnceLock when possible)
 - rust-lang/rust#149921 (Add new source component that includes GPL-licensed source)
 - rust-lang/rust#150460 (fix ManuallyDrop::into_inner aliasing (Miri) issues)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-12-28 18:23:22 +00:00
Jonathan Brouwer
3c7ffa5dd1
Rollup merge of #149447 - theemathas:string-replace_range, r=Mark-Simulacrum
Rewrite `String::replace_range`

This simplifies the code, provides better panic messages, and avoids an integer overflow.
2025-12-28 18:16:09 +01:00
bors
9f54abeeba Auto merge of #150076 - heathdutton:fix-linked-list-cursor-pop-front-index, r=Mark-Simulacrum
Fix `LinkedList::CursorMut::pop_front` to correctly update index

When `pop_front` was called while the cursor pointed to the front element, `move_next` incremented the index but it was never decremented afterwards, causing the index to incorrectly report 1 instead of 0.

Always decrement the index after popping from front using `saturating_sub` to handle edge cases safely.

Fixes rust-lang/rust#147616
2025-12-28 15:10:14 +00:00
Marijn Schouten
9b2d03bd60 .checked_sub(1).unwrap_or(0) → .saturating_sub(1) 2025-12-24 11:37:54 +00:00
Boxy Uwu
90a33f69f4 replace version placeholder 2025-12-19 15:04:30 -08:00
Heath Dutton🕴️
901fe3f804 Fix LinkedList::CursorMut::pop_front to correctly update index
When `pop_front` was called while the cursor pointed to the front
element, `move_next` incremented the index but it was never decremented
afterwards, causing the index to incorrectly report 1 instead of 0.

Always decrement the index after popping from front using
`saturating_sub` to handle edge cases safely.
2025-12-17 15:42:47 -05:00
Alice Ryhl
78f52c1d12 Update tracking issue for PinCoerceUnsized 2025-12-17 20:26:41 +00:00
Chris Denton
735c45eda4
Rollup merge of #149272 - DrAsu33:fix-vec-iter-zst-alignment-148682, r=Mark-Simulacrum
Fix vec iter zst alignment

Closes rust-lang/rust#148682
2025-12-14 09:18:28 +00:00
Matthias Krüger
3a3c7b580f
Rollup merge of #149795 - estebank:let-else-std, r=workingjubilee
Use `let`...`else` instead of `match foo { ... _ => return };` and `if let ... else return` in std

Split off rust-lang/rust#148837.
2025-12-10 07:54:21 +01:00
Matthias Krüger
6078dd3bdf
Rollup merge of #147725 - bjorn3:remove_oom_panic, r=Amanieu
Remove -Zoom=panic

There are major questions remaining about the reentrancy that this allows. It doesn't have any users on github outside of a single project that uses it in a panic=abort project to show backtraces. It can still be emulated through `#[alloc_error_handler]` or `set_alloc_error_hook` depending on if you use the standard library or not. And finally it makes it harder to do various improvements to the allocator shim.

With this PR the sole remaining symbol in the allocator shim that is not effectively emulating weak symbols is the symbol that prevents skipping the allocator shim on stable even when it would otherwise be empty because libstd + `#[global_allocator]` is used.

Closes https://github.com/rust-lang/rust/issues/43596
Fixes https://github.com/rust-lang/rust/issues/126683
2025-12-10 07:54:17 +01:00
Esteban Küber
0488690d3e Use let...else instead of match foo { ... _ => return }; and if let ... else return in std 2025-12-09 23:35:14 +00:00
DrAsu33
34392a99c0 Fix(alloc): Correctly handle ZST alignment for IntoIter::nth_back
This commit consolidates all changes, including the core logic fix for IntoIter::nth_back and the addition of the Miri regression test in `library/alloctests/tests/vec.rs`, to prevent Undefined Behavior (UB) when dealing with highly-aligned Zero-Sized Types.
2025-12-09 07:56:26 +00:00
Theemathas Chirananthavat
5f5286beb2 Rewrite String::replace_range
This simplifies the code, provides better panic messages,
and avoids an integer overflow.
2025-12-08 17:38:45 +07:00
bors
d427ddfe90 Auto merge of #149717 - matthiaskrgr:rollup-spntobh, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - rust-lang/rust#149659 (Look for typos when reporting an unknown nightly feature)
 - rust-lang/rust#149699 (Implement `Vec::from_fn`)
 - rust-lang/rust#149700 (rustdoc: fix bugs with search aliases and merging)
 - rust-lang/rust#149713 (Update windows-gnullvm platform support doc)
 - rust-lang/rust#149716 (miri subtree update)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-12-06 21:42:15 +00:00
Matthias Krüger
8a6f82efac
Rollup merge of #148814 - bend-n:stabilize_array_windows, r=scottmcm
stabilize `array_windows`

Tracking issue: rust-lang/rust#75027
Closes: rust-lang/rust#75027
FCP completed: https://github.com/rust-lang/rust/issues/75027#issuecomment-3477510526
2025-12-06 09:57:59 +01:00
EFanZh
c5113ca1e2 Implement Vec::from_fn 2025-12-06 12:55:15 +08:00
binarycat
38ab135542 alloc: specialize String::extend for slices of str 2025-12-05 17:22:18 -06:00
Matthias Krüger
4d08c33fc1
Rollup merge of #148662 - leftmostcat:document-isize-limit, r=joboet
alloc: Document panics when allocations will exceed max

Document panics in `String` and `Vec` due to capacity overflowing `isize::MAX`. Correct outdated claims of `usize::MAX` limit.

Fixes https://github.com/rust-lang/rust/issues/148598.

Ping `@lolbinarycat`
2025-12-05 16:17:05 +01:00
bors
646a3f8c15 Auto merge of #149125 - zachs18:btreemap-eq-perf, r=workingjubilee
In `BTreeMap::eq`, do not compare the elements if the sizes are different.

Reverts rust-lang/rust#147101 in library/alloc/src/btree/

rust-lang/rust#147101 replaced some instances of code like `a.len() == b.len() && a.iter().eq(&b)` with just `a.iter().eq(&b)`, but the optimization that PR introduced only applies for `TrustedLen` iterators, and `BTreeMap`'s itertors are not `TrustedLen`, so this theoretically regressed perf for comparing large `BTreeMap`/`BTreeSet`s with unequal lengths but equal prefixes, (and also made it so that comparing two different-length `BTreeMap`/`BTreeSet`s with elements whose `PartialEq` impls that can panic now can panic, though this is not a "promised" behaviour either way (cc rust-lang/rust#149122))

Given that `TrustedLen` is an unsafe trait, I opted to not implement it for `BTreeMap`'s iterators, and instead just revert the change. If someone else wants to audit `BTreeMap`'s iterators to make sure they always return the right number of items (even in the face of incorrect user `Ord` impls) and then implement `TrustedLen` for them so that the optimization works for them, then this can be closed in favor of that (or if the perf regression is deemed too theoretical, this can be closed outright).

Example of theoretical perf regression: https://play.rust-lang.org/?version=beta&mode=release&edition=2024&gist=a37e3d61e6bf02669b251315c9a44fe2 (very rough estimates, using `Instant::elapsed`).
In release mode on stable the comparison takes ~23.68µs.
In release mode on beta/nightly the comparison takes ~48.351057ms.
2025-12-02 17:04:58 +00:00
Stuart Cook
dbb92adfc1
Rollup merge of #145628 - tinnamchoi:fix-btree-append, r=Amanieu
[std][BTree] Fix behavior of `::append` to match documentation, `::insert`, and `::extend`

Resolves rust-lang/rust#145614
2025-12-02 13:56:29 +11:00
bendn
919e46f4d4
stabilize [T]::array_windows 2025-12-02 00:37:17 +07:00
Matthias Krüger
5f3dc5d89a
Rollup merge of #149102 - bend-n:maybe_uninit_slice, r=joboet
stabilize maybe_uninit_slice

Tracking issue: rust-lang/rust#63569
Closes: rust-lang/rust#63569
FCP completed: https://github.com/rust-lang/rust/issues/63569#issuecomment-3477510504

Removes:
```rs
pub const fn slice_as_ptr(this: &[MaybeUninit<T>]) -> *const T;
pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T;
```
2025-12-01 17:55:06 +01:00
bjorn3
8f55c15bfe Remove -Zoom=panic
There are major questions remaining about the reentrancy that this
allows. It doesn't have any users on github outside of a single project
that uses it in a panic=abort project to show backtraces. It
can still be emulated through #[alloc_error_handler] or
set_alloc_error_hook depending on if you use the standard library or
not. And finally it makes it harder to do various improvements to the
allocator shim.
2025-11-28 19:30:39 +00:00
Yotam Ofek
6d05636645 Add impl TrustedLen on BTree{Map,Set} iterators 2025-11-27 14:48:18 +02:00
bendn
d67f99af2e
fix 2025-11-27 17:55:34 +07:00
bors
1be6b13be7 Auto merge of #149079 - zachs18:clone_from_ref, r=Mark-Simulacrum
Add `Box::clone_from_ref` and similar under `feature(clone_from_ref)`

Tracking issue: https://github.com/rust-lang/rust/issues/149075

Accepted ACP: https://github.com/rust-lang/libs-team/issues/483

This PR implements `clone_from_ref` (and `try_*` and `_*in` variants), to get a `Box<T>`, `Arc<T>`, or `Rc<T>` by cloning from a `&T` where `T: CloneToUninit`.

The "Implement..." commits replace some ad-hoc conversions with `clone_from_ref` variants, which can be split out to a separate PR if desired.

This PR will conflict with https://github.com/rust-lang/rust/pull/148769 due to usage of `Layout::dangling` (which that PR is renaming to `dangling_ptr`), so they should not be rolled up together, and the one which merges later will need to be amended.
2025-11-26 18:21:00 +00:00
Mads Marquart
1111730c57 Add doc aliases list and vector to Vec 2025-11-23 05:58:15 +01:00