diff options
| author | Jon Gjengset <jon@thesquareplanet.com> | 2017-09-05 12:34:05 -0400 |
|---|---|---|
| committer | Jon Gjengset <jon@thesquareplanet.com> | 2017-09-05 13:11:38 -0400 |
| commit | 35c7943fd2d2a65b63712d95d62c8837633218b4 (patch) | |
| tree | e6071ea3dc7c8d821093ae7999b2c08417e9e1b3 /src/liballoc | |
| parent | 2f1ef9ef1181298d46e79d5dde6bafeb6483926f (diff) | |
| download | rust-35c7943fd2d2a65b63712d95d62c8837633218b4.tar.gz rust-35c7943fd2d2a65b63712d95d62c8837633218b4.zip | |
Add or_default to Entry APIs
Diffstat (limited to 'src/liballoc')
| -rw-r--r-- | src/liballoc/btree/map.rs | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/src/liballoc/btree/map.rs b/src/liballoc/btree/map.rs index f733c3332e2..0adfaf3be8f 100644 --- a/src/liballoc/btree/map.rs +++ b/src/liballoc/btree/map.rs @@ -2104,6 +2104,35 @@ impl<'a, K: Ord, V> Entry<'a, K, V> { } } +impl<'a, K: Ord, V: Default> Entry<'a, K, V> { + #[unstable(feature = "entry_or_default", issue = "44324")] + /// Ensures a value is in the entry by inserting the default value if empty, + /// and returns a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// #![feature(entry_or_default)] + /// # fn main() { + /// use std::collections::BTreeMap; + /// + /// let mut map: BTreeMap<&str, String> = BTreeMap::new(); + /// let s = "hoho".to_string(); + /// + /// map.entry("poneyland").or_default(); + /// + /// assert_eq!(map["poneyland"], None); + /// # } + /// ``` + pub fn or_default(self) -> &'a mut V { + match self { + Occupied(entry) => entry.into_mut(), + Vacant(entry) => entry.insert(Default::default()), + } + } + +} + impl<'a, K: Ord, V> VacantEntry<'a, K, V> { /// Gets a reference to the key that would be used when inserting a value /// through the VacantEntry. |
