1use std::hash::{Hash, Hasher};
2use std::cell::{self, RefCell};
3use std::collections::HashSet;
4
5use typed_arena::Arena;
6
7pub struct Context<T> {
8 store: Arena<T>,
9 vec: RefCell<Vec<*const T>>, }
11
12impl<T> Context<T> {
13 pub fn new() -> Self {
14 Context {
15 store: Arena::new(),
16 vec: RefCell::new(vec![])
17 }
18 }
19 pub fn push(&self, variant: T) -> &T {
20 let id = self.store.alloc(variant);
21 self.vec.borrow_mut().push(id);
22 id
23 }
24 pub fn len(&self) -> usize {
25 self.vec.borrow().len()
26 }
27
28 pub fn iter(&self) -> ContextIter<T> {
29 use std::mem::transmute;
30 ContextIter {
31 vec: unsafe {
32 transmute::<cell::Ref<Vec<*const T>>,
33 cell::Ref<Vec<&T>>>(self.vec.borrow())
34 },
35 idx: 0,
36 }
37 }
38
39 pub fn get(&self, idx: usize) -> Option<&T> {
40 if idx < self.len() {
41 Some(unsafe { &*self.vec.borrow()[idx] })
42 } else {
43 None
44 }
45 }
46}
47
48impl<'a, T> IntoIterator for &'a Context<T> {
49 type Item = &'a T;
50 type IntoIter = ContextIter<'a, T>;
51 fn into_iter(self) -> Self::IntoIter {
52 self.iter()
53 }
54}
55
56pub struct ContextIter<'a, T: 'a> {
57 vec: cell::Ref<'a, Vec<&'a T>>,
58 idx: usize,
59}
60
61impl<'a, T> Iterator for ContextIter<'a, T> {
62 type Item = &'a T;
63
64 fn next(&mut self) -> Option<&'a T> {
65 if self.idx >= self.vec.len() {
66 None
67 } else {
68 let ret = Some(self.vec[self.idx]);
69 self.idx += 1;
70 ret
71 }
72 }
73}
74
75pub struct Interner<T> {
76 store: Arena<T>,
77 refs: RefCell<HashSet<HashPtr<T>>>,
78}
79
80impl<T: Hash + Eq> Interner<T> {
81 pub fn new() -> Self {
82 Interner {
83 store: Arena::new(),
84 refs: RefCell::new(HashSet::new()),
85 }
86 }
87
88 pub fn get(&self, variant: T) -> &T {
89 if let Some(id) = self.refs.borrow().get(&HashPtr(&variant)) {
90 return unsafe { &*id.0 };
91 }
92
93 let id = self.store.alloc(variant);
94 self.refs.borrow_mut().insert(HashPtr(id));
95 id
96 }
97}
98
99struct HashPtr<T>(*const T);
102
103impl<T> Copy for HashPtr<T> {}
104impl<T> Clone for HashPtr<T> { fn clone(&self) -> Self { *self } }
105
106impl<T: Hash> Hash for HashPtr<T> {
107 fn hash<H>(&self, state: &mut H) where H: Hasher {
108 unsafe {
109 (*self.0).hash(state)
110 }
111 }
112}
113
114impl<T: PartialEq> PartialEq for HashPtr<T> {
115 fn eq(&self, rhs: &Self) -> bool {
116 unsafe {
117 (*self.0) == (*rhs.0)
118 }
119 }
120}
121
122impl<T: Eq> Eq for HashPtr<T> { }