summary refs log tree commit diff
path: root/library/alloc/src
AgeCommit message (Collapse)AuthorLines
2021-04-26fix double-drop in in-place collect specializationThe8472-11/+20
(cherry picked from commit 421f5d282a51e130d3ca7c4524d8ad6753437da9)
2021-04-26Update the commentYechan Bae-4/+4
(cherry picked from commit 26a62701e42d10c03ce5f2f911e7d5edeefa2f0f)
2021-04-26Fixes #80335Yechan Bae-18/+24
(cherry picked from commit 6d43225bfb08ec91f7476b76c7fec632c4a096ef)
2021-03-19Rollup merge of #83244 - cuviper:vec_deque-zst, r=m-ou-seDylan DPC-19/+33
Fix overflowing length in Vec<ZST> to VecDeque `Vec` can hold up to `usize::MAX` ZST items, but `VecDeque` has a lower limit to keep its raw capacity as a power of two, so we should check that in `From<Vec<T>> for VecDeque<T>`. We can also simplify the capacity check for the remaining non-ZST case. Before this fix, the new test would fail on the length: ``` thread 'collections::vec_deque::tests::test_from_vec_zst_overflow' panicked at 'assertion failed: `(left == right)` left: `0`, right: `9223372036854775808`', library/alloc/src/collections/vec_deque/tests.rs:474:5 note: panic did not contain expected string panic message: `"assertion failed: `(left == right)`\n left: `0`,\n right: `9223372036854775808`"`, expected substring: `"capacity overflow"` ``` That was a result of `len()` using a mask `& (size - 1)` with the improper length. Now we do get a "capacity overflow" panic as soon as that `VecDeque::from(vec)` is attempted. Fixes #80167.
2021-03-19Auto merge of #71780 - jcotton42:string_remove_matches, r=joshtriplettbors-0/+56
Implement String::remove_matches Closes #50206. I lifted the function help from `@frewsxcv's` original PR (#50015), hope they don't mind. I'm also wondering whether it would be useful for `remove_matches` to collect up the removed substrings into a `Vec` and return them, right now they're just overwritten by the copy and lost.
2021-03-18Auto merge of #81312 - dylni:clarify-btree-range-search-comments, r=m-ou-sebors-3/+2
Clarify BTree `range_search` comments These comments were added by #81169. However, the soundness issue [might not be exploitable here](https://github.com/rust-lang/rust/pull/81169#issuecomment-765271717), so the comments should be updated. cc `@ssomers`
2021-03-18Rollup merge of #82434 - jyn514:hash, r=JohnTitorDylan DPC-3/+4
Add more links between hash and btree collections - Link from `core::hash` to `HashMap` and `HashSet` - Link from HashMap and HashSet to the module-level documentation on when to use the collection - Link from several collections to Wikipedia articles on the general concept See also https://github.com/rust-lang/rust/pull/81989#issuecomment-783920840.
2021-03-18Rollup merge of #82191 - Soveu:dedup, r=nagisaDylan DPC-6/+89
Vec::dedup_by optimization Now `Vec::dedup_by` drops items in-place as it goes through them. From my benchmarks, it is around 10% faster when T is small, with no major regression when otherwise. I used `ptr::copy` instead of conditional `ptr::copy_nonoverlapping`, because the latter had some weird performance issues on my ryzen laptop (it was 50% slower on it than on intel/sandybridge laptop) It would be good if someone was able to reproduce these results.
2021-03-17Fix overflowing length in Vec<ZST> to VecDequeJosh Stone-19/+33
`Vec` can hold up to `usize::MAX` ZST items, but `VecDeque` has a lower limit to keep its raw capacity as a power of two, so we should check that in `From<Vec<T>> for VecDeque<T>`. We can also simplify the capacity check for the remaining non-ZST case. Before this fix, the new test would fail on the length: ``` thread 'collections::vec_deque::tests::test_from_vec_zst_overflow' panicked at 'assertion failed: `(left == right)` left: `0`, right: `9223372036854775808`', library/alloc/src/collections/vec_deque/tests.rs:474:5 note: panic did not contain expected string panic message: `"assertion failed: `(left == right)`\n left: `0`,\n right: `9223372036854775808`"`, expected substring: `"capacity overflow"` ``` That was a result of `len()` using a mask `& (size - 1)` with the improper length. Now we do get a "capacity overflow" panic as soon as that `VecDeque::from(vec)` is attempted.
2021-03-16Fix comments based on reviewdylni-5/+2
2021-03-16Rollup merge of #83072 - henryboisdequin:patch-1, r=Dylan-DPCYuki Okushi-3/+3
Update `Vec` docs Fix typos/nits in `Vec` docs
2021-03-15Merge branch 'master' into dedupSoveu-727/+1153
2021-03-15Vec::dedup optimization - finishing polishesSoveu-11/+7
2021-03-15Replace `type_alias_impl_trait` by `min_type_alias_impl_trait` with no ↵Oli Scherer-1/+2
actual changes in behaviour This makes `type_alias_impl_trait` not actually do anything anymore
2021-03-15Clarify BTree range searching commentsdylni-1/+3
2021-03-13Auto merge of #82760 - WaffleLapkin:unleak_extend_from_within, r=kennytmbors-15/+28
Fix leak in Vec::extend_from_within Fixes #82533
2021-03-13Update `Vec` docsHenry Boisdequin-3/+3
2021-03-12Rollup merge of #82950 - mockersf:slice-intra-doc-link, r=jyn514Yuki Okushi-5/+5
convert slice doc link to intra-doc links Continuing where #80189 stopped, with `core::slice`. I had an issue with two dead links in my doc when implementing `Deref<Target = [T]>` for one of my type. This means that [`binary_search_by_key`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.binary_search_by_key) was available, but not [`sort_by_key`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.sort_by_key) even though it was linked in it's doc (same issue with [`as_ptr`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.as_ptr) and [`as_mut_pbr`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.as_mut_ptr)). It becomes available if I implement `DerefMut`, as it needs an `&mut self`. <details> <summary>Code that will have dead links in its doc</summary> ```rust pub struct A; pub struct B; impl std::ops::Deref for B{ type Target = [A]; fn deref(&self) -> &Self::Target { &A } } ``` </details> I removed the link to `sort_by_key` from `binary_search_by_key` doc as I didn't find a nice way to have a live link: - `binary_search_by_key` is in `core` - `sort_by_key` is in `alloc` - intra-doc link `slice::sort_by_key` doesn't work, as `alloc` is not available when `core` is being build (the warning can't be ignored: ```error[E0710]: an unknown tool name found in scoped lint: `rustdoc::broken_intra_doc_links` ```) - keeping the link as an anchor `#method.sort_by_key` meant a dead link - an absolute link would work but doesn't feel right...
2021-03-10Rollup merge of #79208 - LeSeulArtichaut:stable-unsafe_op_in_unsafe_fn, ↵Yuki Okushi-1/+1
r=nikomatsakis Stabilize `unsafe_op_in_unsafe_fn` lint This makes it possible to override the level of the `unsafe_op_in_unsafe_fn`, as proposed in https://github.com/rust-lang/rust/issues/71668#issuecomment-729770896. Tracking issue: #71668 r? ```@nikomatsakis``` cc ```@SimonSapin``` ```@RalfJung``` # Stabilization report This is a stabilization report for `#![feature(unsafe_block_in_unsafe_fn)]`. ## Summary Currently, the body of unsafe functions is an unsafe block, i.e. you can perform unsafe operations inside. The `unsafe_op_in_unsafe_fn` lint, stabilized here, can be used to change this behavior, so performing unsafe operations in unsafe functions requires an unsafe block. For now, the lint is allow-by-default, which means that this PR does not change anything without overriding the lint level. For more information, see [RFC 2585](https://github.com/rust-lang/rfcs/blob/master/text/2585-unsafe-block-in-unsafe-fn.md) ### Example ```rust // An `unsafe fn` for demonstration purposes. // Calling this is an unsafe operation. unsafe fn unsf() {} // #[allow(unsafe_op_in_unsafe_fn)] by default, // the behavior of `unsafe fn` is unchanged unsafe fn allowed() { // Here, no `unsafe` block is needed to // perform unsafe operations... unsf(); // ...and any `unsafe` block is considered // unused and is warned on by the compiler. unsafe { unsf(); } } #[warn(unsafe_op_in_unsafe_fn)] unsafe fn warned() { // Removing this `unsafe` block will // cause the compiler to emit a warning. // (Also, no "unused unsafe" warning will be emitted here.) unsafe { unsf(); } } #[deny(unsafe_op_in_unsafe_fn)] unsafe fn denied() { // Removing this `unsafe` block will // cause a compilation error. // (Also, no "unused unsafe" warning will be emitted here.) unsafe { unsf(); } } ```
2021-03-09convert slice doc link to intra-doc linksFrançois Mockers-5/+5
2021-03-09Rollup merge of #81127 - hanmertens:binary_heap_sift_down_perf, r=dtolnayMara Bos-2/+2
Improve sift_down performance in BinaryHeap Replacing `child < end - 1` with `child <= end.saturating_sub(2)` in `BinaryHeap::sift_down_range` (surprisingly) results in a significant speedup of `BinaryHeap::into_sorted_vec`. The same substitution can be done for `BinaryHeap::sift_down_to_bottom`, which causes a slight but probably statistically insignificant speedup for `BinaryHeap::pop`. It's interesting that benchmarks aside from `bench_into_sorted_vec` are barely affected, even those that do use `sift_down_*` methods internally. | Benchmark | Before (ns/iter) | After (ns/iter) | Speedup | |--------------------------|------------------|-----------------|---------| | bench_find_smallest_1000<sup>1</sup> | 392,617 | 385,200 | 1.02 | | bench_from_vec<sup>1</sup> | 506,016 | 504,444 | 1.00 | | bench_into_sorted_vec<sup>1</sup> | 476,869 | 384,458 | 1.24 | | bench_peek_mut_deref_mut<sup>3</sup> | 518,753 | 519,792 | 1.00 | | bench_pop<sup>2</sup> | 446,718 | 444,409 | 1.01 | | bench_push<sup>3</sup> | 772,481 | 770,208 | 1.00 | <sup>1</sup>: internally calls `sift_down_range` <sup>2</sup>: internally calls `sift_down_to_bottom` <sup>3</sup>: should not be affected
2021-03-07Add documentation for string->Cow conversionsMichael Howell-0/+33
Mostly, it's just to reassure everyone that these functions don't allocate. Part of #51430
2021-03-05Implement String::remove_matchesJosh Cotton-0/+56
2021-03-05Rollup merge of #82764 - m-ou-se:map-try-insert, r=AmanieuMara-1/+70
Add {BTreeMap,HashMap}::try_insert `{BTreeMap,HashMap}::insert(key, new_val)` returns `Some(old_val)` if the key was already in the map. It's often useful to assert no duplicate values are inserted. We experimented with `map.insert(key, val).unwrap_none()` (https://github.com/rust-lang/rust/issues/62633), but decided that that's not the kind of method we'd like to have on `Option`s. `insert` always succeeds because it replaces the old value if it exists. One could argue that `insert()` is never the right method for panicking on duplicates, since already handles that case by replacing the value, only allowing you to panic after that already happened. This PR adds a `try_insert` method that instead returns a `Result::Err` when the key already exists. This error contains both the `OccupiedEntry` and the value that was supposed to be inserted. This means that unwrapping that result gives more context: ```rust map.insert(10, "world").unwrap_none(); // thread 'main' panicked at 'called `Option::unwrap_none()` on a `Some` value: "hello"', src/main.rs:8:29 ``` ```rust map.try_insert(10, "world").unwrap(); // thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: // OccupiedError { key: 10, old_value: "hello", new_value: "world" }', src/main.rs:6:33 ``` It also allows handling the failure in any other way, as you have full access to the `OccupiedEntry` and the value. `try_insert` returns a reference to the value in case of success, making it an alternative to `.entry(key).or_insert(value)`. r? ```@Amanieu``` Fixes https://github.com/rust-lang/rfcs/issues/3092
2021-03-05Rollup merge of #80723 - rylev:noop-lint-pass, r=estebankMara-4/+4
Implement NOOP_METHOD_CALL lint Implements the beginnings of https://github.com/rust-lang/lang-team/issues/67 - a lint for detecting noop method calls (e.g, calling `<&T as Clone>::clone()` when `T: !Clone`). This PR does not fully realize the vision and has a few limitations that need to be addressed either before merging or in subsequent PRs: * [ ] No UFCS support * [ ] The warning message is pretty plain * [ ] Doesn't work for `ToOwned` The implementation uses [`Instance::resolve`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/instance/struct.Instance.html#method.resolve) which is normally later in the compiler. It seems that there are some invariants that this function relies on that we try our best to respect. For instance, it expects substitutions to have happened, which haven't yet performed, but we check first for `needs_subst` to ensure we're dealing with a monomorphic type. Thank you to ```@davidtwco,``` ```@Aaron1011,``` and ```@wesleywiser``` for helping me at various points through out this PR ❤️.
2021-03-04Add tracking issue for map_try_insert.Mara Bos-4/+4
2021-03-04Implement Error for OccupiedError.Mara Bos-0/+13
2021-03-04Improve Debug implementations of OccupiedError.Mara Bos-2/+3
2021-03-04Add BTreeMap::try_insert and btree_map::OccupiedError.Mara Bos-1/+56
2021-03-04Add regression test for `Vec::extend_from_within` leakWaffle-3/+5
2021-03-04Fix leak in Vec::extend_from_withinWaffle-16/+27
Previously vec's len was updated only after full copy, making the method leak if T::clone panic!s. This commit makes `Vec::extend_from_within` (or, more accurately, it's `T: Clone` specialization) update vec's len on every iteration, fixing the issue. `T: Copy` specialization was not affected by the issue b/c it doesn't call user specified code (as, e.g. `T::clone`), and instead calls `ptr::copy_nonoverlapping`.
2021-03-04Rollup merge of #82564 - WaffleLapkin:revert_spare_mut, r=RalfJungYuki Okushi-10/+14
Revert `Vec::spare_capacity_mut` impl to prevent pointers invalidation The implementation was changed in #79015. Later it was [pointed out](https://github.com/rust-lang/rust/issues/81944#issuecomment-782849785) that the implementation invalidates pointers to the buffer (initialized elements) by creating a unique reference to the buffer. This PR reverts the implementation. r? ```@RalfJung```
2021-03-03Update library/alloc/src/vec/mod.rsWaffle Lapkin-1/+1
Co-authored-by: Ralf Jung <post@ralfj.de>
2021-03-03Fix ui-full-deps suiteRyan Levick-4/+4
2021-03-03Rollup merge of #82439 - ssomers:btree_fix_unsafety, r=Mark-SimulacrumYuki Okushi-16/+15
BTree: fix untrue safety Fix needless and missing `unsafe` tags. r? ````@Mark-Simulacrum````
2021-03-03Make Vec::split_at_spare_mut impl safer & simplierWaffle-9/+5
2021-03-02Auto merge of #82043 - tmiasko:may-have-side-effect, r=kennytmbors-3/+1
Turn may_have_side_effect into an associated constant The `may_have_side_effect` is an implementation detail of `TrustedRandomAccess` trait. It describes if obtaining an iterator element may have side effects. It is currently implemented as an associated function. Turn `may_have_side_effect` into an associated constant. This makes the value immediately available to the optimizer.
2021-03-02Rollup merge of #80189 - jyn514:convert-primitives, r=poliorceticsYuki Okushi-17/+20
Convert primitives in the standard library to intra-doc links Blocked on https://github.com/rust-lang/rust/pull/80181. I forgot that this needs to wait for the beta bump so the standard library can be documented with `doc --stage 0`. Notably I didn't convert `core::slice` because it's like 50 links and I got scared :fearful:
2021-03-01Rollup merge of #82578 - camsteffen:diag-items, r=oli-obkJoshua Nelson-0/+4
Add some diagnostic items for Clippy
2021-03-01Rollup merge of #81210 - ssomers:btree_fix_node_size_test, r=Mark-SimulacrumJoshua Nelson-5/+6
BTreeMap: correct node size test case for choices of B r? `@Mark-Simulacrum`
2021-03-01Add diagnostic itemsCameron Steffen-0/+4
2021-03-01Auto merge of #82440 - ssomers:btree_fix_casts, r=Mark-Simulacrumbors-8/+10
BTree: no longer define impossible casts Casts to leaf to internal only make sense when the original has a chance of being the thing it's cast to. r? `@Mark-Simulacrum`
2021-03-01Auto merge of #81094 - ssomers:btree_drainy_refactor_3, r=Mark-Simulacrumbors-118/+228
BTreeMap: split up range_search into two stages `range_search` expects the caller to pass the same root twice and starts searching a node for both bounds of a range. It's not very clear that in the early iterations, it searches twice in the same node. This PR splits that search up in an initial `find_leaf_edges_spanning_range` that postpones aliasing until the last second, and a second phase for continuing the search for the range in the each subtree independently (`find_lower_bound_edge` & `find_upper_bound_edge`), which greatly helps for use in #81075. It also moves those functions over to the search module. r? `@Mark-Simulacrum`
2021-02-27Revert `Vec::spare_capacity_mut` impl to prevent pointers invalidationWaffle-1/+9
2021-02-25Convert primitives to use intra-doc linksJoshua Nelson-17/+20
2021-02-24library: Normalize safety-for-unsafe-block commentsMiguel Ojeda-10/+11
Almost all safety comments are of the form `// SAFETY:`, so normalize the rest and fix a few of them that should have been a `/// # Safety` section instead. Furthermore, make `tidy` only allow the uppercase form. While currently `tidy` only checks `core`, it is a good idea to prevent `core` from drifting to non-uppercase comments, so that later we can start checking `alloc` etc. too. Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2021-02-23Rollup merge of #82113 - m-ou-se:panic-format-lint, r=estebankDylan DPC-0/+1
Improve non_fmt_panic lint. This change: - fixes the span used by this lint in the case the panic argument is a single macro expansion (e.g. `panic!(a!())`); - adds a suggestion for `panic!(format!(..))` to remove `format!()` instead of adding `"{}", ` or using `panic_any` like it does now; and - fixes the incorrect suggestion to replace `panic![123]` by `panic_any(123]`. Fixes #82109. Fixes #82110. Fixes #82111. Example output: ``` warning: panic message is not a string literal --> src/main.rs:8:12 | 8 | panic!(format!("error: {}", "oh no")); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(non_fmt_panic)]` on by default = note: this is no longer accepted in Rust 2021 = note: the panic!() macro supports formatting, so there's no need for the format!() macro here help: remove the `format!(..)` macro call | 8 | panic!("error: {}", "oh no"); | -- -- ``` r? `@estebank`
2021-02-23BTree: fix untrue safetyStein Somers-16/+15
2021-02-23BTree: no longer define impossible castsStein Somers-8/+10
2021-02-23BTree: split off reusable components from range_searchStein Somers-118/+228