1 use std::any::{Any, TypeId};
2 use std::borrow::Borrow;
3 use std::cell::RefCell;
4 use std::cmp::{Ord, Ordering, PartialOrd};
5 use std::collections::HashMap;
6 use std::convert::AsRef;
9 use std::hash::{Hash, Hasher};
10 use std::marker::PhantomData;
13 use std::path::{Path, PathBuf};
16 // FIXME: replace with std::lazy after it gets stabilized and reaches beta
17 use once_cell::sync::Lazy;
19 use crate::builder::Step;
21 pub struct Interned<T>(usize, PhantomData<*const T>);
23 impl Default for Interned<String> {
24 fn default() -> Self {
25 INTERNER.intern_string(String::default())
29 impl Default for Interned<PathBuf> {
30 fn default() -> Self {
31 INTERNER.intern_path(PathBuf::default())
35 impl<T> Copy for Interned<T> {}
36 impl<T> Clone for Interned<T> {
37 fn clone(&self) -> Interned<T> {
42 impl<T> PartialEq for Interned<T> {
43 fn eq(&self, other: &Self) -> bool {
47 impl<T> Eq for Interned<T> {}
49 impl PartialEq<str> for Interned<String> {
50 fn eq(&self, other: &str) -> bool {
54 impl<'a> PartialEq<&'a str> for Interned<String> {
55 fn eq(&self, other: &&str) -> bool {
59 impl<'a, T> PartialEq<&'a Interned<T>> for Interned<T> {
60 fn eq(&self, other: &&Self) -> bool {
64 impl<'a, T> PartialEq<Interned<T>> for &'a Interned<T> {
65 fn eq(&self, other: &Interned<T>) -> bool {
70 unsafe impl<T> Send for Interned<T> {}
71 unsafe impl<T> Sync for Interned<T> {}
73 impl fmt::Display for Interned<String> {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 impl fmt::Debug for Interned<String> {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 f.write_fmt(format_args!("{:?}", s))
86 impl fmt::Debug for Interned<PathBuf> {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 let s: &Path = &*self;
89 f.write_fmt(format_args!("{:?}", s))
93 impl Hash for Interned<String> {
94 fn hash<H: Hasher>(&self, state: &mut H) {
95 let l = INTERNER.strs.lock().unwrap();
96 l.get(*self).hash(state)
100 impl Hash for Interned<PathBuf> {
101 fn hash<H: Hasher>(&self, state: &mut H) {
102 let l = INTERNER.paths.lock().unwrap();
103 l.get(*self).hash(state)
107 impl Deref for Interned<String> {
109 fn deref(&self) -> &'static str {
110 let l = INTERNER.strs.lock().unwrap();
111 unsafe { mem::transmute::<&str, &'static str>(l.get(*self)) }
115 impl Deref for Interned<PathBuf> {
117 fn deref(&self) -> &'static Path {
118 let l = INTERNER.paths.lock().unwrap();
119 unsafe { mem::transmute::<&Path, &'static Path>(l.get(*self)) }
123 impl AsRef<Path> for Interned<PathBuf> {
124 fn as_ref(&self) -> &'static Path {
125 let l = INTERNER.paths.lock().unwrap();
126 unsafe { mem::transmute::<&Path, &'static Path>(l.get(*self)) }
130 impl AsRef<Path> for Interned<String> {
131 fn as_ref(&self) -> &'static Path {
132 let l = INTERNER.strs.lock().unwrap();
133 unsafe { mem::transmute::<&Path, &'static Path>(l.get(*self).as_ref()) }
137 impl AsRef<OsStr> for Interned<PathBuf> {
138 fn as_ref(&self) -> &'static OsStr {
139 let l = INTERNER.paths.lock().unwrap();
140 unsafe { mem::transmute::<&OsStr, &'static OsStr>(l.get(*self).as_ref()) }
144 impl AsRef<OsStr> for Interned<String> {
145 fn as_ref(&self) -> &'static OsStr {
146 let l = INTERNER.strs.lock().unwrap();
147 unsafe { mem::transmute::<&OsStr, &'static OsStr>(l.get(*self).as_ref()) }
151 impl PartialOrd<Interned<String>> for Interned<String> {
152 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
153 let l = INTERNER.strs.lock().unwrap();
154 l.get(*self).partial_cmp(l.get(*other))
158 impl Ord for Interned<String> {
159 fn cmp(&self, other: &Self) -> Ordering {
160 let l = INTERNER.strs.lock().unwrap();
161 l.get(*self).cmp(l.get(*other))
165 struct TyIntern<T: Clone + Eq> {
167 set: HashMap<T, Interned<T>>,
170 impl<T: Hash + Clone + Eq> Default for TyIntern<T> {
171 fn default() -> Self {
172 TyIntern { items: Vec::new(), set: Default::default() }
176 impl<T: Hash + Clone + Eq> TyIntern<T> {
177 fn intern_borrow<B>(&mut self, item: &B) -> Interned<T>
179 B: Eq + Hash + ToOwned<Owned = T> + ?Sized,
182 if let Some(i) = self.set.get(&item) {
185 let item = item.to_owned();
186 let interned = Interned(self.items.len(), PhantomData::<*const T>);
187 self.set.insert(item.clone(), interned);
188 self.items.push(item);
192 fn intern(&mut self, item: T) -> Interned<T> {
193 if let Some(i) = self.set.get(&item) {
196 let interned = Interned(self.items.len(), PhantomData::<*const T>);
197 self.set.insert(item.clone(), interned);
198 self.items.push(item);
202 fn get(&self, i: Interned<T>) -> &T {
208 pub struct Interner {
209 strs: Mutex<TyIntern<String>>,
210 paths: Mutex<TyIntern<PathBuf>>,
214 pub fn intern_str(&self, s: &str) -> Interned<String> {
215 self.strs.lock().unwrap().intern_borrow(s)
217 pub fn intern_string(&self, s: String) -> Interned<String> {
218 self.strs.lock().unwrap().intern(s)
221 pub fn intern_path(&self, s: PathBuf) -> Interned<PathBuf> {
222 self.paths.lock().unwrap().intern(s)
226 pub static INTERNER: Lazy<Interner> = Lazy::new(Interner::default);
228 /// This is essentially a `HashMap` which allows storing any type in its input and
229 /// any type in its output. It is a write-once cache; values are never evicted,
230 /// which means that references to the value can safely be returned from the
237 Box<dyn Any>, // actually a HashMap<Step, Interned<Step::Output>>
243 pub fn new() -> Cache {
244 Cache(RefCell::new(HashMap::new()))
247 pub fn put<S: Step>(&self, step: S, value: S::Output) {
248 let mut cache = self.0.borrow_mut();
249 let type_id = TypeId::of::<S>();
250 let stepcache = cache
252 .or_insert_with(|| Box::new(HashMap::<S, S::Output>::new()))
253 .downcast_mut::<HashMap<S, S::Output>>()
254 .expect("invalid type mapped");
255 assert!(!stepcache.contains_key(&step), "processing {:?} a second time", step);
256 stepcache.insert(step, value);
259 pub fn get<S: Step>(&self, step: &S) -> Option<S::Output> {
260 let mut cache = self.0.borrow_mut();
261 let type_id = TypeId::of::<S>();
262 let stepcache = cache
264 .or_insert_with(|| Box::new(HashMap::<S, S::Output>::new()))
265 .downcast_mut::<HashMap<S, S::Output>>()
266 .expect("invalid type mapped");
267 stepcache.get(step).cloned()
273 pub fn all<S: Ord + Copy + Step>(&mut self) -> Vec<(S, S::Output)> {
274 let cache = self.0.get_mut();
275 let type_id = TypeId::of::<S>();
278 .map(|b| b.downcast::<HashMap<S, S::Output>>().expect("correct type"))
279 .map(|m| m.into_iter().collect::<Vec<_>>())
280 .unwrap_or_default();
281 v.sort_by_key(|&(a, _)| a);
285 pub fn contains<S: Step>(&self) -> bool {
286 self.0.borrow().contains_key(&TypeId::of::<S>())