about summary refs log tree commit diff
path: root/library/alloc/src/vec/mod.rs
AgeCommit message (Collapse)AuthorLines
2025-01-25[Clippy] Add vec_reserve & vecdeque_reserve diagnostic itemswowinter13-0/+1
2025-01-24Rollup merge of #135728 - hkBst:patch-8, r=joboetMatthias Krüger-3/+5
document order of items in iterator from drain fixes #135710
2025-01-24Rollup merge of #135983 - hkBst:patch-13, r=jhprattMatthias Krüger-4/+3
Doc difference between extend and extend_from_slice fixes #97119
2025-01-24Doc difference between extend and extend_from_sliceMarijn Schouten-4/+3
fixes #97119
2025-01-24Make `Vec::pop_if` a bit more presentablePavel Grigorenko-7/+4
2025-01-19Fix whitespaceMarijn Schouten-1/+1
2025-01-19document order of items in iterator from drainMarijn Schouten-3/+5
fixes 135710
2025-01-13Add another `Vec::splice` examplecod10129-3/+13
Add an example for using splice to insert multiple elements efficiently into a vector.
2024-12-22Auto merge of #131193 - EFanZh:asserts-vec-len, r=the8472bors-2/+9
Asserts the maximum value that can be returned from `Vec::len` Currently, casting `Vec<i32>` to `Vec<u32>` takes O(1) time: ```rust // See <https://godbolt.org/z/hxq3hnYKG> for assembly output. pub fn cast(vec: Vec<i32>) -> Vec<u32> { vec.into_iter().map(|e| e as _).collect() } ``` But the generated assembly is not the same as the identity function, which prevents us from casting `Vec<Vec<i32>>` to `Vec<Vec<u32>>` within O(1) time: ```rust // See <https://godbolt.org/z/7n48bxd9f> for assembly output. pub fn cast(vec: Vec<Vec<i32>>) -> Vec<Vec<u32>> { vec.into_iter() .map(|e| e.into_iter().map(|e| e as _).collect()) .collect() } ``` This change tries to fix the problem. You can see the comparison here: <https://godbolt.org/z/jdManrKvx>.
2024-12-20Rollup merge of #126118 - jan-ferdinand:docs_for_vec_set_len, r=the8472Jacob Pratt-1/+6
docs: Mention `spare_capacity_mut()` in `Vec::set_len` I recently went down a small rabbit hole when trying to identify safe use of `Vec::set_len`. The solution was `Vec::spare_capacity_mut`. I think the docs on `Vec::set_len` benefit from mentioning this method. A possible counter-argument could be that the [clippy lint `uninit_vec`](https://rust-lang.github.io/rust-clippy/master/index.html#/uninit_vec) already nudges people in the right direction. However, I think a working example on `Vec::set_len` is still beneficial. Happy to hear your thoughts on the matter. :blush:
2024-12-16Add a range argument to vec.extract_ifThe 8472-15/+28
2024-12-15Asserts the maximum value that can be returned from `Vec::len`EFanZh-2/+9
2024-12-14Replace i32 by char to add claritytkirishima-14/+14
In some `Vec` and `VecDeque` examples where elements are i32, examples can seem a bit confusing at first glance if a parameter of the method is an usize.
2024-12-05Improve documentationXelph-11/+14
Fix missing newlines that rustfmt removed. fix trailing whitespace Fix duplicate word. Reformat panic reasons into a list remove trailing whitespace 2 electric boogaloo Change verbe tense. Integrate suggestions
2024-11-29Auto merge of #133533 - BoxyUwU:bump-boostrap, r=jieyouxu,Mark-Simulacrumbors-2/+2
Bump boostrap compiler to new beta Currently failing due to something about the const stability checks and `panic!`. I'm not sure why though since I wasn't able to see any PRs merged in the past few days that would result in a `cfg(bootstrap)` that shouldn't be removed. cc `@RalfJung` #131349
2024-11-28Also use zero when referencing to capacity or lengthtimvisee-4/+4
2024-11-27update cfgsBoxy-2/+2
2024-11-11Tag relevant functions with #[rustc_as_ptr] attributegavincrawford-0/+2
2024-10-14Auto merge of #126557 - GrigorenkoPV:vec_track_caller, r=joboetbors-0/+38
Add `#[track_caller]` to allocating methods of `Vec` & `VecDeque` Part 4 in a lengthy saga. r? `@joshtriplett` because they were the reviewer the last 3 times. `@bors` rollup=never "[just in case this has perf effects, Vec is hot](https://github.com/rust-lang/rust/pull/79323#issuecomment-731866746)" This was first attempted in #79323 by `@nvzqz.` It got approval from `@joshtriplett,` but rotted with merge conflicts and got closed. Then it got picked up by `@Dylan-DPC-zz` in #83359. A benchmark was run[^perf], the results (after a bit of thinking[^thinking]) were deemed ok[^ok], but there was a typo[^typo] and the PR was made from a wrong remote in the first place[^remote], so #83909 was opened instead. By the time #83909 rolled around, the methods in question had received some optimizations[^optimizations], so another perf run was conducted[^perf2]. The results were ok[^ok2]. There was a suggestion to add regression tests for panic behavior [^tests], but before it could be addressed, the PR fell victim to merge conflicts[^conflicts] and died again[^rip]. 3 years have passed, and (from what I can tell) this has not been tried again, so here I am now, reviving this old effort. Given how much time has passed and the fact that I've also touched `VecDeque` this time, it probably makes sense to `@bors` try `@rust-timer` [^perf]: https://github.com/rust-lang/rust/pull/83359#issuecomment-804450095 [^thinking]: https://github.com/rust-lang/rust/pull/83359#issuecomment-805286704 [^ok]: https://github.com/rust-lang/rust/pull/83359#issuecomment-812739031 [^typo]: https://github.com/rust-lang/rust/pull/83359#issuecomment-812750205 [^remote]: https://github.com/rust-lang/rust/pull/83359#issuecomment-814067119 [^optimizations]: https://github.com/rust-lang/rust/pull/83909#issuecomment-813736593 [^perf2]: https://github.com/rust-lang/rust/pull/83909#issuecomment-813825552 [^ok2]: https://github.com/rust-lang/rust/pull/83909#issuecomment-813831341 [^tests]: https://github.com/rust-lang/rust/pull/83909#issuecomment-825788964 [^conflicts]: https://github.com/rust-lang/rust/pull/83909#issuecomment-851173480 [^rip]: https://github.com/rust-lang/rust/pull/83909#issuecomment-873569771
2024-10-07Rollup merge of #128399 - mammothbane:master, r=Amanieu,tgross35Stuart Cook-11/+44
liballoc: introduce String, Vec const-slicing This change `const`-qualifies many methods on `Vec` and `String`, notably `as_slice`, `as_str`, `len`. These changes are made behind the unstable feature flag `const_vec_string_slice`. ## Motivation This is to support simultaneous variance over ownership and constness. I have an enum type that may contain either `String` or `&str`, and I want to produce a `&str` from it in a possibly-`const` context. ```rust enum StrOrString<'s> { Str(&'s str), String(String), } impl<'s> StrOrString<'s> { const fn as_str(&self) -> &str { match self { // In a const-context, I really only expect to see this variant, but I can't switch the implementation // in some mode like #[cfg(const)] -- there has to be a single body Self::Str(s) => s, // so this is a problem, since it's not `const` Self::String(s) => s.as_str(), } } } ``` Currently `String` and `Vec` don't support this, but can without functional changes. Similar logic applies for `len`, `capacity`, `is_empty`. ## Changes The essential thing enabling this change is that `Unique::as_ptr` is `const`. This lets us convert `RawVec::ptr` -> `Vec::as_ptr` -> `Vec::as_slice` -> `String::as_str`. I had to move the `Deref` implementations into `as_{str,slice}` because `Deref` isn't `#[const_trait]`, but I would expect this change to be invisible up to inlining. I moved the `DerefMut` implementations as well for uniformity.
2024-10-06liballoc: introduce String, Vec const-slicingNathan Perry-11/+44
This change `const`-qualifies many methods on Vec and String, notably `as_slice`, `as_str`, `len`. These changes are made behind the unstable feature flag `const_vec_string_slice` with the following tracking issue: https://github.com/rust-lang/rust/issues/129041
2024-09-20Add `Vec::as_non_null`Tim (Theemathas) Chirananthavat-2/+69
2024-09-20Add `#[track_caller]` to allocating methods of `Vec` & `VecDeque`Pavel Grigorenko-0/+38
2024-09-19[Clippy] Swap `manual_while_let_some` to use diagnostic items instead of pathsGnomedDev-0/+2
2024-09-19[Clippy] Swap `repeat_vec_with_capacity` to use diagnostic item instead of pathGnomedDev-0/+1
2024-09-19[Clippy] Swap `VecArgs::hir` to use diagnostic items instead of pathsGnomedDev-0/+2
2024-09-19[Clippy] Swap `option_as_ref_deref` to use diagnostic items instead of pathsGnomedDev-0/+2
2024-09-15Rollup merge of #130061 - theemathas:box_vec_non_null, ↵Stuart Cook-14/+306
r=MarkSimulacrum,workingjubilee Add `NonNull` convenience methods to `Box` and `Vec` Implements the ACP: https://github.com/rust-lang/libs-team/issues/418. The docs for the added methods are mostly copied from the existing methods that use raw pointers instead of `NonNull`. I'm new to this "contributing to rustc" thing, so I'm sorry if I did something wrong. In particular, I don't know what the process is for creating a new unstable feature. Please advise me if I should do something. Thank you.
2024-09-15Add tracking issue number for `box_vec_non_null`Tim (Theemathas) Chirananthavat-4/+4
2024-09-08add FIXME(const-hack)Ralf Jung-1/+1
2024-09-07Add `NonNull` convenience methods to `Vec`Tim (Theemathas) Chirananthavat-14/+306
2024-09-02Auto merge of #129063 - the8472:cold-opt-size, r=Amanieubors-0/+4
Apply size optimizations to panic machinery and some cold functions * std dependencies gimli and addr2line are now built with opt-level=s * various panic-related methods and `#[cold]` methods are now marked `#[optimize(size)]` Panics should be cold enough that it doesn't make sense to optimize them for speed. The only tradeoff here is if someone does a lot of backtrace captures (without panics) and printing then the opt-level change might impact their perf. Seems to be the first use of the optimize attribute. Tracking issue #54882
2024-08-19docs: Mention `spare_capacity_mut()` in `Vec::set_len`Jan Ferdinand Sauer-1/+6
2024-08-14apply #[optimize(size)] to #[cold] ones and part of the panick machineryThe 8472-0/+4
2024-08-14add Box::as_ptr and Box::as_mut_ptr methodsRalf Jung-2/+1
2024-08-03Rollup merge of #127586 - zachs18:more-must-use, r=cuviperMatthias Krüger-0/+2
Add `#[must_use]` to some `into_raw*` functions. cc #121287 r? ``@cuviper`` Adds `#[must_use = "losing the pointer will leak memory"]`[^1] to `Box::into_raw(_with_allocator)`, `Vec::into_raw_parts(_with_alloc)`, `String::into_raw_parts`[^2], and `rc::{Rc, Weak}::into_raw_with_allocator` (Rc's normal `into_raw` and all of `Arc`'s `into_raw*`s are already `must_use`). Adds `#[must_use = "losing the raw <resource name may leak resources"]` to `IntoRawFd::into_raw_fd`, `IntoRawSocket::into_raw_socket`, and `IntoRawHandle::into_raw_handle`. [^1]: "*will* leak memory" may be too-strong wording (since `Box`/`Vec`/`String`/`rc::Weak` might not have a backing allocation), but I left it as-is for simplicity and consistency. [^2]: `String::into_raw_parts`'s `must_use` message is changed from the previous (possibly misleading) "`self` will be dropped if the result is not used".
2024-07-30Auto merge of #128234 - jcsp:retain-empty-case, r=tgross35bors-0/+6
Optimize empty case in Vec::retain While profiling some code that happens to call Vec::retain() in a tight loop, I noticed more runtime than expected in retain, even in a bench case where the vector was always empty. When I wrapped my call to retain in `if !myvec.is_empty()` I saw faster execution compared with doing retain on an empty vector. On closer inspection, Vec::retain is doing set_len(0) on itself even when the vector is empty, and then resetting the length again in BackshiftOnDrop::drop. Unscientific screengrab of a flamegraph illustrating how we end up spending time in set_len and drop: ![image](https://github.com/user-attachments/assets/ebc72ace-84a0-4432-9b6f-1b3c96d353ba)
2024-07-29Optimize empty case in Vec::retainJohn Spray-0/+6
2024-07-29Reformat `use` declarations.Nicholas Nethercote-3/+2
The previous commit updated `rustfmt.toml` appropriately. This commit is the outcome of running `x fmt --all` with the new formatting options.
2024-07-28Rollup merge of #127765 - bitfield:fix_stdlib_doc_nits, r=dtolnayGuillaume Gomez-12/+14
Fix doc nits Many tiny changes to stdlib doc comments to make them consistent (for example "Returns foo", rather than "Return foo"), adding missing periods, paragraph breaks, backticks for monospace style, and other minor nits.
2024-07-27Rollup merge of #125897 - RalfJung:from-ref, r=AmanieuTrevor Gross-2/+2
from_ref, from_mut: clarify documentation This was brought up [here](https://github.com/rust-lang/rust/issues/56604#issuecomment-2143193486). The domain of quantification is generally always constrained by the type in the type signature, and I am not sure it's always worth spelling that out explicitly as that makes things exceedingly verbose. But since this was explicitly brought up, let's clarify.
2024-07-26Fix doc nitsJohn Arundel-12/+14
Many tiny changes to stdlib doc comments to make them consistent (for example "Returns foo", rather than "Return foo", per RFC1574), adding missing periods, paragraph breaks, backticks for monospace style, and other minor nits. https://github.com/rust-lang/rfcs/blob/master/text/1574-more-api-documentation-conventions.md#appendix-a-full-conventions-text
2024-07-13Rollup merge of #127446 - zachs18:miri-stdlib-leaks-core-alloc, ↵Jubilee-0/+6
r=Mark-Simulacrum Remove memory leaks in doctests in `core`, `alloc`, and `std` cc `@RalfJung` https://github.com/rust-lang/rust/issues/126067 https://github.com/rust-lang/miri/issues/3670 Should be no actual *documentation* changes[^1], all added/modified lines in the doctests are hidden with `#`, This PR splits the existing memory leaks in doctests in `core`, `alloc`, and `std` into two general categories: 1. "Non-focused" memory leaks that are incidental to the thing being documented, and/or are easy to remove, i.e. they are only there because preventing the leak would make the doctest less clear and/or concise. - These doctests simply have a comment like `# // Prevent leaks for Miri.` above the added line that removes the memory leak. - [^2]Some of these would perhaps be better as part of the public documentation part of the doctest, to clarify that a memory leak can happen if it is not otherwise mentioned explicitly in the documentation (specifically the ones in `(A)Rc::increment_strong_count(_in)`). 2. "Focused" memory leaks that are intentional and documented, and/or are possibly fragile to remove. - These doctests have a `# // FIXME` comment above the line that removes the memory leak, with a note that once `-Zmiri-disable-leak-check` can be applied at test granularity, these tests should be "un-unleakified" and have `-Zmiri-disable-leak-check` enabled. - Some of these are possibly fragile (e.g. unleaking the result of `Vec::leak`) and thus should definitely not be made part of the documentation. This should be all of the leaks currently in `core` and `alloc`. I only found one leak in `std`, and it was in the first category (excluding the modules `@RalfJung` mentioned in https://github.com/rust-lang/rust/issues/126067 , and reducing the number of iterations of [one test](https://github.com/rust-lang/rust/blob/master/library/std/src/sync/once_lock.rs#L49-L94) from 1000 to 10) [^1]: assuming [^2] is not added [^2]: backlink
2024-07-10Clarify/add `must_use` messages for more `into_raw*` functions of `alloc` types.Zachary S-0/+2
2024-07-07Specialize `TrustedLen` for `Iterator::unzip()`Chayim Refael Friedman-0/+20
Don't check the capacity every time (and also for `Extend` for tuples, as this is how `unzip()` is implemented). I did this with an unsafe method on `Extend` that doesn't check for growth (`extend_one_unchecked()`). I've marked it as perma-unstable currently, although we may want to expose it in the future so collections outside of std can benefit from it. Then specialize `Extend for (A, B)` for `TrustedLen` to call it. It may seem that an alternative way of implementing this is to have a semi-public trait (`#[doc(hidden)]` public, so collections outside of core can implement it) for `extend()` inside tuples, and specialize it from collections. However, it is impossible due to limitations of `min_specialization`. A concern that may arise with the current approach is that implementing `extend_one_unchecked()` correctly must also incur implementing `extend_reserve()`, otherwise you can have UB. This is a somewhat non-local safety invariant. However, I believe this is fine, since to have actual UB you must have unsafe code inside your `extend_one_unchecked()` that makes incorrect assumption, *and* not implement `extend_reserve()`. I've also documented this requirement.
2024-07-06Mitigate focused memory leaks in `alloc` doctests for Miri.Zachary S-0/+6
If/when `-Zmiri-disable-leak-check` is able to be used at test-granularity, it should applied to these tests instead of unleaking.
2024-07-01Avoid MIR bloat in inliningScott McMurray-0/+1
In 126578 we ended up with more binary size increases than expected. This change attempts to avoid inlining large things into small things, to avoid that kind of increase, in cases when top-down inlining will still be able to do that inlining later.
2024-06-11replace version placeholderPietro Albini-1/+1
2024-06-06less garbage, more examplesRalf Jung-2/+2
2024-05-26Stabilize `slice_flatten`Cyborus-3/+1