about summary refs log tree commit diff
diff options
context:
space:
mode:
authorKarlWithK <cjh16@rice.edu>2022-06-15 02:04:18 -0500
committerKarlWithK <cjh16@rice.edu>2022-06-15 02:04:18 -0500
commitcec72acdcae939023d7d4e09ad1b06d49f269276 (patch)
tree4ec73546952bc8f46cc2617625c12cccf218f8d5
parentd3d22e1e664d33519ddc1b4bbc00cc93eed3e7be (diff)
downloadrust-cec72acdcae939023d7d4e09ad1b06d49f269276.tar.gz
rust-cec72acdcae939023d7d4e09ad1b06d49f269276.zip
Add examples using `add_modify` to btree
Updated the btree's documentation to include two references to
add_modify.

The first is when the `Entry` API is mentioned at the beginning. With
the same reasoning as HashMap's documentation, I thought it would best
to keep `attack`, but show the `mana` example.

The second is with the `entry` function that is used for the `Entry`
API. The code example was a perfect use for `add_modify`, which is why
it was changed to reflect that.
-rw-r--r--library/alloc/src/collections/btree/map.rs7
1 files changed, 6 insertions, 1 deletions
diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs
index 6027991a0ed..7532c1d5114 100644
--- a/library/alloc/src/collections/btree/map.rs
+++ b/library/alloc/src/collections/btree/map.rs
@@ -159,6 +159,9 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
 /// // update a key, guarding against the key possibly not being set
 /// let stat = player_stats.entry("attack").or_insert(100);
 /// *stat += random_stat_buff();
+///
+/// // modify an entry before an insert with in-place mutation
+/// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
 /// ```
 #[stable(feature = "rust1", since = "1.0.0")]
 #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
@@ -1135,10 +1138,12 @@ impl<K, V> BTreeMap<K, V> {
     ///
     /// // count the number of occurrences of letters in the vec
     /// for x in ["a", "b", "a", "c", "a", "b"] {
-    ///     *count.entry(x).or_insert(0) += 1;
+    ///     count.entry(x).and_modify(|curr| *curr += 1).or_insert(1);
     /// }
     ///
     /// assert_eq!(count["a"], 3);
+    /// assert_eq!(count["b"], 2);
+    /// assert_eq!(count["1"], 1);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn entry(&mut self, key: K) -> Entry<'_, K, V>