Commit Graph

51 Commits

Author SHA1 Message Date
bstrie 49aa79ec11 Deprecate items that accidentally weren't deprecated
Fixes #82080
2021-03-09 19:09:20 -05:00
Mara 232caad395
Rollup merge of #82764 - m-ou-se:map-try-insert, r=Amanieu
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-05 10:57:22 +01:00
Mara Bos eddd4f0501 Add tracking issue for map_try_insert. 2021-03-04 16:54:28 +01:00
Mara Bos 1aedb4c3a3 Remove unnecessary bound from HashMap::try_insert. 2021-03-04 16:46:41 +01:00
Mara Bos da01455813 Ignore file length tidy warning in hash/map.rs. 2021-03-04 16:25:24 +01:00
Mara Bos d85d82ab22 Implement Error for OccupiedError. 2021-03-04 15:58:50 +01:00
Mara Bos 69d95e232a Improve Debug implementations of OccupiedError. 2021-03-04 15:58:50 +01:00
Mara Bos f6fe24aab3 Add HashMap::try_insert and hash_map::OccupiedError. 2021-03-04 15:58:50 +01:00
Ryan Levick c5ff54cbdb Fix std tests 2021-03-03 11:22:51 +01:00
Jack Huey d3304c8ac3
Rollup merge of #81588 - xfix:delete-doc-alias, r=Mark-Simulacrum
Add doc aliases for "delete"

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-02-02 16:01:41 -05:00
Konrad Borowski 15701f7531 Add doc aliases for "delete"
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-31 11:07:37 +01:00
Konrad Borowski 56c27360b1 Replace predecessor with range in collections documentation
Fixes #81548.
2021-01-30 14:24:06 +01:00
Thom Wiggers d069c58e78
shrink_to shouldn't panic on len greater than capacity 2021-01-26 19:25:37 +01:00
Chris Jefferson 78d919280d Clarify what the effects of a 'logic error' are 2021-01-16 09:36:28 +00:00
Konrad Borowski 9e779986aa Add "length" as doc alias to len methods 2020-12-28 09:13:46 +01:00
David Adler 7adeb710fb Use the hashbrown::{HashMap,HashSet} `clone_from` impls. 2020-12-26 19:39:38 -05:00
Yuki Okushi 0765536c0b
Rollup merge of #78083 - ChaiTRex:master, r=m-ou-se
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-19 15:15:57 +09:00
Chai T. Rex f1b930d57c Improved documentation for HashMap/BTreeMap Entry's .or_insert_with_key method 2020-12-07 21:36:01 -05:00
Chai T. Rex 866ef87d3f Update rustc version that or_insert_with_key landed 2020-12-01 01:06:40 -05:00
Guillaume Gomez ef32ef7baf
Rollup merge of #77996 - tkaitchuck:master, r=m-ou-se
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-13 15:26:10 +01:00
Tom Kaitchuck 4e5848349c
Update library/std/src/collections/hash/map.rs
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
2020-11-12 20:14:57 -08:00
Camelid 8258cf285f Convert a bunch of intra-doc links 2020-11-07 12:50:57 -08:00
Tom Kaitchuck 5b3d98d9f8 Change link to point to crates.io keyword "hasher"
Signed-off-by: Tom Kaitchuck <Tom.Kaitchuck@gmail.com>
2020-10-27 20:49:52 -07:00
Camelid 59f108885e Improve formatting of hash collections docs 2020-10-26 14:05:06 -07:00
Chai T. Rex c2de8fe294 Stabilize or_insert_with_key 2020-10-18 15:45:09 -04:00
Tom Kaitchuck 1d287255f5 Change mention of `fnv` in HashMap to mention `aHash` as an alternitive hasher.
Signed-off-by: Tom Kaitchuck <tom.kaitchuck@emc.com>
2020-10-15 14:03:39 -07:00
Jonas Schievink 4ae7710e1d
Rollup merge of #77072 - sharnoff:hash-docs, r=LukasKalbertodt
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-04 15:45:33 +02:00
Jonas Schievink 1118ab9930
Rollup merge of #75377 - canova:map_debug_impl, r=dtolnay
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-03 00:31:04 +02:00
Waffle 1c2c336dbc Link `new` method in `DefautHasher`s doc 2020-10-02 00:30:19 +03:00
Jonas Schievink 9ab95c36e2
Rollup merge of #76917 - GuillaumeGomez:map-missing-code-examples, r=Dylan-DPC
Add missing code examples on HashMap types

r? @Dylan-DPC
2020-09-27 01:53:13 +02:00
sharnoff 8a011b5da2 minor doc changes, attribute orderings 2020-09-22 19:34:05 +01:00
Guillaume Gomez be3d8e5d6c Add missing code examples on HashMap types 2020-09-21 13:32:03 +02:00
Ralf Jung f24d279084
Rollup merge of #76887 - GuillaumeGomez:hashset-iter-types-examples, r=Dylan-DPC
Add missing examples on HashSet iter types
2020-09-20 15:51:59 +02:00
Guillaume Gomez 28588e5df1 Add missing examples on HashSet iter types 2020-09-18 20:09:31 +02:00
Amjad Alsharafi 878dfa6718 Fixed intra-docs links in library/std/src/collections/hash/map.rs 2020-09-18 07:50:22 +08:00
Matt Brubeck fb1fab5a67 Tests for HashMap/HashSet::drain_filter 2020-09-08 17:24:28 -07:00
Matt Brubeck 49aef963d3 Add HashMap::drain_filter and HashSet::drain_filter
Implements #59618.
2020-09-08 17:24:28 -07:00
Matt Brubeck ebd15e790a Implement HashSet in terms of hashbrown::HashSet 2020-09-08 17:24:23 -07:00
Matt Brubeck 15ccdeb224 Update to hashbrown 0.9 2020-09-08 17:23:26 -07:00
bors aa81d32165 Auto merge of #76128 - poliorcetics:doc-use-arc-clone, r=KodrAus
Use Arc::clone and Rc::clone in documentation

This PR replaces uses of `x.clone()` by `Rc::clone(&x)` (or `Arc::clone(&x)`) to better match the documentation for those types.

@rustbot modify labels: T-doc
2020-09-06 12:34:31 +00:00
Lzu Tao a4e926daee std: move "mod tests/benches" to separate files
Also doing fmt inplace as requested.
2020-08-31 02:56:59 +00:00
Alexis Bourget 81e85ce76d Move to Arc::clone(&x) over x.clone() in library/std 2020-08-30 21:59:43 +02:00
Camelid e9928d8926
Switch to intra-doc links in `std::collections` 2020-08-23 13:51:01 -07:00
Nazım Can Altınova 8faf550e5f
Remove the unused bounds from Debug impl of HashMap::{IntoKeys,IntoValues} 2020-08-11 20:42:02 +02:00
Nazım Can Altınova 456738e3d1
Only print values in the Debug of HashMap::ValuesMut struct 2020-08-10 23:06:04 +02:00
Nazım Can Altınova 4cd2637e2b
Update the tracking issue number of map_into_keys_values 2020-08-08 16:35:54 +02:00
Nazım Can Altınova 25545ed180
Only print the fields that are relevant to iterators for Debug of IntoKeys and IntoValues 2020-08-07 13:47:04 +02:00
Nazım Can Altınova 41dd4ee7ff
Add unit tests for new `HashMap::into_{keys,values}` methods 2020-08-07 13:13:41 +02:00
Nazım Can Altınova e31116af50
Add `into_{keys,values}` methods for HashMap 2020-08-07 13:13:37 +02:00
Amanieu d'Antras d51b7b229a Update hashbrown to 0.8.1 2020-08-07 07:03:12 +01:00