about summary refs log tree commit diff
path: root/library/alloc/src/vec
AgeCommit message (Collapse)AuthorLines
2025-09-28Auto merge of #147042 - Noratrieb:untrack-caller-vec, r=tgross35bors-57/+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-25Remove most `#[track_caller]` from allocating Vec methodsNoratrieb-57/+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 #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-24feature: Implement vec_try_removeBenjaminBrienen-2/+30
Vec::try_remove is a non-panicking version of Vec::remove
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-4/+4
2025-09-21Add panic=immediate-abortBen Kimock-4/+4
2025-09-20docs: improve doc of some methods w/ rangestk-4/+4
2025-09-18Plumb Allocator generic into `std::vec::PeekMut`Sidney Cammeresi-35/+41
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-08-12Add cast_init and cast_uninit methods for pointersltdk-1/+1
2025-08-12Handle the `capacity == 0` caseSabrinaJewson-27/+34
2025-08-11Respond to review commentsSabrinaJewson-5/+5
2025-08-11Make explicit guarantees about `Vec`’s allocatorSabrinaJewson-4/+47
This commit amends the documentation of `Vec::as_mut_ptr` and `Vec::into_raw_parts` to make it explicit that such calls may be paired with calls to `dealloc` with a suitable layout. This guarantee was effectively already provided by the docs of `Vec::from_raw_parts` mentioning `alloc`. Additionally, we copy-paste and adjust the “Memory layout” section from the documentation of `std::boxed` to `std::vec`. This explains the allocator guarantees in more detail.
2025-08-02Rollup merge of #144478 - joshtriplett:doc-code-formatting-prep, r=AmanieuSamuel Tardieu-5/+5
Improve formatting of doc code blocks We don't currently apply automatic formatting to doc comment code blocks. As a result, it has built up various idiosyncracies, which make such automatic formatting difficult. Some of those idiosyncracies also make things harder for human readers or other tools. This PR makes a few improvements to doc code formatting, in the hopes of making future automatic formatting easier, as well as in many cases providing net readability improvements. I would suggest reading each commit separately, as each commit contains one class of changes.
2025-07-30Implement push_mutBalt-14/+108
2025-07-25Avoid placing `// FIXME` comments inside doc code blocksJosh Triplett-4/+4
This leads tools like rustfmt to get confused, because the doc code block effectively spans two doc comments. As a result, the tools think the first code block is unclosed, and the subsequent terminator opens a new block. Move the FIXME comments outside the doc code blocks, instead.
2025-07-25Improve and regularize comment placement in doc codeJosh Triplett-1/+1
Because doc code does not get automatically formatted, some doc code has creative placements of comments that automatic formatting can't handle. Reformat those comments to make the resulting code support standard Rust formatting without breaking; this is generally an improvement to readability as well. Some comments are not indented to the prevailing indent, and are instead aligned under some bit of code. Indent them to the prevailing indent, and put spaces *inside* the comments to align them with code. Some comments span several lines of code (which aren't the line the comment is about) and expect alignment. Reformat them into one comment not broken up by unrelated intervening code. Some comments are placed on the same line as an opening brace, placing them effectively inside the subsequent block, such that formatting would typically format them like a line of that block. Move those comments to attach them to what they apply to. Some comments are placed on the same line as a one-line braced block, effectively attaching them to the closing brace, even though they're about the code inside the block. Reformat to make sure the comment will stay on the same line as the code it's commenting.
2025-07-15Auto merge of #143877 - xizheyin:143813, r=scottmcm,saethlinbors-3/+17
`std::vec`: Add UB check for `set_len`, `from_raw_parts_in`, and etc. Closes rust-lang/rust#143813 I noticed that `from_parts_in` do the similar things like `from_raw_parts_in`, so I add the UB check in the last commit. If it is not appropriate, I will remove it. And I fix a typo in the first commit. r? `@scottmcm`
2025-07-13update issue number for `const_trait_impl`Deadbeef-1/+1
2025-07-13std::vec: Add UB check in `from_parts_in`xizheyin-0/+5
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-07-13std::vec: Add UB check in `from_raw_parts_in`xizheyin-0/+5
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-07-13`std::vec`: Upgrade `debug_assert` to UB check in `set_len`xizheyin-2/+6
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-07-13Fix typo in `std::vec`xizheyin-1/+1
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-07-07Make `Default` const and add some `const Default` implsEsteban Küber-1/+2
Full list of `impl const Default` types: - () - bool - char - Cell - std::ascii::Char - usize - u8 - u16 - u32 - u64 - u128 - i8 - i16 - i32 - i64 - i128 - f16 - f32 - f64 - f128 - std::marker::PhantomData<T> - Option<T> - std::iter::Empty<T> - std::ptr::Alignment - &[T] - &mut [T] - &str - &mut str - String - Vec<T>
2025-07-02Auto merge of #143338 - matthiaskrgr:rollup-ykaxh04, r=matthiaskrgrbors-82/+82
Rollup of 11 pull requests Successful merges: - rust-lang/rust#131923 (Derive `Copy` and `Hash` for `IntErrorKind`) - rust-lang/rust#138340 (Remove some unsized tuple impls now that we don't support unsizing tuples anymore) - rust-lang/rust#141219 (Change `{Box,Arc,Rc,Weak}::into_raw` to only work with `A = Global`) - rust-lang/rust#142212 (bootstrap: validate `rust.codegen-backends` & `target.<triple>.codegen-backends`) - rust-lang/rust#142237 (Detect more cases of unused_parens around types) - rust-lang/rust#142964 (Attribute rework: a parser for single attributes without arguments) - rust-lang/rust#143070 (Rewrite `macro_rules!` parser to not use the MBE engine itself) - rust-lang/rust#143235 (Assemble const bounds via normal item bounds in old solver too) - rust-lang/rust#143261 (Feed `explicit_predicates_of` instead of `predicates_of`) - rust-lang/rust#143276 (loop match: handle opaque patterns) - rust-lang/rust#143306 (Add `track_caller` attributes to trace origin of Clippy lints) r? `@ghost` `@rustbot` modify labels: rollup try-job: aarch64-apple try-job: x86_64-msvc-1 try-job: x86_64-gnu try-job: dist-i586-gnu-i586-i686-musl try-job: test-various
2025-07-02Rollup merge of #142138 - ashivaram23:vec_into_chunks, r=scottmcmMatthias Krüger-0/+55
Add `Vec::into_chunks` Tracking issue rust-lang/rust#142137
2025-07-01Change `{Box,Arc,Rc,Weak}::into_raw` to only work with `A = Global`Amanieu d'Antras-82/+82
Also applies to `Vec::into_raw_parts`. The expectation is that you can round-trip these methods with `from_raw`, but this is only true when using the global allocator. With custom allocators you should instead be using `into_raw_with_allocator` and `from_raw_in`. The implementation of `Box::leak` is changed to use `Box::into_raw_with_allocator` and explicitly leak the allocator (which was already the existing behavior). This is because, for `leak` to be safe, the allocator must not free its underlying backing store. The `Allocator` trait only guarantees that allocated memory remains valid until the allocator is dropped.
2025-06-11update docs, testJeremy Smart-5/+1
2025-06-07fix wording in assertAmogh Shivaram-1/+1
2025-06-07cfg for no no_global_oom_handlingAmogh Shivaram-0/+1
2025-06-06put feature attribute in exampleAmogh Shivaram-0/+2
2025-06-06Add `into_chunks`Amogh Shivaram-0/+52
2025-06-06fix testsJeremy Smart-0/+1
2025-06-04add Vec::peek_mutJeremy Smart-0/+90
2025-05-17Docs(lib/extract_if): Unify example descriptionPaul Mabileau-1/+1
Signed-off-by: Paul Mabileau <paul.mabileau@harfanglab.fr>
2025-05-17Docs(lib/extract_if): Unify paragraph about elements mutationPaul Mabileau-2/+2
Take the one from `BTreeMap` that seems the best-worded and most precise among the available variations. Signed-off-by: Paul Mabileau <paul.mabileau@harfanglab.fr>
2025-05-17Docs(lib/extract_if): Unify paragraph about closure actionsPaul Mabileau-3/+3
Also fixes `HashSet`'s that incorrectly designated itself as a `list`. Signed-off-by: Paul Mabileau <paul.mabileau@harfanglab.fr>
2025-05-17Docs(lib/alloc/vec): Add the missing `an` to `extract_if`'s first sentencePaul Mabileau-1/+1
As inspired by the equivalent methods from other collection types. Signed-off-by: Paul Mabileau <paul.mabileau@harfanglab.fr>
2025-05-15Rollup merge of #140685 - viliml:patch-1, r=Mark-SimulacrumMatthias Krüger-3/+3
Simplify `Vec::as_non_null` implementation and make it `const` Tracking issue: #130364.
2025-05-06Rollup merge of #139773 - thaliaarchi:vec-into-iter-last, r=workingjubileeStuart Cook-0/+5
Implement `Iterator::last` for `vec::IntoIter` Avoid iterating everything when we have random access to the last element.
2025-05-06Rollup merge of #139764 - dtolnay:extractif, r=AmanieuStuart Cook-2/+13
Consistent trait bounds for ExtractIf Debug impls Closes #137654. Refer to that issue for a table of the **4** different impl signatures we previously had in the standard library for Debug impls of various ExtractIf iterator types. The one we are standardizing on is the one so far only used by `alloc::collections::linked_list::ExtractIf`, which is _no_ `F: Debug` bound, _no_ `F: FnMut` bound, only `T: Debug` bound. This PR applies the following signature changes: ```diff /* alloc::collections::btree_map */ pub struct ExtractIf<'a, K, V, F, A = Global> where - F: 'a + FnMut(&K, &mut V) -> bool, Allocator + Clone, impl Debug for ExtractIf<'a, K, V, F, + A, > where K: Debug, V: Debug, - F: FnMut(&K, &mut V) -> bool, + A: Allocator + Clone, ``` ```diff /* alloc::collections::btree_set */ pub struct ExtractIf<'a, T, F, A = Global> where - T: 'a, - F: 'a + FnMut(&T) -> bool, Allocator + Clone, impl Debug for ExtractIf<'a, T, F, A> where T: Debug, - F: FnMut(&T) -> bool, A: Allocator + Clone, ``` ```diff /* alloc::collections::linked_list */ impl Debug for ExtractIf<'a, T, F, + A, > where T: Debug, + A: Allocator, ``` ```diff /* alloc::vec */ impl Debug for ExtractIf<'a, T, F, A> where T: Debug, - F: Debug, A: Allocator, - A: Debug, ``` ```diff /* std::collections::hash_map */ pub struct ExtractIf<'a, K, V, F> where - F: FnMut(&K, &mut V) -> bool, impl Debug for ExtractIf<'a, K, V, F> where + K: Debug, + V: Debug, - F: FnMut(&K, &mut V) -> bool, ``` ```diff /* std::collections::hash_set */ pub struct ExtractIf<'a, T, F> where - F: FnMut(&T) -> bool, impl Debug for ExtractIf<'a, T, F> where + T: Debug, - F: FnMut(&T) -> bool, ``` I have made the following changes to bring these types into better alignment with one another. - Delete `F: Debug` bounds. These are especially problematic because Rust closures do not come with a Debug impl, rendering the impl useless. - Delete `A: Debug` bounds. Allocator parameters are unstable for now, but in the future this would become an API commitment that we do not debug-print a representation of the allocator when printing an iterator. - Delete `F: FnMut` bounds. Requires `hashbrown` PR: https://github.com/rust-lang/hashbrown/pull/616. **API commitment:** we commit to not doing RefCell voodoo inside ExtractIf to have some way for its Debug impl (which takes &amp;self) to call a FnMut closure, if this is even possible. - Add `T: Debug` bounds (or `K`/`V`), even on Debug impls that do not currently make use of them, but might in the future. **Breaking change.** Must backport into Rust 1.87 (current beta) or do a de-stabilization PR in beta to delay those types by one release. - Render using `debug_struct` + `finish_non_exhaustive`, instead of `debug_tuple`. - Do not render the _entire_ underlying collection. - Show a "peek" field indicating the current position of the iterator.
2025-05-05Consistent trait bounds for ExtractIf Debug implsDavid Tolnay-2/+13
2025-05-05Simplify `Vec::as_non_null` implementation and make it `const`Vilim Lendvaj-3/+3
2025-05-05Rollup merge of #135734 - nk9:extract_if-doc-equivalent, r=tgross35Trevor Gross-6/+12
Correct `extract_if` sample equivalent. Tracking issue: https://github.com/rust-lang/rust/issues/43244 Original PR: #133265 The sample code marked as equivalent in the doc comment isn't currently equivalent. Given the same predicate and range, if your vector were `[1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6]`, then all of the 3s would be removed. `i` is only incremented when an element is dropped, but `range.end` is unchanged, so the items shift down. I got very confused when reading the docs and trying to square this sample code with the explanation of how the function works. Fortunately, the real `extract_if()` does not have this problem. I've added an `end` variable to align the behavior. I've also taken the opportunity to simplify the predicate, which now just matches odd numbers, and to pad out the vec of numbers to line up the zero-indexed range with the integers in the vec. r? the8472
2025-05-04extract_if's sample equivalent now really equivalent.Nick Kocharhook-6/+12
Simpler predicate. Compare sample code output to that of the library function.
2025-05-03Suggest `retain_mut` over `retain` as `Vec::extract_if` alternativePaolo Barbolini-2/+2
2025-05-02Implement Iterator::last for vec::IntoIterThalia Archibald-0/+5
2025-04-28Rename sub_ptr to offset_from_unsigned in docsDaniPopes-2/+2