about summary refs log tree commit diff
path: root/library/alloc/src/collections
AgeCommit message (Collapse)AuthorLines
2021-06-02Replace IntoIter::new with IntoIterator::into_iter in stdMuhammad Mominul Huque-2/+1
2021-05-30Improve Debug impls for LinkedList reference iterators to show itemsFrank Steffahn-2/+18
2021-05-29Fix unsoundness of Debug implementation for linked_list::IterMutFrank Steffahn-6/+3
2021-05-21Remove surplus prepend LinkedList fnJubilee Young-21/+0
Originally committed to Rust in 2013, it is identical to append with a reversed order of arguments.
2021-05-18Auto merge of #84767 - scottmcm:try_trait_actual, r=lcnrbors-2/+2
Implement the new desugaring from `try_trait_v2` ~~Currently blocked on https://github.com/rust-lang/rust/issues/84782, which has a PR in https://github.com/rust-lang/rust/pull/84811~~ Rebased atop that fix. `try_trait_v2` tracking issue: https://github.com/rust-lang/rust/issues/84277 Unfortunately this is already touching a ton of things, so if you have suggestions for good ways to split it up, I'd be happy to hear them. (The combination between the use in the library, the compiler changes, the corresponding diagnostic differences, even MIR tests mean that I don't really have a great plan for it other than trying to have decently-readable commits. r? `@ghost` ~~(This probably shouldn't go in during the last week before the fork anyway.)~~ Fork happened.
2021-05-16mark internal inplace_iteration traits as hiddenThe8472-0/+2
2021-05-07BTree: no longer copy keys and values before dropping themStein Somers-45/+95
2021-05-06Perf Experiment: Wait, what if I just skip the trait aliasScott McMurray-3/+3
2021-05-06Bootstrapping preparation for the libraryScott McMurray-3/+3
Since just `ops::Try` will need to change meaning.
2021-05-06Rollup merge of #84328 - Folyd:stablize_map_into_keys_values, r=m-ou-seDylan DPC-16/+14
Stablize {HashMap,BTreeMap}::into_{keys,values} I would propose to stabilize `{HashMap,BTreeMap}::into_{keys,values}`( aka. `map_into_keys_values`). Closes #75294.
2021-05-05alloc: Add unstable Cfg feature `no-global_oom_handling`John Ericson-0/+11
For certain sorts of systems, programming, it's deemed essential that all allocation failures be explicitly handled where they occur. For example, see Linus Torvald's opinion in [1]. Merely not calling global panic handlers, or always `try_reserving` first (for vectors), is not deemed good enough, because the mere presence of the global OOM handlers is burdens static analysis. One option for these projects to use rust would just be to skip `alloc`, rolling their own allocation abstractions. But this would, in my opinion be a real shame. `alloc` has a few `try_*` methods already, and we could easily have more. Features like custom allocator support also demonstrate and existing to support diverse use-cases with the same abstractions. A natural way to add such a feature flag would a Cargo feature, but there are currently uncertainties around how std library crate's Cargo features may or not be stable, so to avoid any risk of stabilizing by mistake we are going with a more low-level "raw cfg" token, which cannot be interacted with via Cargo alone. Note also that since there is no notion of "default cfg tokens" outside of Cargo features, we have to invert the condition from `global_oom_handling` to to `not(no_global_oom_handling)`. This breaks the monotonicity that would be important for a Cargo feature (i.e. turning on more features should never break compatibility), but it doesn't matter for raw cfg tokens which are not intended to be "constraint solved" by Cargo or anything else. To support this use-case we create a new feature, "global-oom-handling", on by default, and put the global OOM handler infra and everything else it that depends on it behind it. By default, nothing is changed, but users concerned about global handling can make sure it is disabled, and be confident that all OOM handling is local and explicit. For this first iteration, non-flat collections are outright disabled. `Vec` and `String` don't yet have `try_*` allocation methods, but are kept anyways since they can be oom-safely created "from parts", and we hope to add those `try_` methods in the future. [1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
2021-05-05Bump map_into_keys_values stable version to 1.54.0.Mara Bos-14/+14
2021-04-28Minor grammar tweaks for readabilityBen-Lichtman-4/+4
2021-04-22Improve BinaryHeap::retain.Mara Bos-32/+53
It now doesn't fully rebuild the heap, but only the parts that are necessary.
2021-04-19Stablize {HashMap,BTreeMap}::into_{keys,values}Folyd-16/+14
2021-04-15VecDeque: Improve doc comments in binary search fnsVojtech Kral-5/+23
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
2021-04-15VecDeque: Add partition_point() #78021Vojtech Kral-0/+45
2021-04-15VecDeque: binary_search_by(): return right away if hit found at back.first() ↵Vojtech Kral-1/+4
#78021
2021-04-12Stabilize BTree{Map,Set}::retainJubilee Young-4/+2
2021-04-04Rollup merge of #82726 - ssomers:btree_node_rearange, r=Mark-SimulacrumDylan DPC-167/+165
BTree: move blocks around in node.rs Without changing any names or implementation, reorder some members: - Move down the ones defined long ago on the demised `struct Root`, to below the definition of their current host `struct NodeRef`. - Move up some defined on `struct NodeRef` that are interspersed with those defined on `struct Handle`. - Move up the `correct_…` methods squeezed between the two flavours of `push`. - Move the unchecked static downcasts (`cast_to_…`) after the upcasts (`forget_`) and the (weirdly named) dynamic downcasts (`force`). r? ````@Mark-Simulacrum````
2021-04-04Auto merge of #83267 - ssomers:btree_prune_range_search_overlap, ↵bors-27/+43
r=Mark-Simulacrum BTree: no longer search arrays twice to check Ord A possible addition to / partial replacement of #83147: no longer linearly search the upper bound of a range in the initial portion of the keys we already know are below the lower bound. - Should be faster: fewer key comparisons at the cost of some instructions dealing with offsets - Makes code a little more complicated. - No longer detects ill-defined `Ord` implementations, but that wasn't a publicised feature, and was quite incomplete, and was only done in the `range` and `range_mut` methods. r? `@Mark-Simulacrum`
2021-03-30Rollup merge of #82331 - frol:feat/std-binary-heap-as-slice, r=AmanieuDylan DPC-0/+21
alloc: Added `as_slice` method to `BinaryHeap` collection I initially asked about whether it is useful addition on https://internals.rust-lang.org/t/should-i-add-as-slice-method-to-binaryheap/13816, and it seems there were no objections, so went ahead with this PR. > There is [`BinaryHeap::into_vec`](https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html#method.into_vec), but it consumes the value. I wonder if there is API design limitation that should be taken into account. Implementation-wise, the inner buffer is just a Vec, so it is trivial to expose as_slice from it. Please, guide me through if I need to add tests or something else. UPD: Tracking issue #83659
2021-03-29Updated the tracking issue #Vlad Frolov-1/+1
2021-03-21use BITS constantThe8472-1/+1
2021-03-21implement TrustedLen and TrustedRandomAccess for VecDeque iteratorsThe8472-3/+77
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-18BTree: no longer search arrays twice to check OrdStein Somers-33/+27
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-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-17BTree: clarify order sanity enforced by range searchesStein Somers-7/+29
2021-03-16Fix comments based on reviewdylni-5/+2
2021-03-15Clarify BTree range searching commentsdylni-1/+3
2021-03-13provide a more realistic example for BinaryHeap::as_sliceVlad Frolov-5/+3
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-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-03BTree: move blocks around in node.rsStein Somers-167/+165
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-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/+227
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-24library: Normalize safety-for-unsafe-block commentsMiguel Ojeda-2/+2
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>