1#![doc = include_str!("../README.md")]
2
3use std::{borrow::Borrow, collections::HashMap, hash::Hash};
4
5#[derive(Clone, Debug)]
6pub struct TrainMap<'a, K, V> {
7 map: HashMap<K, V>,
8 parent: Option<&'a TrainMap<'a, K, V>>,
9}
10
11impl<'a, K: Eq + Hash, V> TrainMap<'a, K, V> {
12 pub fn new() -> Self {
13 Self {
14 map: Default::default(),
15 parent: None,
16 }
17 }
18
19 pub fn with_capacity(capacity: usize) -> Self {
20 Self {
21 map: HashMap::with_capacity(capacity),
22 parent: None,
23 }
24 }
25
26 pub fn get<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> Option<&V>
27 where
28 K: Borrow<Q>,
29 {
30 if let Some(value) = self.map.get(key) {
31 Some(value)
32 } else if let Some(parent) = self.parent {
33 parent.get(key)
34 } else {
35 None
36 }
37 }
38
39 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
40 self.map.insert(key, value)
41 }
42
43 pub fn fork(&'a self) -> Self {
44 Self {
45 map: Default::default(),
46 parent: Some(self),
47 }
48 }
49}
50
51impl<'a, K: Eq + Hash, V> Default for TrainMap<'a, K, V> {
52 fn default() -> Self {
53 Self::new()
54 }
55}
56
57impl<'a, K: Eq + Hash, V> Extend<(K, V)> for TrainMap<'a, K, V> {
58 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iterator: T) {
59 self.map.extend(iterator)
60 }
61}