about summary refs log tree commit diff
path: root/library/alloc/src/vec/mod.rs
AgeCommit message (Collapse)AuthorLines
2022-10-17Allow `Vec::leak` with `no_global_oom_handling`Chris Denton-1/+0
2022-10-09Auto merge of #89123 - the8472:push_in_capacity, r=amanieubors-0/+45
add Vec::push_within_capacity - fallible, does not allocate This method can serve several purposes. It * is fallible * guarantees that items in Vec aren't moved * allows loops that do `reserve` and `push` separately to avoid pulling in the allocation machinery a second time in the `push` part which should make things easier on the optimizer * eases the path towards `ArrayVec` a bit since - compared to `push()` - there are fewer questions around how it should be implemented I haven't named it `try_push` because that should probably occupy a middle ground that will still try to reserve and only return an error in the unlikely OOM case. resolves #84649
2022-10-04Rollup merge of #101642 - SkiFire13:fix-inplace-collection-leak, r=the8472Dylan DPC-1/+1
Fix in-place collection leak when remaining element destructor panic Fixes #101628 cc `@the8472` I went for the drop guard route, placing it immediately before the `forget_allocation_drop_remaining` call and after the comment, as to signal they are closely related. I also updated the test to check for the leak, though the only change really needed was removing the leak clean up for miri since now that's no longer leaked.
2022-10-03Rollup merge of #99216 - duarten:master, r=joshtriplettMatthias Krüger-8/+73
docs: be less harsh in wording for Vec::from_raw_parts In particular, be clear that it is sound to specify memory not originating from a previous `Vec` allocation. That is already suggested in other parts of the documentation about zero-alloc conversions to Box<[T]>. Incorporate a constraint from `slice::from_raw_parts` that was missing but needs to be fulfilled, since a `Vec` can be converted into a slice. Fixes https://github.com/rust-lang/rust/issues/98780.
2022-09-22Make ZST checks in core/alloc more readableScott McMurray-3/+3
There's a bunch of these checks because of special handing for ZSTs in various unsafe implementations of stuff. This lets them be `T::IS_ZST` instead of `mem::size_of::<T>() == 0` every time, making them both more readable and more terse. *Not* proposed for stabilization at this time. Would be `pub(crate)` except `alloc` wants to use it too. (And while it doesn't matter now, if we ever get something like 85836 making it a const can help codegen be simpler.)
2022-09-10Fix leaking in inplace collection when destructor panicsGiacomo Stevanato-1/+1
2022-08-31Fix a bunch of typoDezhi Wu-2/+2
This PR will fix some typos detected by [typos]. I only picked the ones I was sure were spelling errors to fix, mostly in the comments. [typos]: https://github.com/crate-ci/typos
2022-08-23Make use of `[wrapping_]byte_{add,sub}`Maybe Waffle-2/+2
...replacing `.cast().wrapping_offset().cast()` & similar code.
2022-08-22Rollup merge of #100872 - JanBeh:PR_vec_default_alloc_doc, r=fee1-deadDylan DPC-0/+2
Add guarantee that Vec::default() does not alloc Currently `Vec::new()` is guaranteed to not allocate until elements are pushed onto the `Vec`, but such a guarantee is missing for `Vec`'s implementation of `Default::default`. This adds such a guarantee for `Vec::default()` to the API reference. See also [this discussion on URLO](https://users.rust-lang.org/t/guarantee-that-vec-default-does-not-allocate/79903).
2022-08-22Rollup merge of #100331 - lo48576:try-reserve-preserve-on-failure, r=thomccDylan DPC-1/+2
Guarantee `try_reserve` preserves the contents on error Update doc comments to make the guarantee explicit. However, some implementations does not have the statement though. * `HashMap`, `HashSet`: require guarantees on hashbrown side. * `PathBuf`: simply redirecting to `OsString`. Fixes #99606.
2022-08-22Add guarantee that Vec::default() does not allocJan Behrens-0/+2
Currently `Vec::new()` is guaranteed to not allocate until elements are pushed onto the `Vec`, but such a guarantee is missing for `Vec`'s implementation of `Default::default`. This adds such a guarantee for `Vec::default()` to the API reference.
2022-08-21Rollup merge of #100822 - WaffleLapkin:no_offset_question_mark, r=scottmcmMatthias Krüger-3/+3
Replace most uses of `pointer::offset` with `add` and `sub` As PR title says, it replaces `pointer::offset` in compiler and standard library with `pointer::add` and `pointer::sub`. This generally makes code cleaner, easier to grasp and removes (or, well, hides) integer casts. This is generally trivially correct, `.offset(-constant)` is just `.sub(constant)`, `.offset(usized as isize)` is just `.add(usized)`, etc. However in some cases we need to be careful with signs of things. r? ````@scottmcm```` _split off from #100746_
2022-08-21Make some docs nicer wrt pointer offsetsMaybe Waffle-4/+4
2022-08-21Replace most uses of `pointer::offset` with `add` and `sub`Maybe Waffle-3/+3
2022-08-13address review comments, add tracking issueThe 8472-7/+8
2022-08-13add Vec::push_within_capacity - fallible, does not allocateThe8472-0/+44
2022-08-10Guarantee `try_reserve` preserves the contents on errorYOSHIOKA Takuma-1/+2
Update doc comments to make the guarantee explicit. However, some implementations does not have the statement though. * `HashMap`, `HashSet`: require guarantees on hashbrown side. * `PathBuf`: simply redirecting to `OsString`. Fixes #99606.
2022-07-14add code examplesDuarte Nunes-1/+50
2022-07-13rustdocDuarte Nunes-1/+1
2022-07-13typoDuarte Nunes-2/+2
2022-07-13changes to wordingDuarte Nunes-9/+15
2022-07-13docs: be less harsh in wording for Vec::from_raw_partsDuarte Nunes-5/+15
In particular, be clear that it is sound to specify memory not originating from a previous `Vec` allocation. That is already suggested in other parts of the documentation about zero-alloc conversions to Box<[T]>. Incorporate a constraint from `slice::from_raw_parts` that was missing but needs to be fulfilled, since a `Vec` can be converted into a slice.
2022-07-03Auto merge of #98755 - nnethercote:faster-vec-insert, r=cuviperbors-6/+9
Optimize `Vec::insert` for the case where `index == len`. By skipping the call to `copy` with a zero length. This makes it closer to `push`. I did this recently for `SmallVec` (https://github.com/servo/rust-smallvec/pull/282) and it was a big perf win in one case. Although I don't have a specific use case in mind, it seems worth doing it for `Vec` as well. Things to note: - In the `index < len` case, the number of conditions checked is unchanged. - In the `index == len` case, the number of conditions checked increases by one, but the more expensive zero-length copy is avoided. - In the `index > len` case the code now reserves space for the extra element before panicking. This seems like an unimportant change. r? `@cuviper`
2022-07-01update cfg(bootstrap)sPietro Albini-1/+1
2022-07-01Optimize `Vec::insert` for the case where `index == len`.Nicholas Nethercote-6/+9
By skipping the call to `copy` with a zero length. This makes it closer to `push`. I did this recently for `SmallVec` (https://github.com/servo/rust-smallvec/pull/282) and it was a big perf win in one case. Although I don't have a specific use case in mind, it seems worth doing it for `Vec` as well. Things to note: - In the `index < len` case, the number of conditions checked is unchanged. - In the `index == len` case, the number of conditions checked increases by one, but the more expensive zero-length copy is avoided. - In the `index > len` case the code now reserves space for the extra element before panicking. This seems like an unimportant change.
2022-06-19Fix documentation for with_capacity and reserve families of methodsjmaargh-28/+57
Documentation for the following methods with_capacity with_capacity_in with_capacity_and_hasher reserve reserve_exact try_reserve try_reserve_exact was inconsistent and often not entirely correct where they existed on the following types Vec VecDeque String OsString PathBuf BinaryHeap HashSet HashMap BufWriter LineWriter since the allocator is allowed to allocate more than the requested capacity in all such cases, and will frequently "allocate" much more in the case of zero-sized types (I also checked BufReader, but there the docs appear to be accurate as it appears to actually allocate the exact capacity). Some effort was made to make the documentation more consistent between types as well. Fix with_capacity* methods for Vec Fix *reserve* methods for Vec Fix docs for *reserve* methods of VecDeque Fix docs for String::with_capacity Fix docs for *reserve* methods of String Fix docs for OsString::with_capacity Fix docs for *reserve* methods on OsString Fix docs for with_capacity* methods on HashSet Fix docs for *reserve methods of HashSet Fix docs for with_capacity* methods of HashMap Fix docs for *reserve methods on HashMap Fix expect messages about OOM in doctests Fix docs for BinaryHeap::with_capacity Fix docs for *reserve* methods of BinaryHeap Fix typos Fix docs for with_capacity on BufWriter and LineWriter Fix consistent use of `hasher` between `HashMap` and `HashSet` Fix warning in doc test Add test for capacity of vec with ZST Fix doc test error
2022-06-02Auto merge of #97293 - est31:remove_box, r=oli-obkbors-2/+5
Add #[rustc_box] and use it inside alloc This commit adds an alternative content boxing syntax, and uses it inside alloc. ```Rust #![feature(box_syntax)] fn foo() { let foo = box bar; } ``` is equivalent to ```Rust #![feature(rustc_attrs)] fn foo() { let foo = #[rustc_box] Box::new(bar); } ``` The usage inside the very performance relevant code in liballoc is the only remaining relevant usage of box syntax in the compiler (outside of tests, which are comparatively easy to port). box syntax was originally designed to be used by all Rust developers. This introduces a replacement syntax more tailored to only being used inside the Rust compiler, and with it, lays the groundwork for eventually removing box syntax. [Earlier work](https://github.com/rust-lang/rust/pull/87781#issuecomment-894714878) by `@nbdd0121` to lower `Box::new` to `box` during THIR -> MIR building ran into borrow checker problems, requiring the lowering to be adjusted in a way that led to [performance regressions](https://github.com/rust-lang/rust/pull/87781#issuecomment-894872367). The proposed change in this PR lowers `#[rustc_box] Box::new` -> `box` in the AST -> HIR lowering step, which is way earlier in the compiler, and thus should cause less issues both performance wise as well as regarding type inference/borrow checking/etc. Hopefully, future work can move the lowering further back in the compiler, as long as there are no performance regressions.
2022-06-01Auto merge of #97553 - nbdd0121:lib, r=Mark-Simulacrumbors-0/+2
Add `#[inline]` to `Vec`'s `Deref/DerefMut` This should help #97552 (although I haven't verified).
2022-06-01Use #[rustc_box] in alloc instead of box syntaxest31-2/+5
2022-05-31Rollup merge of #97578 - ojeda:checkpatch, r=JohnTitorMatthias Krüger-1/+1
alloc: remove repeated word in comment Linux's `checkpatch.pl` reports: ```txt #42544: FILE: rust/alloc/vec/mod.rs:2692: WARNING: Possible repeated word: 'to' + // - Elements are :Copy so it's OK to to copy them, without doing ``` Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-05-31Auto merge of #97521 - SkiFire13:clarify-vec-as-ptr, r=Dylan-DPCbors-2/+4
Clarify the guarantees of Vec::as_ptr and Vec::as_mut_ptr when there's no allocation Currently the documentation says they return a pointer to the vector's buffer, which has the implied precondition that the vector allocated some memory. However `Vec`'s documentation also specifies that it won't always allocate, so it's unclear whether the pointer returned is valid in that case. Of course you won't be able to read/write actual bytes to/from it since the capacity is 0, but there's an exception: zero sized read/writes. They are still valid as long as the pointer is not null and the memory it points to wasn't deallocated, but `Vec::as_ptr` and `Vec::as_mut_ptr` don't specify that's not the case. This PR thus specifies they are actually valid for zero sized reads since `Vec` is implemented to hold a dangling pointer in those cases, which is neither null nor was deallocated.
2022-05-31alloc: remove repeated word in commentMiguel Ojeda-1/+1
Linux's `checkpatch.pl` reports: ```txt #42544: FILE: rust/alloc/vec/mod.rs:2692: WARNING: Possible repeated word: 'to' + // - Elements are :Copy so it's OK to to copy them, without doing ``` Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-05-30Add `#[inline]` to `Vec`'s `Deref/DerefMut`Gary Guo-0/+2
2022-05-29Clarify the guarantees of Vec::as_ptr and Vec::as_mut_ptr when there's no ↵Giacomo Stevanato-2/+4
allocation
2022-05-28Rollup merge of #95214 - tbu-:pr_vec_append_doc, r=Mark-SimulacrumMatthias Krüger-1/+1
Remove impossible panic note from `Vec::append` Neither the number of elements in a vector can overflow a `usize`, nor can the amount of elements in two vectors.
2022-05-23Rollup merge of #97087 - Nilstrieb:clarify-slice-iteration-order, r=dtolnayDylan DPC-4/+7
Clarify slice and Vec iteration order While already being inferable from the doc examples, it wasn't fully specified. This is the only logical way to do a slice iterator, so I think this should be uncontroversial. It also improves the `Vec::into_iter` example to better show the order and that the iterator returns owned values.
2022-05-19Reverse condition in Vec::retain_mut doctestajtribick-3/+3
2022-05-16Clarify slice and Vec iteration orderNilstrieb-4/+7
While already being inferable from the doc examples, it wasn't fully specified. This is the only logical way to do a slice iterator.
2022-05-02Rollup merge of #96222 - jmaargh:john-mark/clarify-from-raw-parts-docs, ↵Yuki Okushi-2/+4
r=JohnTitor Clarify docs for `from_raw_parts` on `Vec` and `String` Closes #95427 Original safety explanation for `from_raw_parts` was unclear on safety for consuming a C string. This clarifies when doing so is safe.
2022-04-27Revert "impl From<&[T; N]> and From<&mut [T; N]> for Vec<T>"Jake Goulding-42/+0
This reverts commit 5dd702763ae0e112332a4447171adbed51aeee3d.
2022-04-19Clarify docs for from_raw_partsjmaargh-2/+4
Original safety explanation for from_raw_parts was unclear on safety for consuming a C string. This clarifies when doing so is safe.
2022-04-13Speed up Vec::clear().Nicholas Nethercote-1/+12
Currently it just calls `truncate(0)`. `truncate()` is (a) not marked as `#[inline]`, and (b) more general than needed for `clear()`. This commit changes `clear()` to do the work itself. This modest change was first proposed in rust-lang#74172, where the reviewer rejected it because there was insufficient evidence that `Vec::clear()`'s performance mattered enough to justify the change. Recent changes within rustc have made `Vec::clear()` hot within `macro_parser.rs`, so the change is now clearly worthwhile. Although it doesn't show wins on CI perf runs, this seems to be because they use PGO. But not all platforms currently use PGO. Also, local builds don't use PGO, and `truncate` sometimes shows up in an over-represented fashion in local profiles. So local profiling will be made easier by this change. Note that this will also benefit `String::clear()`, because it just calls `Vec::clear()`. Finally, the commit removes the `vec-clear.rs` codegen test. It was added in #52908. From before then until now, `Vec::clear()` just called `Vec::truncate()` with a zero length. The body of Vec::truncate() has changed a lot since then. Now that `Vec::clear()` is doing actual work itself, and not just calling `Vec::truncate()`, it's not surprising that its generated code includes a load and an icmp. I think it's reasonable to remove this test.
2022-04-08add `<[[T; N]]>::flatten`, `<[[T; N]]>::flatten_mut`, and `Vec::<[T; ↵Cyborus04-0/+45
N]>::into_flattened`
2022-03-31Rollup merge of #95491 - faern:stabilize-vec_retain_mut, r=yaahcDylan DPC-3/+1
Stabilize feature vec_retain_mut on Vec and VecDeque Closes #90829
2022-03-31Rollup merge of #95298 - ↵Dylan DPC-1/+1
jhorstmann:fix-double-drop-of-allocator-in-vec-into-iter, r=oli-obk Fix double drop of allocator in IntoIter impl of Vec Fixes #95269 The `drop` impl of `IntoIter` reconstructs a `RawVec` from `buf`, `cap` and `alloc`, when that `RawVec` is dropped it also drops the allocator. To avoid dropping the allocator twice we wrap it in `ManuallyDrop` in the `InttoIter` struct. Note this is my first contribution to the standard library, so I might be missing some details or a better way to solve this.
2022-03-30Stabilize feature vec_retain_mut on Vec and VecDequeLinus Färnstrand-3/+1
2022-03-28Rollup merge of #95098 - shepmaster:vec-from-array-ref, r=dtolnayDylan DPC-0/+42
impl From<&[T; N]> and From<&mut [T; N]> for Vec<T> I really wanted to write: ```rust fn example(a: impl Into<Vec<u8>>) {} fn main() { example(b"raw"); } ```
2022-03-28Rollup merge of #95016 - janpaul123:patch-1, r=dtolnayDylan DPC-3/+7
Docs: make Vec::from_raw_parts documentation less strict This is my first PR; be gentle! In https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/2?u=janpaul123 it was suggested to me that I should make a PR to make the documentation of `Vec::from_raw_parts` less strict, since we don't require `T` to have the same size, just `size_of::<T>() * capacity` to be the same, since that is what results in `Layout::size` being the same in `dealloc`, which is really what matters. Also in https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/8?u=janpaul123 it was suggested that it's better to use `slice::from_raw_parts`, which I think is useful advise that could also be mentioned in the docs, so I added that too. Let me know what you think! :)
2022-03-25Fix double drop of allocator in IntoIter impl of VecJörn Horstmann-1/+1
2022-03-22Remove impossible panic note from `Vec::append`Tobias Bucher-1/+1
Neither the number of elements in a vector can overflow a `usize`, nor can the amount of elements in two vectors.