|
| 1 | +//! **Private** generalizations of containers: |
| 2 | +//! - `Map`: `BTreeMap` and `HashMap` (any hasher). |
| 3 | +
|
| 4 | +#![cfg(feature = "use_alloc")] |
| 5 | + |
| 6 | +use alloc::collections::BTreeMap; |
| 7 | +#[cfg(feature = "use_std")] |
| 8 | +use core::hash::{BuildHasher, Hash}; |
| 9 | +#[cfg(feature = "use_std")] |
| 10 | +use std::collections::HashMap; |
| 11 | + |
| 12 | +pub trait Map { |
| 13 | + type Key; |
| 14 | + type Value; |
| 15 | + fn is_empty(&self) -> bool; |
| 16 | + fn clear(&mut self); |
| 17 | + fn insert(&mut self, key: Self::Key, value: Self::Value) -> Option<Self::Value>; |
| 18 | + fn remove(&mut self, key: &Self::Key) -> Option<Self::Value>; |
| 19 | + fn entry_or_default(&mut self, key: Self::Key) -> &mut Self::Value |
| 20 | + where |
| 21 | + Self::Value: Default; |
| 22 | +} |
| 23 | + |
| 24 | +impl<K, V> Map for BTreeMap<K, V> |
| 25 | +where |
| 26 | + K: Ord, |
| 27 | +{ |
| 28 | + type Key = K; |
| 29 | + type Value = V; |
| 30 | + fn is_empty(&self) -> bool { |
| 31 | + self.is_empty() |
| 32 | + } |
| 33 | + fn clear(&mut self) { |
| 34 | + self.clear() |
| 35 | + } |
| 36 | + fn insert(&mut self, key: K, value: V) -> Option<V> { |
| 37 | + self.insert(key, value) |
| 38 | + } |
| 39 | + fn remove(&mut self, key: &K) -> Option<V> { |
| 40 | + self.remove(key) |
| 41 | + } |
| 42 | + fn entry_or_default(&mut self, key: K) -> &mut V |
| 43 | + where |
| 44 | + V: Default, |
| 45 | + { |
| 46 | + self.entry(key).or_default() |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +#[cfg(feature = "use_std")] |
| 51 | +impl<K, V, S> Map for HashMap<K, V, S> |
| 52 | +where |
| 53 | + K: Eq + Hash, |
| 54 | + S: BuildHasher, |
| 55 | +{ |
| 56 | + type Key = K; |
| 57 | + type Value = V; |
| 58 | + fn is_empty(&self) -> bool { |
| 59 | + self.is_empty() |
| 60 | + } |
| 61 | + fn clear(&mut self) { |
| 62 | + self.clear() |
| 63 | + } |
| 64 | + fn insert(&mut self, key: K, value: V) -> Option<V> { |
| 65 | + self.insert(key, value) |
| 66 | + } |
| 67 | + fn remove(&mut self, key: &K) -> Option<V> { |
| 68 | + self.remove(key) |
| 69 | + } |
| 70 | + fn entry_or_default(&mut self, key: K) -> &mut V |
| 71 | + where |
| 72 | + V: Default, |
| 73 | + { |
| 74 | + self.entry(key).or_default() |
| 75 | + } |
| 76 | +} |
0 commit comments