Skip to content

Commit 1e619ef

Browse files
committed
Further improvement of doc
1 parent 641c6da commit 1e619ef

File tree

1 file changed

+179
-11
lines changed

1 file changed

+179
-11
lines changed

src/map.rs

Lines changed: 179 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3963,7 +3963,7 @@ impl<'a, K, V, S, A: Allocator + Clone> RawVacantEntryMut<'a, K, V, S, A> {
39633963
/// use core::hash::{BuildHasher, Hash};
39643964
/// use hashbrown::hash_map::{HashMap, RawEntryMut};
39653965
///
3966-
/// fn compute_hash<K, S>(hash_builder: &S) -> impl Fn(&K) -> u64 + '_
3966+
/// fn make_hasher<K, S>(hash_builder: &S) -> impl Fn(&K) -> u64 + '_
39673967
/// where
39683968
/// K: Hash + ?Sized,
39693969
/// S: BuildHasher,
@@ -3979,12 +3979,12 @@ impl<'a, K, V, S, A: Allocator + Clone> RawVacantEntryMut<'a, K, V, S, A> {
39793979
/// let mut map: HashMap<&str, u32> = HashMap::new();
39803980
/// let key = "a";
39813981
/// let hash_builder = map.hasher().clone();
3982-
/// let hash = compute_hash(&hash_builder)(&key);
3982+
/// let hash = make_hasher(&hash_builder)(&key);
39833983
///
39843984
/// match map.raw_entry_mut().from_hash(hash, |q| q == &key) {
39853985
/// RawEntryMut::Occupied(_) => panic!(),
39863986
/// RawEntryMut::Vacant(v) => assert_eq!(
3987-
/// v.insert_with_hasher(hash, key, 100, compute_hash(&hash_builder)),
3987+
/// v.insert_with_hasher(hash, key, 100, make_hasher(&hash_builder)),
39883988
/// (&mut "a", &mut 100)
39893989
/// ),
39903990
/// }
@@ -4173,8 +4173,7 @@ impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for Entry<'_, K, V, S, A
41734173
/// Entry::Occupied(mut view) => {
41744174
/// assert_eq!(view.get(), &100);
41754175
/// let v = view.get_mut();
4176-
/// let new_v = (*v) * 10;
4177-
/// *v = new_v;
4176+
/// *v *= 10;
41784177
/// assert_eq!(view.insert(1111), 1000);
41794178
/// }
41804179
/// }
@@ -4229,6 +4228,32 @@ impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for OccupiedEntry<'_, K,
42294228
/// It is part of the [`Entry`] enum.
42304229
///
42314230
/// [`Entry`]: enum.Entry.html
4231+
///
4232+
/// # Examples
4233+
///
4234+
/// ```
4235+
/// use hashbrown::hash_map::{Entry, HashMap, VacantEntry};
4236+
///
4237+
/// let mut map = HashMap::<&str, i32>::new();
4238+
///
4239+
/// let entry_v: VacantEntry<_, _, _> = match map.entry("a") {
4240+
/// Entry::Vacant(view) => view,
4241+
/// Entry::Occupied(_) => unreachable!(),
4242+
/// };
4243+
/// entry_v.insert(10);
4244+
/// assert!(map[&"a"] == 10 && map.len() == 1);
4245+
///
4246+
/// // Nonexistent key (insert and update)
4247+
/// match map.entry("b") {
4248+
/// Entry::Occupied(_) => unreachable!(),
4249+
/// Entry::Vacant(view) => {
4250+
/// let value = view.insert(2);
4251+
/// assert_eq!(*value, 2);
4252+
/// *value = 20;
4253+
/// }
4254+
/// }
4255+
/// assert!(map[&"b"] == 20 && map.len() == 2);
4256+
/// ```
42324257
pub struct VacantEntry<'a, K, V, S, A: Allocator + Clone = Global> {
42334258
hash: u64,
42344259
key: K,
@@ -4241,12 +4266,21 @@ impl<K: Debug, V, S, A: Allocator + Clone> Debug for VacantEntry<'_, K, V, S, A>
42414266
}
42424267
}
42434268

4244-
/// A view into a single entry in a map, which may either be vacant or occupied.
4269+
/// A view into a single entry in a map, which may either be vacant or occupied,
4270+
/// with any borrowed form of the map's key type.
4271+
///
42454272
///
42464273
/// This `enum` is constructed from the [`entry_ref`] method on [`HashMap`].
4274+
///
4275+
/// [`Hash`] and [`Eq`] on the borrowed form of the map's key type *must* match those
4276+
/// for the key type. It also require that key may be constructed from the borrowed
4277+
/// form through the [`From`] trait.
42474278
///
42484279
/// [`HashMap`]: struct.HashMap.html
42494280
/// [`entry_ref`]: struct.HashMap.html#method.entry_ref
4281+
/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
4282+
/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
4283+
/// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
42504284
///
42514285
/// # Examples
42524286
///
@@ -4360,6 +4394,43 @@ impl<'a, K: Borrow<Q>, Q: ?Sized> AsRef<Q> for KeyOrRef<'a, K, Q> {
43604394
/// It is part of the [`EntryRef`] enum.
43614395
///
43624396
/// [`EntryRef`]: enum.EntryRef.html
4397+
///
4398+
/// # Examples
4399+
///
4400+
/// ```
4401+
/// use hashbrown::hash_map::{EntryRef, HashMap, OccupiedEntryRef};
4402+
///
4403+
/// let mut map = HashMap::new();
4404+
/// map.extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)]);
4405+
///
4406+
/// let key = String::from("a");
4407+
/// let _entry_o: OccupiedEntryRef<_, _, _, _> = map.entry_ref(&key).insert(100);
4408+
/// assert_eq!(map.len(), 3);
4409+
///
4410+
/// // Existing key (insert and update)
4411+
/// match map.entry_ref("a") {
4412+
/// EntryRef::Vacant(_) => unreachable!(),
4413+
/// EntryRef::Occupied(mut view) => {
4414+
/// assert_eq!(view.get(), &100);
4415+
/// let v = view.get_mut();
4416+
/// *v *= 10;
4417+
/// assert_eq!(view.insert(1111), 1000);
4418+
/// }
4419+
/// }
4420+
///
4421+
/// assert_eq!(map["a"], 1111);
4422+
/// assert_eq!(map.len(), 3);
4423+
///
4424+
/// // Existing key (take)
4425+
/// match map.entry_ref("c") {
4426+
/// EntryRef::Vacant(_) => unreachable!(),
4427+
/// EntryRef::Occupied(view) => {
4428+
/// assert_eq!(view.remove_entry(), ("c".to_owned(), 30));
4429+
/// }
4430+
/// }
4431+
/// assert_eq!(map.get("c"), None);
4432+
/// assert_eq!(map.len(), 2);
4433+
/// ```
43634434
pub struct OccupiedEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone = Global> {
43644435
hash: u64,
43654436
key: Option<KeyOrRef<'b, K, Q>>,
@@ -4401,6 +4472,32 @@ impl<K: Borrow<Q>, Q: ?Sized + Debug, V: Debug, S, A: Allocator + Clone> Debug
44014472
/// It is part of the [`EntryRef`] enum.
44024473
///
44034474
/// [`EntryRef`]: enum.EntryRef.html
4475+
///
4476+
/// # Examples
4477+
///
4478+
/// ```
4479+
/// use hashbrown::hash_map::{EntryRef, HashMap, VacantEntryRef};
4480+
///
4481+
/// let mut map = HashMap::<String, i32>::new();
4482+
///
4483+
/// let entry_v: VacantEntryRef<_, _, _, _> = match map.entry_ref("a") {
4484+
/// EntryRef::Vacant(view) => view,
4485+
/// EntryRef::Occupied(_) => unreachable!(),
4486+
/// };
4487+
/// entry_v.insert(10);
4488+
/// assert!(map["a"] == 10 && map.len() == 1);
4489+
///
4490+
/// // Nonexistent key (insert and update)
4491+
/// match map.entry_ref("b") {
4492+
/// EntryRef::Occupied(_) => unreachable!(),
4493+
/// EntryRef::Vacant(view) => {
4494+
/// let value = view.insert(2);
4495+
/// assert_eq!(*value, 2);
4496+
/// *value = 20;
4497+
/// }
4498+
/// }
4499+
/// assert!(map["b"] == 20 && map.len() == 2);
4500+
/// ```
44044501
pub struct VacantEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone = Global> {
44054502
hash: u64,
44064503
key: KeyOrRef<'b, K, Q>,
@@ -4418,6 +4515,27 @@ impl<K: Borrow<Q>, Q: ?Sized + Debug, V, S, A: Allocator + Clone> Debug
44184515
/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
44194516
///
44204517
/// Contains the occupied entry, and the value that was not inserted.
4518+
///
4519+
/// # Examples
4520+
///
4521+
/// ```
4522+
/// use hashbrown::hash_map::{HashMap, OccupiedError};
4523+
///
4524+
/// let mut map: HashMap<_, _> = [("a", 10), ("b", 20)].into();
4525+
///
4526+
/// // try_insert method returns mutable reference to the value if keys are vacant,
4527+
/// // but if the map did have key present, nothing is updated, and the provided
4528+
/// // value is returned inside `Err(_)` variant
4529+
/// match map.try_insert("a", 100) {
4530+
/// Err(OccupiedError { mut entry, value }) => {
4531+
/// assert_eq!(entry.key(), &"a");
4532+
/// assert_eq!(value, 100);
4533+
/// assert_eq!(entry.insert(100), 10)
4534+
/// }
4535+
/// _ => unreachable!(),
4536+
/// }
4537+
/// assert_eq!(map[&"a"], 100);
4538+
/// ```
44214539
pub struct OccupiedError<'a, K, V, S, A: Allocator + Clone = Global> {
44224540
/// The entry in the map that was already occupied.
44234541
pub entry: OccupiedEntry<'a, K, V, S, A>,
@@ -4453,6 +4571,28 @@ impl<'a, K, V, S, A: Allocator + Clone> IntoIterator for &'a HashMap<K, V, S, A>
44534571
type Item = (&'a K, &'a V);
44544572
type IntoIter = Iter<'a, K, V>;
44554573

4574+
/// Creates an iterator over the entries of a `HashMap` in arbitrary order.
4575+
/// The iterator element type is `(&'a K, &'a V)`.
4576+
///
4577+
/// Return the same `Iter` struct as by the [`iter`] method on [`HashMap`].
4578+
///
4579+
/// [`iter`]: struct.HashMap.html#method.iter
4580+
/// [`HashMap`]: struct.HashMap.html
4581+
///
4582+
/// # Examples
4583+
///
4584+
/// ```
4585+
/// use hashbrown::HashMap;
4586+
/// let map_one: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
4587+
/// let mut map_two = HashMap::new();
4588+
///
4589+
/// for (key, value) in &map_one {
4590+
/// println!("Key: {}, Value: {}", key, value);
4591+
/// map_two.insert_unique_unchecked(*key, *value);
4592+
/// }
4593+
///
4594+
/// assert_eq!(map_one, map_two);
4595+
/// ```
44564596
#[cfg_attr(feature = "inline-more", inline)]
44574597
fn into_iter(self) -> Iter<'a, K, V> {
44584598
self.iter()
@@ -4463,6 +4603,33 @@ impl<'a, K, V, S, A: Allocator + Clone> IntoIterator for &'a mut HashMap<K, V, S
44634603
type Item = (&'a K, &'a mut V);
44644604
type IntoIter = IterMut<'a, K, V>;
44654605

4606+
/// Creates an iterator over the entries of a `HashMap` in arbitrary order
4607+
/// with mutable references to the values. The iterator element type is
4608+
/// `(&'a K, &'a mut V)`.
4609+
///
4610+
/// Return the same `IterMut` struct as by the [`iter_mut`] method on
4611+
/// [`HashMap`].
4612+
///
4613+
/// [`iter_mut`]: struct.HashMap.html#method.iter_mut
4614+
/// [`HashMap`]: struct.HashMap.html
4615+
///
4616+
/// # Examples
4617+
///
4618+
/// ```
4619+
/// use hashbrown::HashMap;
4620+
/// let mut map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
4621+
///
4622+
/// for (key, value) in &mut map {
4623+
/// println!("Key: {}, Value: {}", key, value);
4624+
/// *value *= 2;
4625+
/// }
4626+
///
4627+
/// let mut vec = map.iter().collect::<Vec<_>>();
4628+
/// // The `Iter` iterator produces items in arbitrary order, so the
4629+
/// // items must be sorted to test them against a sorted array.
4630+
/// vec.sort_unstable();
4631+
/// assert_eq!(vec, [(&"a", &2), (&"b", &4), (&"c", &6)]);
4632+
/// ```
44664633
#[cfg_attr(feature = "inline-more", inline)]
44674634
fn into_iter(self) -> IterMut<'a, K, V> {
44684635
self.iter_mut()
@@ -4482,13 +4649,14 @@ impl<K, V, S, A: Allocator + Clone> IntoIterator for HashMap<K, V, S, A> {
44824649
/// ```
44834650
/// use hashbrown::HashMap;
44844651
///
4485-
/// let mut map = HashMap::new();
4486-
/// map.insert("a", 1);
4487-
/// map.insert("b", 2);
4488-
/// map.insert("c", 3);
4652+
/// let map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
44894653
///
44904654
/// // Not possible with .iter()
4491-
/// let vec: Vec<(&str, i32)> = map.into_iter().collect();
4655+
/// let mut vec: Vec<(&str, i32)> = map.into_iter().collect();
4656+
/// // The `IntoIter` iterator produces items in arbitrary order, so
4657+
/// // the items must be sorted to test them against a sorted array.
4658+
/// vec.sort_unstable();
4659+
/// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
44924660
/// ```
44934661
#[cfg_attr(feature = "inline-more", inline)]
44944662
fn into_iter(self) -> IntoIter<K, V, A> {

0 commit comments

Comments
 (0)