about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2017-10-06 12:51:11 +0000
committerbors <bors@rust-lang.org>2017-10-06 12:51:11 +0000
commita8feaee5b6b54c03f49481fe04a9ad9e8f659f7c (patch)
tree4918f2dbd5a71e6157e0e50c1fd71278e5161225 /src
parent3ed8b698421291f5057059da885cd670d76a47e9 (diff)
parent9e36111fc60ff448bb8c2977dc51ccf0d3e3a3e9 (diff)
downloadrust-a8feaee5b6b54c03f49481fe04a9ad9e8f659f7c.tar.gz
rust-a8feaee5b6b54c03f49481fe04a9ad9e8f659f7c.zip
Auto merge of #44734 - mchlrhw:wip/hashmap-entry-and-then, r=BurntSushi
Implement `and_modify` on `Entry`

## Motivation

`Entry`s are useful for allowing access to existing values in a map while also allowing default values to be inserted for absent keys. The existing API is similar to that of `Option`, where `or` and `or_with` can be used if the option variant is `None`.

The `Entry` API is, however, missing an equivalent of `Option`'s `and_then` method. If it were present it would be possible to modify an existing entry before calling `or_insert` without resorting to matching on the entry variant.

Tracking issue: https://github.com/rust-lang/rust/issues/44733.
Diffstat (limited to 'src')
-rw-r--r--src/doc/unstable-book/src/library-features/entry-and-modify.md77
-rw-r--r--src/liballoc/btree/map.rs34
-rw-r--r--src/libstd/collections/hash/map.rs35
3 files changed, 146 insertions, 0 deletions
diff --git a/src/doc/unstable-book/src/library-features/entry-and-modify.md b/src/doc/unstable-book/src/library-features/entry-and-modify.md
new file mode 100644
index 00000000000..1280c71e83c
--- /dev/null
+++ b/src/doc/unstable-book/src/library-features/entry-and-modify.md
@@ -0,0 +1,77 @@
+# `entry_and_modify`
+
+The tracking issue for this feature is: [#44733]
+
+[#44733]: https://github.com/rust-lang/rust/issues/44733
+
+------------------------
+
+This introduces a new method for the Entry API of maps
+(`std::collections::HashMap` and `std::collections::BTreeMap`), so that
+occupied entries can be modified before any potential inserts into the
+map.
+
+For example:
+
+```rust
+#![feature(entry_and_modify)]
+# fn main() {
+use std::collections::HashMap;
+
+struct Foo {
+    new: bool,
+}
+
+let mut map: HashMap<&str, Foo> = HashMap::new();
+
+map.entry("quux")
+   .and_modify(|e| e.new = false)
+   .or_insert(Foo { new: true });
+# }
+```
+
+This is not possible with the stable API alone since inserting a default
+_before_ modifying the `new` field would mean we would lose the default state:
+
+```rust
+# fn main() {
+use std::collections::HashMap;
+
+struct Foo {
+    new: bool,
+}
+
+let mut map: HashMap<&str, Foo> = HashMap::new();
+
+map.entry("quux").or_insert(Foo { new: true }).new = false;
+# }
+```
+
+In the above code the `new` field will never be `true`, even though we only
+intended to update that field to `false` for previously extant entries.
+
+To achieve the same effect as `and_modify` we would have to manually match
+against the `Occupied` and `Vacant` variants of the `Entry` enum, which is
+a little less user-friendly, and much more verbose:
+
+```rust
+# fn main() {
+use std::collections::HashMap;
+use std::collections::hash_map::Entry;
+
+struct Foo {
+    new: bool,
+}
+
+let mut map: HashMap<&str, Foo> = HashMap::new();
+
+match map.entry("quux") {
+    Entry::Occupied(entry) => {
+        entry.into_mut().new = false;
+    },
+    Entry::Vacant(entry) => {
+        entry.insert(Foo { new: true });
+    },
+};
+# }
+```
diff --git a/src/liballoc/btree/map.rs b/src/liballoc/btree/map.rs
index 4c93fead172..b114dc640fb 100644
--- a/src/liballoc/btree/map.rs
+++ b/src/liballoc/btree/map.rs
@@ -2102,6 +2102,40 @@ impl<'a, K: Ord, V> Entry<'a, K, V> {
             Vacant(ref entry) => entry.key(),
         }
     }
+
+    /// Provides in-place mutable access to an occupied entry before any
+    /// potential inserts into the map.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(entry_and_modify)]
+    /// use std::collections::BTreeMap;
+    ///
+    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
+    ///
+    /// map.entry("poneyland")
+    ///    .and_modify(|e| { *e += 1 })
+    ///    .or_insert(42);
+    /// assert_eq!(map["poneyland"], 42);
+    ///
+    /// map.entry("poneyland")
+    ///    .and_modify(|e| { *e += 1 })
+    ///    .or_insert(42);
+    /// assert_eq!(map["poneyland"], 43);
+    /// ```
+    #[unstable(feature = "entry_and_modify", issue = "44733")]
+    pub fn and_modify<F>(self, mut f: F) -> Self
+        where F: FnMut(&mut V)
+    {
+        match self {
+            Occupied(mut entry) => {
+                f(entry.get_mut());
+                Occupied(entry)
+            },
+            Vacant(entry) => Vacant(entry),
+        }
+    }
 }
 
 impl<'a, K: Ord, V: Default> Entry<'a, K, V> {
diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs
index 406acde1f1c..3c0fa0860d3 100644
--- a/src/libstd/collections/hash/map.rs
+++ b/src/libstd/collections/hash/map.rs
@@ -2013,6 +2013,41 @@ impl<'a, K, V> Entry<'a, K, V> {
             Vacant(ref entry) => entry.key(),
         }
     }
+
+    /// Provides in-place mutable access to an occupied entry before any
+    /// potential inserts into the map.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(entry_and_modify)]
+    /// use std::collections::HashMap;
+    ///
+    /// let mut map: HashMap<&str, u32> = HashMap::new();
+    ///
+    /// map.entry("poneyland")
+    ///    .and_modify(|e| { *e += 1 })
+    ///    .or_insert(42);
+    /// assert_eq!(map["poneyland"], 42);
+    ///
+    /// map.entry("poneyland")
+    ///    .and_modify(|e| { *e += 1 })
+    ///    .or_insert(42);
+    /// assert_eq!(map["poneyland"], 43);
+    /// ```
+    #[unstable(feature = "entry_and_modify", issue = "44733")]
+    pub fn and_modify<F>(self, mut f: F) -> Self
+        where F: FnMut(&mut V)
+    {
+        match self {
+            Occupied(mut entry) => {
+                f(entry.get_mut());
+                Occupied(entry)
+            },
+            Vacant(entry) => Vacant(entry),
+        }
+    }
+
 }
 
 impl<'a, K, V: Default> Entry<'a, K, V> {