fera_graph/props/
hashmap.rs1use prelude::*;
6
7use std::collections::hash_map::RandomState;
8use std::collections::HashMap;
9use std::hash::BuildHasher;
10use std::ops::{Index, IndexMut};
11
12pub struct HashMapProp<I: GraphItem, T: Clone, S = RandomState> {
16    default: T,
17    map: HashMap<I, T, S>,
18}
19
20impl<I, T> HashMapProp<I, T>
21where
22    I: GraphItem,
23    T: Clone,
24{
25    pub fn new(default: T) -> Self {
31        HashMapProp {
32            default: default,
33            map: HashMap::default(),
34        }
35    }
36}
37
38impl<I, T, S> HashMapProp<I, T, S>
39where
40    I: GraphItem,
41    T: Clone,
42    S: BuildHasher,
43{
44    pub fn with_hasher(default: T, hasher: S) -> Self {
45        HashMapProp {
46            default: default,
47            map: HashMap::with_hasher(hasher),
48        }
49    }
50}
51
52impl<I, T, S> Index<I> for HashMapProp<I, T, S>
53where
54    I: GraphItem,
55    T: Clone,
56    S: BuildHasher,
57{
58    type Output = T;
59
60    #[inline]
61    fn index(&self, v: I) -> &Self::Output {
62        self.map.get(&v).unwrap_or(&self.default)
63    }
64}
65
66impl<I, T, S> IndexMut<I> for HashMapProp<I, T, S>
67where
68    I: GraphItem,
69    T: Clone,
70    S: BuildHasher,
71{
72    #[inline]
73    fn index_mut(&mut self, v: I) -> &mut Self::Output {
74        let default = &self.default;
75        self.map.entry(v).or_insert_with(|| default.clone())
76    }
77}
78
79impl<G, T, S> VertexPropMutNew<G, T> for HashMapProp<Vertex<G>, T, S>
80where
81    G: WithVertex,
82    T: Clone,
83    S: BuildHasher + Default,
84{
85    fn new_vertex_prop(_: &G, value: T) -> Self
86    where
87        T: Clone,
88    {
89        Self::with_hasher(value, S::default())
90    }
91}
92
93impl<G, T, S> EdgePropMutNew<G, T> for HashMapProp<Edge<G>, T, S>
94where
95    G: WithEdge,
96    T: Clone,
97    S: BuildHasher + Default,
98{
99    fn new_edge_prop(_: &G, value: T) -> Self
100    where
101        T: Clone,
102    {
103        Self::with_hasher(value, S::default())
104    }
105}