Skip to content

Commit d43c3cc

Browse files
Generic container: new Map private trait
Note: `BTreeMap::remove<Q>` and `BTreeMap::remove<Q>` both accept a more general `Q` rather than just `Self::Key`. If ever needed, `Map<Q>` would be possible (with the same bound on `Q` than `Self::Key`: `Ord` or `Eq + Hash`).
1 parent 8ed734b commit d43c3cc

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

src/generic_containers.rs

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
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+
}

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,8 @@ mod extrema_set;
186186
mod flatten_ok;
187187
mod format;
188188
#[cfg(feature = "use_alloc")]
189+
mod generic_containers;
190+
#[cfg(feature = "use_alloc")]
189191
mod group_map;
190192
#[cfg(feature = "use_alloc")]
191193
mod groupbylazy;

0 commit comments

Comments
 (0)