bitsy_script/
vars.rs

1use crate::*;
2use alloc::string::String;
3use alloc::string::ToString;
4use hashbrown::HashMap;
5
6#[derive(Debug, Default, Clone, PartialEq)]
7pub enum Val {
8    #[default]
9    Undef,
10    I(i16),
11    S(String),
12    F(f32),
13}
14
15impl Val {
16    pub fn new(s: &str) -> Val {
17        let s = s.trim_ascii();
18        if s == "true" {
19            return Val::I(1);
20        }
21        if s == "false" {
22            return Val::I(0);
23        }
24        if let Ok(i) = s.parse::<i16>() {
25            return Val::I(i);
26        }
27        if let Ok(f) = s.parse::<f32>() {
28            return Val::F(f);
29        }
30        Val::S(unquote(s).to_string())
31    }
32}
33
34fn unquote(v: &str) -> &str {
35    let n_quotes = v.chars().filter(|ch| *ch == '"').count();
36    if n_quotes != 2 {
37        return v;
38    }
39    if v.starts_with('"') && v.ends_with('"') {
40        let v = &v[1..];
41        &v[..v.len() - 1]
42    } else {
43        v
44    }
45}
46
47#[derive(Default, Clone, Debug)]
48pub struct Vars {
49    items: HashMap<String, Val>,
50}
51
52impl Vars {
53    pub fn new() -> Self {
54        Self::default()
55    }
56
57    pub fn set(&mut self, name: String, v: Val) {
58        self.items.insert(name, v);
59    }
60
61    pub fn get(&self, name: &str) -> &Val {
62        self.items.get(name).unwrap_or(&Val::Undef)
63    }
64}