Skip to main content

lift_core/
interning.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
5pub struct StringId(pub u32);
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
8pub struct TypeInternId(pub u32);
9
10#[derive(Debug, Default)]
11pub struct StringInterner {
12    map: HashMap<String, StringId>,
13    strings: Vec<String>,
14}
15
16impl StringInterner {
17    pub fn new() -> Self {
18        Self::default()
19    }
20
21    pub fn intern(&mut self, s: &str) -> StringId {
22        if let Some(&id) = self.map.get(s) {
23            return id;
24        }
25        let id = StringId(self.strings.len() as u32);
26        self.strings.push(s.to_string());
27        self.map.insert(s.to_string(), id);
28        id
29    }
30
31    pub fn resolve(&self, id: StringId) -> &str {
32        &self.strings[id.0 as usize]
33    }
34
35    pub fn len(&self) -> usize {
36        self.strings.len()
37    }
38
39    pub fn is_empty(&self) -> bool {
40        self.strings.is_empty()
41    }
42}
43
44#[derive(Debug, Default)]
45pub struct TypeInterner {
46    map: HashMap<crate::types::CoreType, TypeInternId>,
47    types: Vec<crate::types::CoreType>,
48}
49
50impl TypeInterner {
51    pub fn new() -> Self {
52        Self::default()
53    }
54
55    pub fn intern(&mut self, ty: crate::types::CoreType) -> crate::types::TypeId {
56        if let Some(&id) = self.map.get(&ty) {
57            return crate::types::TypeId(id);
58        }
59        let id = TypeInternId(self.types.len() as u32);
60        self.types.push(ty.clone());
61        self.map.insert(ty, id);
62        crate::types::TypeId(id)
63    }
64
65    pub fn resolve(&self, id: crate::types::TypeId) -> &crate::types::CoreType {
66        &self.types[id.0 .0 as usize]
67    }
68
69    pub fn len(&self) -> usize {
70        self.types.len()
71    }
72
73    pub fn is_empty(&self) -> bool {
74        self.types.is_empty()
75    }
76}