about summary refs log tree commit diff
path: root/library/alloc/src/vec
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.
2025-01-10alloc: remove unsound `IsZero` for raw pointersjoboet-13/+2
Fixes #135338
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-16remove obsolete comment and pub(super) visibilityThe 8472-12/+6
2024-12-16remove bounds from vec and linkedlist ExtractIfThe 8472-12/+5
since drain-on-drop behavior was removed those bounds no longer serve a purpose
2024-12-16Add a range argument to vec.extract_ifThe 8472-20/+46
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-25library: consistently use American spelling for 'behavior'Ralf Jung-1/+1
2024-10-14Auto merge of #126557 - GrigorenkoPV:vec_track_caller, r=joboetbors-0/+57
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-25Use `&raw` in the standard libraryJosh Stone-2/+2
Since the stabilization in #127679 has reached stage0, 1.82-beta, we can start using `&raw` freely, and even the soft-deprecated `ptr::addr_of!` and `ptr::addr_of_mut!` can stop allowing the unstable feature. I intentionally did not change any documentation or tests, but the rest of those macro uses are all now using `&raw const` or `&raw mut` in the standard library.
2024-09-22Reformat using the new identifier sorting from rustfmtMichael Goulet-2/+2
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/+57
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-16/+308
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-12Rollup merge of #130101 - RalfJung:const-cleanup, r=fee1-deadMatthias Krüger-3/+3
some const cleanup: remove unnecessary attributes, add const-hack indications I learned that we use `FIXME(const-hack)` on top of the "const-hack" label. That seems much better since it marks the right place in the code and moves around with the code. So I went through the PRs with that label and added appropriate FIXMEs in the code. IMO this means we can then remove the label -- Cc ``@rust-lang/wg-const-eval.`` I also noticed some const stability attributes that don't do anything useful, and removed them. r? ``@fee1-dead``
2024-09-08add FIXME(const-hack)Ralf Jung-3/+3
2024-09-08Remove needless returns detected by clippy in librariesEduardo Sánchez Muñoz-3/+3
2024-09-07Add `NonNull` convenience methods to `Vec`Tim (Theemathas) Chirananthavat-16/+308
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-32/+23
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-14/+17
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-14/+17
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