wasmonkey/
map.rs

1use std::collections::HashMap;
2use std::fs::File;
3use std::io::prelude::*;
4use std::path::Path;
5
6use crate::errors::*;
7
8#[derive(Clone, Debug, Default, Serialize)]
9pub struct PatchedBuiltinsMap {
10    pub env: HashMap<String, String>,
11}
12
13impl PatchedBuiltinsMap {
14    pub fn with_capacity(capacity: usize) -> Self {
15        PatchedBuiltinsMap {
16            env: HashMap::with_capacity(capacity),
17        }
18    }
19
20    pub fn insert(&mut self, name: String, imported_name: String) -> Option<String> {
21        self.env.insert(name, imported_name)
22    }
23
24    pub fn write_to_file<P: AsRef<Path>>(
25        &self,
26        builtins_map_path: P,
27        original_names: bool,
28    ) -> Result<(), WError> {
29        let mut map_with_original_names;
30        let map = if original_names {
31            self
32        } else {
33            map_with_original_names = PatchedBuiltinsMap::default();
34            for imported_name in self.env.values() {
35                map_with_original_names
36                    .env
37                    .insert(imported_name.clone(), imported_name.clone());
38            }
39            &map_with_original_names
40        };
41        let json = serde_json::to_string_pretty(map).map_err(|_| WError::ParseError)?;
42        File::create(builtins_map_path)?.write_all(json.as_bytes())?;
43        Ok(())
44    }
45
46    pub fn builtins_map(
47        &self,
48        module: &str,
49        original_names: bool,
50    ) -> Result<HashMap<String, String>, Error> {
51        if module != "env" {
52            bail!(WError::UsageError("Empty module"));
53        }
54        if original_names {
55            return Ok(self.env.clone());
56        }
57        let mut env_map_with_original_names = HashMap::new();
58        for imported_name in self.env.values() {
59            env_map_with_original_names.insert(imported_name.clone(), imported_name.clone());
60        }
61        Ok(env_map_with_original_names)
62    }
63}