1#[derive(Clone, Debug)]
3pub struct Context<K, T>(Vec<(K, T)>);
4
5impl<K: Eq + Clone, T: Clone> Context<K, T> {
6 pub fn empty() -> Context<K, T> {
7 Context(vec![])
8 }
9
10 pub fn from(ctx: Vec<(K, T)>) -> Context<K, T> {
11 Context(ctx)
12 }
13
14 pub fn lookup(&self, v: &K) -> Option<T> {
15 for (v0, t) in &self.0 {
16 if v0 == v {
17 return Some(t.clone());
18 }
19 }
20 None
21 }
22
23 pub fn extend(&self, v: K, t: T) -> Context<K, T> {
24 let mut result = self.clone();
25 result.0.push((v, t));
26 result
27 }
28
29 pub fn extend_from(&self, another: &Context<K, T>) -> Context<K, T> {
30 let mut result = self.clone();
31 for (v, t) in another.0.iter() {
32 result.0.push((v.clone(), t.clone()));
33 }
34 result
35 }
36
37 pub fn into_inner(self) -> Vec<(K, T)> {
38 self.0
39 }
40}
41
42impl<K, T> std::ops::Deref for Context<K, T> {
43 type Target = Vec<(K, T)>;
44
45 fn deref(&self) -> &Self::Target {
46 &self.0
47 }
48}
49
50impl<K: std::fmt::Display, T: std::fmt::Display> std::fmt::Display for Context<K, T> {
51 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
52 write!(f, "[")?;
53 for (i, (name, v)) in self.0.iter().enumerate() {
54 write!(f, "{name} : {v}")?;
55 if i + 1 < self.0.len() {
56 write!(f, ", ")?;
57 }
58 }
59 write!(f, "]")?;
60 Ok(())
61 }
62}