about summary refs log tree commit diff
path: root/library/alloc
AgeCommit message (Collapse)AuthorLines
2025-10-01implement `Box::take`edwloef-0/+31
2025-09-30Rollup merge of #146886 - taiki-e:rc-inner-align, r=Mark-SimulacrumMatthias Krüger-8/+12
Add repr(align(2)) to RcInner and ArcInner `Rc` currently assumes that `RcInner` has at least 2-byte alignment, but on AVR, `usize` has 1-byte alignment (this is because the AVR has 1-byte register sizes, so having 2-byte alignment is generally useless), breaking this assumption. https://github.com/rust-lang/rust/blob/9f32ccf35fb877270bc44a86a126440f04d676d0/library/alloc/src/rc.rs#L3005-L3008 This PR adds `repr(align(2))` to force `RcInner` to always have at least 2-byte alignment. Note that `ArcInner` doesn't need `repr(align(2))` because atomic types have the alignment same as its size. This PR adds a comment about this.
2025-09-30Add repr(align(2)) to RcInner and ArcInnerTaiki Endo-8/+12
2025-09-29Use `Iterator::eq` and (dogfood) `eq_by` in compiler and libraryYotam Ofek-1/+1
2025-09-28Auto merge of #147042 - Noratrieb:untrack-caller-vec, r=tgross35bors-121/+0
Remove most `#[track_caller]` from allocating Vec methods They cause significant binary size overhead while contributing little value. closes rust-lang/rust#146963, see that issue for more details.
2025-09-27Remove `cfg(bootstrap)` for `doc_cfg` feature following #141925Guillaume Gomez-16/+1
2025-09-27fmtGuillaume Gomez-6/+1
2025-09-27Remove `doc_cfg_hide` featureGuillaume Gomez-1/+1
2025-09-27Strenghten checks for `doc(auto_cfg(show/hide))` attributesGuillaume Gomez-1/+0
2025-09-27Implement RFC 3631Guillaume Gomez-8/+21
2025-09-26Update CURRENT_RUSTC_VERSION post-bumpMark Rousskov-13/+13
2025-09-25Auto merge of #147037 - matthiaskrgr:rollup-xtgqzuu, r=matthiaskrgrbors-29/+82
Rollup of 8 pull requests Successful merges: - rust-lang/rust#116882 (rustdoc: hide `#[repr]` if it isn't part of the public ABI) - rust-lang/rust#135771 ([rustdoc] Add support for associated items in "jump to def" feature) - rust-lang/rust#141032 (avoid violating `slice::from_raw_parts` safety contract in `Vec::extract_if`) - rust-lang/rust#142401 (Add proper name mangling for pattern types) - rust-lang/rust#146293 (feat: non-panicking `Vec::try_remove`) - rust-lang/rust#146859 (BTreeMap: Don't leak allocators when initializing nodes) - rust-lang/rust#146924 (Add doc for `NonZero*` const creation) - rust-lang/rust#146933 (Make `render_example_with_highlighting` return an `impl fmt::Display`) r? `@ghost` `@rustbot` modify labels: rollup
2025-09-25Remove most `#[track_caller]` from allocating Vec methodsNoratrieb-121/+0
They cause significant binary size overhead while contributing little value. Also removes them from the wrapping String methods that do not panic.
2025-09-25Rollup merge of #146859 - cammeresi:btree-alloc-20250920, r=joboetMatthias Krüger-2/+13
BTreeMap: Don't leak allocators when initializing nodes Memory was allocated via `Box::leak` and thence intended to be tracked and deallocated manually, but the allocator was also leaked, not tracked, and never dropped. Now it is dropped immediately. According to my reading of the `Allocator` trait, if a copy of the allocator remains live, then its allocations must remain live. Since the B-tree has a copy of the allocator that will only be dropped after the nodes, it's safe to not store the allocator in each node (which would be a much more intrusive change). Fixes: rust-lang/rust#106203
2025-09-25Rollup merge of #146293 - BenjaminBrienen:try_remove, r=joboetMatthias Krüger-2/+30
feat: non-panicking `Vec::try_remove` `if index < my_vector.len() { Some(my_vector.remove(index)) } else { None }` is annoying to write and non-panicking functions are broadly useful. APC: https://github.com/rust-lang/libs-team/issues/649 Tracking issue: https://github.com/rust-lang/rust/issues/146954
2025-09-25Rollup merge of #141032 - petrosagg:extract-if-ub, r=joboetMatthias Krüger-25/+39
avoid violating `slice::from_raw_parts` safety contract in `Vec::extract_if` The implementation of the `Vec::extract_if` iterator violates the safety contract adverized by `slice::from_raw_parts` by always constructing a mutable slice for the entire length of the vector even though that span of memory can contain holes from items already drained. The safety contract of `slice::from_raw_parts` requires that all elements must be properly initialized. As an example we can look at the following code: ```rust let mut v = vec![Box::new(0u64), Box::new(1u64)]; for item in v.extract_if(.., |x| **x == 0) { drop(item); } ``` In the second iteration a `&mut [Box<u64>]` slice of length 2 will be constructed. The first slot of the slice contains the bitpattern of an already deallocated box, which is invalid. This fixes the issue by only creating references to valid items and using pointer manipulation for the rest. I have also taken the liberty to remove the big `unsafe` blocks in place of targetted ones with a SAFETY comment. The approach closely mirrors the implementation of `Vec::retain_mut`. **Note to reviewers:** The diff is easier to follow with whitespace hidden.
2025-09-25Auto merge of #147019 - Zalathar:rollup-boxzbmo, r=Zalatharbors-36/+123
Rollup of 14 pull requests Successful merges: - rust-lang/rust#145067 (RawVecInner: add missing `unsafe` to unsafe fns) - rust-lang/rust#145277 (Do not materialise X in [X; 0] when X is unsizing a const) - rust-lang/rust#145973 (Add `std` support for `armv7a-vex-v5`) - rust-lang/rust#146667 (Add an attribute to check the number of lanes in a SIMD vector after monomorphization) - rust-lang/rust#146735 (unstably constify float mul_add methods) - rust-lang/rust#146737 (f16_f128: enable some more tests in Miri) - rust-lang/rust#146766 (Add attributes for #[global_allocator] functions) - rust-lang/rust#146905 (llvm: update remarks support on LLVM 22) - rust-lang/rust#146982 (Remove erroneous normalization step in `tests/run-make/linker-warning`) - rust-lang/rust#147005 (Small string formatting cleanup) - rust-lang/rust#147007 (Explicitly note `&[SocketAddr]` impl of `ToSocketAddrs`) - rust-lang/rust#147008 (bootstrap.py: Respect build.jobs while building bootstrap tool) - rust-lang/rust#147013 (rustdoc: Fix documentation for `--doctest-build-arg`) - rust-lang/rust#147015 (Use `LLVMDisposeTargetMachine`) r? `@ghost` `@rustbot` modify labels: rollup
2025-09-25Rollup merge of #145067 - btj:patch-3, r=tgross35Stuart Cook-36/+123
RawVecInner: add missing `unsafe` to unsafe fns Some (module-private) functions in `library/alloc/src/raw_vec/mod.rs` are unsafe (i.e. may cause UB when called from safe code) but are not marked `unsafe`. Specifically: - `RawVecInner::grow_exact` causes UB if called with `len` and `additional` arguments such that `len + additional` is less than the current capacity. Indeed, in that case it calls [Allocator::grow](https://doc.rust-lang.org/std/alloc/trait.Allocator.html#method.grow) with a `new_layout` that is smaller than `old_layout`, which violates a safety precondition. - The RawVecInner methods for resizing the buffer cause UB if called with an `elem_layout` different from the one used to initially allocate the buffer, because in that case `Allocator::grow` or `Allocator::shrink` are called with an `old_layout` that does not *fit* the allocated block, which violates a safety precondition. - `RawVecInner::current_memory` might cause UB if called with an `elem_layout` different from the one used to initially allocate the buffer, because the `unchecked_mul` might overflow. - Furthermore, these methods cause UB if called with an `elem_layout` where the size is not a multiple of the alignment. This is because `Layout::repeat` is used (in `layout_array`) to compute the allocation's layout when allocating, which includes padding to ensure alignment of array elements, but simple multiplication is used (in `current_memory`) to compute the old allocation's layout when resizing or deallocating, which would cause the layout used to resize or deallocate to not *fit* the allocated block, which violates a safety precondition. I discovered these issues while performing formal verification of `library/alloc/src/raw_vec/mod.rs` per [Challenge 19](https://model-checking.github.io/verify-rust-std/challenges/0019-rawvec.html) of the [AWS Rust Standard Library Verification Contest](https://aws.amazon.com/blogs/opensource/verify-the-safety-of-the-rust-standard-library/).
2025-09-24BTreeMap: Don't leak allocators when initializing nodesSidney Cammeresi-2/+13
Memory was allocated via `Box::leak` and thence intended to be tracked and deallocated manually, but the allocator was also leaked, not tracked, and never dropped. Now it is dropped immediately. According to my reading of the `Allocator` trait, if a copy of the allocator remains live, then its allocations must remain live. Since the B-tree has a copy of the allocator that will only be dropped after the nodes, it's safe to not store the allocator in each node (which would be a much more intrusive change).
2025-09-24feature: Implement vec_try_removeBenjaminBrienen-2/+30
Vec::try_remove is a non-panicking version of Vec::remove
2025-09-24alloc: simplify `Default` for `Box<CStr>` and `Rc<CStr>`joboet-5/+2
2025-09-23Auto merge of #146317 - saethlin:panic=immediate-abort, r=nnethercotebors-9/+7
Add panic=immediate-abort MCP: https://github.com/rust-lang/compiler-team/issues/909 This adds a new panic strategy, `-Cpanic=immediate-abort`. This panic strategy essentially just codifies use of `-Zbuild-std-features=panic_immediate_abort`. This PR is intended to just set up infrastructure, and while it will change how the compiler is invoked for users of the feature, there should be no other impacts. In many parts of the compiler, `PanicStrategy::ImmediateAbort` behaves just like `PanicStrategy::Abort`, because actually most parts of the compiler just mean to ask "can this unwind?" so I've added a helper function so we can say `sess.panic_strategy().unwinds()`. The panic and unwind strategies have some level of compatibility, which mostly means that we can pre-compile the sysroot with unwinding panics then the sysroot can be linked with aborting panics later. The immediate-abort strategy is all-or-nothing, enforced by `compiler/rustc_metadata/src/dependency_format.rs` and this is tested for in `tests/ui/panic-runtime/`. We could _technically_ be more compatible with the other panic strategies, but immediately-aborting panics primarily exist for users who want to eliminate all the code size responsible for the panic runtime. I'm open to other use cases if people want to present them, but not right now. This PR is already large. `-Cpanic=immediate-abort` sets both `cfg(panic = "immediate-abort")` _and_ `cfg(panic = "abort")`. bjorn3 pointed out that people may be checking for the abort cfg to ask if panics will unwind, and also the sysroot feature this is replacing used to require `-Cpanic=abort` so this seems like a good back-compat step. At least for the moment. Unclear if this is a good idea indefinitely. I can imagine this being confusing. The changes to the standard library attributes are purely mechanical. Apart from that, I removed an `unsafe` we haven't needed for a while since the `abort` intrinsic became safe, and I've added a helpful diagnostic for people trying to use the old feature. To test that `-Cpanic=immediate-abort` conflicts with other panic strategies, I've beefed up the core-stubs infrastructure a bit. There is now a separate attribute to set flags on it. I've added a test that this produces the desired codegen, called `tests/run-make-cargo/panic-immediate-abort-codegen/` and also a separate run-make-cargo test that checks that we can build a binary.
2025-09-22Rollup merge of #146887 - taiki-e:rc-doc-feature, r=joboetGuillaume Gomez-18/+0
Remove unused #![feature(get_mut_unchecked)] in Rc and Arc examples https://github.com/rust-lang/rust/pull/93109 removed the use of APIs enabled by this feature in these examples, but the `#![feature]` attributes ware not removed.
2025-09-22Remove unused #![feature(get_mut_unchecked)] in Rc and Arc examplesTaiki Endo-18/+0
2025-09-22avoid violating `slice::from_raw_parts` safety contract in `Vec::extract_if`Petros Angelatos-25/+39
The implementation of the `Vec::extract_if` iterator violates the safety contract adverized by `slice::from_raw_parts` by always constructing a mutable slice for the entire length of the vector even though that span of memory can contain holes from items already drained. The safety contract of `slice::from_raw_parts` requires that all elements must be properly initialized. As an example we can look at the following code: ```rust let mut v = vec![Box::new(0u64), Box::new(1u64)]; for item in v.extract_if(.., |x| **x == 0) { drop(item); } ``` In the second iteration a `&mut [Box<u64>]` slice of length 2 will be constructed. The first slot of the slice contains the bitpattern of an already deallocated box, which is invalid. This fixes the issue by only creating references to valid items and using pointer manipulation for the rest. I have also taken the liberty to remove the big `unsafe` blocks in place of targetted ones with a SAFETY comment. The approach closely mirrors the implementation of `Vec::retain_mut`. Signed-off-by: Petros Angelatos <petrosagg@gmail.com>
2025-09-21Change the cfg to a dashBen Kimock-7/+7
2025-09-21Add panic=immediate-abortBen Kimock-9/+7
2025-09-21btree InternalNode::new safety commentsMarijn Schouten-2/+3
2025-09-21Rollup merge of #146820 - cammeresi:alloc-20250919, r=tgross35Stuart Cook-2/+11
Add unstable attribute to BTreeMap-related allocator generics Although these types aren't directly constructable externally, since they're pub, I think this omission was an oversight. r? libs-api
2025-09-21Rollup merge of #144091 - thaliaarchi:stabilize-new-zeroed, r=Mark-SimulacrumStuart Cook-40/+6
Stabilize `new_zeroed_alloc` The corresponding `new_uninit` and `new_uninit_slice` functions were stabilized in rust-lang/rust#129401, but the zeroed counterparts were left for later out of a [desire](https://github.com/rust-lang/rust/issues/63291#issuecomment-2161039756) to stabilize only the minimal set. These functions are straightforward mirrors of the uninit functions and well-established. Since no blockers or design questions have surfaced in the past year, I think it's time to stabilize them. Tracking issue: rust-lang/rust#129396
2025-09-20docs: improve doc of some methods w/ rangestk-16/+16
2025-09-20Auto merge of #146621 - cammeresi:peek-20250915, r=Amanieubors-35/+41
Make `PeekMut` generic over the allocator - plumb in allocator generic - additional testing Related: rust-lang/rust#122742
2025-09-19Add unstable attribute to BTreeMap-related allocator genericsSidney Cammeresi-2/+11
Although these types aren't directly constructable externally, since they're pub, I think this omission was an oversight.
2025-09-19btree: safety comments for init and newMarijn Schouten-1/+7
2025-09-18Plumb Allocator generic into `std::vec::PeekMut`Sidney Cammeresi-35/+41
2025-09-17Add space after brace in `Box<[T]>::new_uninit_slice` exampleAlan Wu-1/+1
2025-09-17Rollup merge of #144871 - Kivooeo:btree_entry_insert-stabilize, r=jhprattStuart Cook-4/+2
Stabilize `btree_entry_insert` feature This stabilises `btree_map::VacantEntry::insert_entry` and `btree_map::Entry::insert_entry`, following the FCP in [tracking issue](https://github.com/rust-lang/rust/issues/65225). New stable API: ```rust impl<'a, K: Ord, V, A: Allocator + Clone> Entry<'a, K, V, A> { pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, A>; } impl<'a, K: Ord, V, A: Allocator + Clone> VacantEntry<'a, K, V, A> { pub fn insert_entry(mut self, value: V) -> OccupiedEntry<'a, K, V, A>; } ``` (FCP ended almost a year ago, so if it's needed for process we could rerun it) Closes: https://github.com/rust-lang/rust/issues/65225
2025-09-14Switch `std::vec::PeekMut::pop` from self to this parameter.Sidney Cammeresi-2/+2
Since PeekMut implements Deref, it shouldn't have any methods of its own. See also: `std::collections::binary_heap::PeekMut::pop`
2025-09-13Rollup merge of #145471 - rs-sac:extr, r=the8472Jacob Pratt-12/+10
Stabilize BTree{Map,Set}::extract_if Tracking issue: rust-lang/rust#70530 FCP completed: https://github.com/rust-lang/rust/issues/70530#issuecomment-3191454465 Closes: rust-lang/rust#70530
2025-09-07optimization: Don't include ASCII characters in Unicode tablesKarl Meakin-3/+2
The ASCII subset of Unicode is fixed and will never change, so we don't need to generate tables for it with every new Unicode version. This saves a few bytes of static data and speeds up `char::is_control` and `char::is_grapheme_extended` on ASCII inputs. Since the table lookup functions exported from the `unicode` module will give nonsensical errors on ASCII input (and in fact will panic in debug mode), I had to add some private wrapper methods to `char` which check for ASCII-ness first.
2025-09-05RawVecInner: add missing `unsafe` to unsafe fnsBart Jacobs-36/+123
- RawVecInner::grow_exact causes UB if called with len and additional arguments such that len + additional is less than the current capacity. Indeed, in that case it calls Allocator::grow with a new_layout that is smaller than old_layout, which violates a safety precondition. - All RawVecInner methods for resizing the buffer cause UB if called with an elem_layout different from the one used to initially allocate the buffer, because in that case Allocator::grow/shrink is called with an old_layout that does not fit the allocated block, which violates a safety precondition. - RawVecInner::current_memory might cause UB if called with an elem_layout different from the one used to initially allocate the buffer, because the unchecked_mul might overflow. - Furthermore, these methods cause UB if called with an elem_layout where the size is not a multiple of the alignment. This is because Layout::repeat is used (in layout_array) to compute the allocation's layout when allocating, which includes padding to ensure alignment of array elements, but simple multiplication is used (in current_memory) to compute the old allocation's layout when resizing or deallocating, which would cause the layout used to resize or deallocate to not fit the allocated block, which violates a safety precondition.
2025-09-04Rollup merge of #145750 - btj:drop-alloc-guard, r=tgross35Stuart Cook-25/+2
raw_vec.rs: Remove superfluous fn alloc_guard `alloc_guard` checks that its argument is at most `isize::MAX`, but it is called only with layout sizes, which are already guaranteed to be at most `isize::MAX`.
2025-09-03Rollup merge of #145279 - clarfonthey:const-convert-initial, r=tgross35Stuart Cook-7/+17
Constify conversion traits (part 1) This is the first part of rust-lang/rust#144289 being split into smaller pieces. It adds/moves constness of several traits under the `const_convert` feature: * `From` * `Into` * `TryFrom` * `TryInto` * `FromStr` * `AsRef` * `AsMut` * `Borrow` * `BorrowMut` * `Deref` * `DerefMut` There are a few methods that are intrinsically tied to these traits which I've included in the feature. Particularly, those which are wrappers over `AsRef`: * `ByteStr::new` (unstable under `bstr` feature) * `OsStr::new` * `Path::new` Those which directly use `Into`: * `Result::into_ok` * `Result::into_err` And those which use `Deref` and `DerefMut`: * `Pin::as_ref` * `Pin::as_mut` * `Pin::as_deref_mut` * `Option::as_deref` * `Option::as_deref_mut` * `Result::as_deref` * `Result::as_deref_mut` (note: the `Option` and `Result` methods were suggested by ``@npmccallum`` initially as rust-lang/rust#146101) The parts which are missing from this PR are: * Anything that involves heap-allocated types * Making any method const than the ones listed above * Anything that could rely on the above, *or* could rely on system-specific code for `OsStr` or `Path` (note: this mostly makes these methods useless since `str` doesn't implement `AsRef<OsStr>` yet, but it's better to track the method for now and add impls later, IMHO) r? ``@tgross35`` (who mostly already reviewed this)
2025-09-03raw_vec.rs: Remove superfluous fn alloc_guardBart Jacobs-25/+2
It checks that its argument is at most isize::MAX, but it is called only with layout sizes, which are already guaranteed to be at most isize::MAX.
2025-09-01Constify conversion traitsltdk-7/+17
2025-08-31Rollup merge of #145592 - nilotpal-n7:fix-format-alignment, r=lcnrMatthias Krüger-1/+1
Fix format string grammar in docs and improve alignment error message for #144023 This PR improves error messages and documentation for format strings involving alignment and formatting traits. Highlights: - Clearer error messages for invalid alignment specifiers (e.g., `{0:#X>18}`), showing the expected `<`, `^`, or `>` and a working example: println!("{0:>#18X}", value); - Updated UI test `format-alignment-hash.rs` to reflect the improved error output. - Documentation clarification: ensures examples correctly show how width, alignment, and traits like `x`, `X`, `#` combine. Motivation: Previously, using `#` with alignment and width produced confusing errors. This PR guides users on the correct syntax and provides actionable examples. Testing: - Built the compiler (`./x build`) - Blessed and ran UI tests (`./x. test src/test/ui/fmt/format-alignment-hash.rs --bless`) - Verified full test suite passes (`./x test`) Issue: rust-lang/rust#144023
2025-08-27Stabilize BTree{Map,Set}::extract_ifSidney Cammeresi-12/+10
2025-08-27Fix format string grammar in docs and improve alignment error messageNilotpal Gupta-1/+1
2025-08-27Rollup merge of #145562 - tbu-:pr_simplify_to_string_spec, r=tgross35Matthias Krüger-50/+23
Simplify macro generating ToString implementations for `&…&str` Use deref coercion to let the compiler remove any amount of references. Also use that macro for `Cow` and `String`.
2025-08-27Rollup merge of #145335 - clarfonthey:wtf8-core-alloc, r=Mark-SimulacrumMatthias Krüger-0/+1297
Move WTF-8 code from std into core and alloc This is basically a small portion of rust-lang/rust#129411 with a smaller scope. It *does not*\* affect any public APIs; this code is still internal to the standard library. It just moves the WTF-8 code into `core` and `alloc` so it can be accessed by `no_std` crates like `backtrace`. > \* The only public API this affects is by adding a `Debug` implementation to `std::os::windows::ffi::EncodeWide`, which was not present before. This is due to the fact that `core` requires `Debug` implementations for all types, but `std` does not (yet) require this. Even though this was ultimately changed to be a wrapper over the original type, not a re-export, I decided to keep the `Debug` implementation so it remains useful. Like we do with ordinary strings, the tests are still located entirely in `alloc`, rather than splitting them into `core` and `alloc`. ---- Reviewer note: for ease of review, this is split into three commits: 1. Moving the original files into their new "locations" 2. Actually modifying the code to compile. 3. Removing aesthetic changes that were made so that the diff for commit 2 was readable. You can review commits 1 and 3 to verify these claims, but commit 2 contains the majority of the changes you should care about. ---- API changes: `impl Debug for std::os::windows::ffi::EncodeWide`