]> git.lizzy.rs Git - rust.git/commitdiff
Implement get_key_value for HashMap, BTreeMap
authorDiggory Blake <diggsey@googlemail.com>
Mon, 25 Dec 2017 00:00:04 +0000 (00:00 +0000)
committerDiggory Blake <diggsey@googlemail.com>
Sun, 25 Mar 2018 22:50:47 +0000 (23:50 +0100)
src/liballoc/btree/map.rs
src/libstd/collections/hash/map.rs

index ed9c8c18f0d6db7059d65d77a78b59af9b3a1b72..cada190032aa064c806545b65c9c96ec05e3b65b 100644 (file)
@@ -576,6 +576,33 @@ pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
         }
     }
 
+    /// Returns the key-value pair corresponding to the supplied key.
+    ///
+    /// The supplied key may be any borrowed form of the map's key type, but the ordering
+    /// on the borrowed form *must* match the ordering on the key type.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(map_get_key_value)]
+    /// use std::collections::BTreeMap;
+    ///
+    /// let mut map = BTreeMap::new();
+    /// map.insert(1, "a");
+    /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
+    /// assert_eq!(map.get_key_value(&2), None);
+    /// ```
+    #[unstable(feature = "map_get_key_value", issue = "49347")]
+    pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
+        where K: Borrow<Q>,
+              Q: Ord
+    {
+        match search::search_tree(self.root.as_ref(), k) {
+            Found(handle) => Some(handle.into_kv()),
+            GoDown(_) => None,
+        }
+    }
+
     /// Returns `true` if the map contains a value for the specified key.
     ///
     /// The key may be any borrowed form of the map's key type, but the ordering
index b18b38ec302460e4eb1f0fd9c84739dfac9252a3..f0bb781411fb4103026cf5d3d2954ef9761d8207 100644 (file)
@@ -1184,6 +1184,34 @@ pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
         self.search(k).map(|bucket| bucket.into_refs().1)
     }
 
+    /// Returns the key-value pair corresponding to the supplied key.
+    ///
+    /// The supplied key may be any borrowed form of the map's key type, but
+    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
+    /// the key type.
+    ///
+    /// [`Eq`]: ../../std/cmp/trait.Eq.html
+    /// [`Hash`]: ../../std/hash/trait.Hash.html
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(map_get_key_value)]
+    /// use std::collections::HashMap;
+    ///
+    /// let mut map = HashMap::new();
+    /// map.insert(1, "a");
+    /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
+    /// assert_eq!(map.get_key_value(&2), None);
+    /// ```
+    #[unstable(feature = "map_get_key_value", issue = "49347")]
+    pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
+        where K: Borrow<Q>,
+              Q: Hash + Eq
+    {
+        self.search(k).map(|bucket| bucket.into_refs())
+    }
+
     /// Returns true if the map contains a value for the specified key.
     ///
     /// The key may be any borrowed form of the map's key type, but