about summary refs log tree commit diff
path: root/library/std/src/collections/hash
AgeCommit message (Collapse)AuthorLines
2021-08-07Use assert_matches! instead of if let {} elseKornel-9/+12
2021-08-07Auto merge of #87408 - kornelski:try_reserve_error, r=yaahcbors-5/+8
Hide allocator details from TryReserveError I think there's [no need for TryReserveError to carry detailed information](https://github.com/rust-lang/rust/issues/48043#issuecomment-825139280), but I wouldn't want that issue to delay stabilization of the `try_reserve` feature. So I'm proposing to stabilize `try_reserve` with a `TryReserveError` as an opaque structure, and if needed, expose error details later. This PR moves the `enum` to an unstable inner `TryReserveErrorKind` that lives under a separate feature flag. `TryReserveErrorKind` could possibly be left as an implementation detail forever, and the `TryReserveError` get methods such as `allocation_size() -> Option<usize>` or `layout() -> Option<Layout>` instead, or the details could be dropped completely to make try-reserve errors just a unit struct, and thus smaller and cheaper.
2021-08-06Auto merge of #87462 - ibraheemdev:tidy-file-length-ignore-comment, ↵bors-2/+0
r=Mark-Simulacrum Ignore comments in tidy-filelength Ref https://github.com/rust-lang/rust/issues/60302#issuecomment-652402127
2021-07-28Rollup merge of #87330 - inquisitivecrystal:extend-reserve, r=JohnTitorYuki Okushi-9/+1
Use hashbrown's `extend_reserve()` in `HashMap` When we added `extend_reserve()` to our implementation of `Extend` for `HashMap`, hashbrown didn't have a version we could use. Now that hashbrown has added it, we should use its version instead of implementing it ourself.
2021-07-25ignore comments in tidy-filelengthibraheemdev-2/+0
2021-07-24Auto merge of #84111 - bstrie:hashfrom, r=joshtriplettbors-21/+108
Stabilize `impl From<[(K, V); N]> for HashMap` (and friends) In addition to allowing HashMap to participate in Into/From conversion, this adds the long-requested ability to use constructor-like syntax for initializing a HashMap: ```rust let map = HashMap::from([ (1, 2), (3, 4), (5, 6) ]); ``` This addition is highly motivated by existing precedence, e.g. it is already possible to similarly construct a Vec from a fixed-size array: ```rust let vec = Vec::from([1, 2, 3]); ``` ...and it is already possible to collect a Vec of tuples into a HashMap (and vice-versa): ```rust let vec = Vec::from([(1, 2)]); let map: HashMap<_, _> = vec.into_iter().collect(); let vec: Vec<(_, _)> = map.into_iter().collect(); ``` ...and of course it is likewise possible to collect a fixed-size array of tuples into a HashMap ([but not vice-versa just yet](https://github.com/rust-lang/rust/issues/81615)): ```rust let arr = [(1, 2)]; let map: HashMap<_, _> = std::array::IntoIter::new(arr).collect(); ``` Therefore this addition seems like a no-brainer. As for any impl, this would be insta-stable.
2021-07-24Hide allocator details from TryReserveErrorKornel-5/+8
2021-07-24Update std_collections_from_array stability versionbstrie-2/+2
2021-07-24Rollup merge of #86790 - janikrabe:retain-iter-order-doc, r=m-ou-seYuki Okushi-0/+2
Document iteration order of `retain` functions For `HashSet` and `HashMap`, this simply copies the comment from `BinaryHeap::retain`. For `BTreeSet` and `BTreeMap`, this adds an additional guarantee that wasn't previously documented. I think that because these data structures are inherently ordered and other functions guarantee ordered iteration, it makes sense to provide this guarantee for `retain` as well.
2021-07-20Use hashbrown's `extend_reserve()` in `HashMap`inquisitivecrystal-9/+1
2021-07-15Added diagnostic items to structs and traits for ClippyxFrednet-0/+1
2021-07-06Stabilize Vec<T>::shrink_toYoh Deadfall-4/+2
2021-07-01Document iteration order of `retain` functionsJanik Rabe-0/+2
For `HashSet` and `HashMap`, this simply copies the comment from `BinaryHeap::retain`. For `BTreeSet` and `BTreeMap`, this adds an additional guarantee that wasn't previously documented. I think that because these data structures are inherently ordered and other functions guarantee ordered iteration, it makes sense to provide this guarantee for `retain` as well.
2021-06-30impl From<[(K, V); N]> for std::collectionsbstrie-21/+108
2021-06-30Remove "length" doc aliasesAmanieu d'Antras-2/+0
2021-06-30Remove "delete" doc aliasesAmanieu d'Antras-2/+0
2021-05-06Rollup merge of #84328 - Folyd:stablize_map_into_keys_values, r=m-ou-seDylan DPC-18/+12
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-05Bump map_into_keys_values stable version to 1.54.0.Mara Bos-12/+12
2021-04-21Replace all `fmt.pad` with `debug_struct`Christiaan Dirkx-3/+3
2021-04-19Stablize {HashMap,BTreeMap}::into_{keys,values}Folyd-18/+12
2021-03-27Use DebugStruct::finish_non_exhaustive() in std.Mara Bos-6/+9
2021-03-18Rollup merge of #82434 - jyn514:hash, r=JohnTitorDylan DPC-2/+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-05Rollup merge of #82764 - m-ou-se:map-try-insert, r=AmanieuMara-0/+68
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-04Add tracking issue for map_try_insert.Mara Bos-4/+4
2021-03-04Remove unnecessary bound from HashMap::try_insert.Mara Bos-4/+1
2021-03-04Ignore file length tidy warning in hash/map.rs.Mara Bos-0/+2
2021-03-04Implement Error for OccupiedError.Mara Bos-0/+13
2021-03-04Improve Debug implementations of OccupiedError.Mara Bos-1/+11
2021-03-04Add HashMap::try_insert and hash_map::OccupiedError.Mara Bos-0/+46
2021-03-03Fix std testsRyan Levick-4/+4
2021-02-23Add more links between hash and btree collectionsJoshua Nelson-2/+4
- 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
2021-01-31Add doc aliases for "delete"Konrad Borowski-0/+2
This patch adds doc aliases for "delete". The added aliases are supposed to reference usages `delete` in other programming languages. - `HashMap::remove`, `BTreeMap::remove` -> `Map#delete` and `delete` keyword in JavaScript. - `HashSet::remove`, `BTreeSet::remove` -> `Set#delete` in JavaScript. - `mem::drop` -> `delete` keyword in C++. - `fs::remove_file`, `fs::remove_dir`, `fs::remove_dir_all` -> `File#delete` in Java, `File#delete` and `Dir#delete` in Ruby. Before this change, searching for "delete" in documentation returned no results.
2021-01-26shrink_to shouldn't panic on len greater than capacityThom Wiggers-6/+2
2021-01-16Clarify what the effects of a 'logic error' areChris Jefferson-1/+6
2020-12-28Add "length" as doc alias to len methodsKonrad Borowski-0/+2
2020-12-26Use the hashbrown::{HashMap,HashSet} `clone_from` impls.David Adler-2/+35
2020-12-19Rollup merge of #78083 - ChaiTRex:master, r=m-ou-seYuki Okushi-5/+7
Stabilize or_insert_with_key Stabilizes the `or_insert_with_key` feature from https://github.com/rust-lang/rust/issues/71024. This allows inserting key-derived values when a `HashMap`/`BTreeMap` entry is vacant. The difference between this and `.or_insert_with(|| ... )` is that this provides a reference to the key to the closure after it is moved with `.entry(key_being_moved)`, avoiding the need to copy or clone the key.
2020-12-07Improved documentation for HashMap/BTreeMap Entry's .or_insert_with_key methodChai T. Rex-3/+6
2020-12-01Update rustc version that or_insert_with_key landedChai T. Rex-1/+1
2020-11-13Rollup merge of #77996 - tkaitchuck:master, r=m-ou-seGuillaume Gomez-3/+3
Doc change: Remove mention of `fnv` in HashMap Disclaimer: I am the author of [aHash](https://github.com/tkaitchuck/aHash). This changes the Rustdoc in `HashMap` from mentioning the `fnv` crate to mentioning the `aHash` crate, as an alternative `Hasher` implementation. ### Why Fnv [has poor hash quality](https://github.com/rurban/smhasher), is [slow for larger keys](https://github.com/tkaitchuck/aHash/blob/master/compare/readme.md#speed), and does not provide dos resistance, because it is unkeyed (this can also cause [other problems](https://accidentallyquadratic.tumblr.com/post/153545455987/rust-hash-iteration-reinsertion)). Fnv has acceptable performance for integers and has very poor performance with keys >32 bytes. This is the reason it was removed from the standard library in https://github.com/rust-lang/rust/pull/37229 . Because regardless of which dimension you value, there are better alternatives, it does not make sense for anyone to consider using `fnv`. The text mentioning `fnv` in the standard library continues to create confusion: https://github.com/rust-lang/hashbrown/issues/153 https://github.com/rust-lang/hashbrown/issues/9 . There are also a number of [crates using it](https://crates.io/crates/fnv/reverse_dependencies) a great many of which are hashing strings (Which is when Fnv is the [worst](https://github.com/cbreeden/fxhash#benchmarks), [possible](https://github.com/tkaitchuck/aHash#speed), [choice](http://cglab.ca/~abeinges/blah/hash-rs/).) I think aHash makes the most sense to mention as an alternative because it is the most credible option (in my obviously biased opinion). It offers [good performance on numbers and strings](https://github.com/tkaitchuck/aHash/blob/master/compare/readme.md#speed), is [of high quality](https://github.com/tkaitchuck/aHash#hash-quality), and [provides dos resistance](https://github.com/tkaitchuck/aHash/wiki/How-aHash-is-resists-DOS-attacks). It is popular (see [stats](https://crates.io/crates/ahash)) and is the default hasher for [hashbrown](https://crates.io/crates/hashbrown) and [dashmap](https://crates.io/crates/dashmap) which are the most popular alternative hashmaps. Finally it does not have any of the [`gotcha` cases](https://github.com/tkaitchuck/aHash#fxhash) that `FxHash` suffers from. (Which is the other popular hashing option when DOS attacks are not a concern) Signed-off-by: Tom Kaitchuck <tom.kaitchuck@emc.com>
2020-11-12Update library/std/src/collections/hash/map.rsTom Kaitchuck-1/+1
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
2020-11-07Convert a bunch of intra-doc linksCamelid-4/+0
2020-10-27Change link to point to crates.io keyword "hasher"Tom Kaitchuck-3/+3
Signed-off-by: Tom Kaitchuck <Tom.Kaitchuck@gmail.com>
2020-10-26Improve formatting of hash collections docsCamelid-5/+6
2020-10-18Stabilize or_insert_with_keyChai T. Rex-2/+1
2020-10-15Change mention of `fnv` in HashMap to mention `aHash` as an alternitive hasher.Tom Kaitchuck-2/+2
Signed-off-by: Tom Kaitchuck <tom.kaitchuck@emc.com>
2020-10-04Rollup merge of #77072 - sharnoff:hash-docs, r=LukasKalbertodtJonas Schievink-20/+20
Minor `hash_map` doc adjustments + item attribute orderings This PR is really a couple visual changes glued together: 1. Some of the doc comments for items in `std::collections::hash_map` referenced the names of types without escaping their formatting (e.g. using "VacantEntry" instead of "`VacantEntry`") - the ones I could find were changed to the latter 2. The vast majority of pre-item attributes seem to place doc comments as the first attribute (instead of things like `#[feature(...)]`), so the few that had the other order were changed. 3. Also ordering related: the general trend seems to be that `#[feature]` attributes follow `#[inline]`, so I swapped the two lines in places where that ordering was reversed. This is primarily a change based on stylistic continuity and aesthetics - I'm not sure how important that actually is / should be. I figured this would be pretty uncontroversial, but some of these might have been intentional for reasons I don't know about - if so, I'd be happy to remove the relevant changes. Of these, the final set of changes is probably the most unnecessary, so it also might be better to leave those out (in favor of reducing code churn).
2020-10-03Rollup merge of #75377 - canova:map_debug_impl, r=dtolnayJonas Schievink-8/+4
Fix Debug implementations of some of the HashMap and BTreeMap iterator types HashMap's `ValuesMut`, BTreeMaps `ValuesMut`, IntoValues and `IntoKeys` structs were printing both keys and values on their Debug implementations. But they are iterators over either keys or values. Irrelevant values should not be visible. With this PR, they only show relevant fields. This fixes #75297. [Here's an example code.](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=0c79356ed860e347a0c1a205616f93b7) This prints this on nightly: ``` ValuesMut { inner: IterMut { range: [(1, "hello"), (2, "goodbye")], length: 2 } } IntoKeys { inner: [(1, "hello"), (2, "goodbye")] } IntoValues { inner: [(1, "hello"), (2, "goodbye")] } [(2, "goodbye"), (1, "hello")] ``` After the patch this example prints these instead: ``` ["hello", "goodbye"] ["hello", "goodbye"] [1, 2] ["hello", "goodbye"] ``` I didn't add test cases for them, since I couldn't see any tests for Debug implementations anywhere. But please let me know if I should add it to a specific place. r? @dtolnay
2020-10-02Link `new` method in `DefautHasher`s docWaffle-4/+3
2020-09-27Rollup merge of #76917 - GuillaumeGomez:map-missing-code-examples, r=Dylan-DPCJonas Schievink-1/+106
Add missing code examples on HashMap types r? @Dylan-DPC