1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::{
cmp::Eq,
collections::{hash_map::DefaultHasher, HashMap},
hash::{Hash, Hasher},
};
pub struct GraphArena<T>
where
T: Sized + Hash + Eq,
{
data: Vec<T>,
mapping: HashMap<u64, usize>,
}
impl<T> GraphArena<T>
where
T: Sized + Hash + Eq,
{
pub fn new() -> Self {
GraphArena {
data: Vec::new(),
mapping: HashMap::new(),
}
}
pub fn get(&self, key: usize) -> &T {
&self.data[key]
}
pub fn insert(&mut self, item: T) -> usize {
let hashsum = hash(&item);
if let Some(key) = self.mapping.get(&hashsum) {
return *key;
}
let index = self.data.len();
self.data.push(item);
self.mapping.insert(hashsum, index);
index
}
}
impl<T> IntoIterator for GraphArena<T>
where
T: Sized + Hash + Eq,
{
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.data.into_iter()
}
}
fn hash<T>(item: &T) -> u64
where
T: Hash,
{
let mut hasher = DefaultHasher::new();
item.hash(&mut hasher);
hasher.finish()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_hash() {
let obj = (123, 456);
let h1 = hash(&obj);
let h2 = hash(&obj);
assert_eq!(h1, h2);
}
}