Skip to main content

ironwork_rt/
environment.rs

1//! The environment variables Micro Focus's and GnuCOBOL's ACCEPT ... FROM ENVIRONMENT, SET
2//! ENVIRONMENT and DISPLAY UPON ENVIRONMENT-NAME and ENVIRONMENT-VALUE read and set under
3//! `--compliance extended` (docs/compliance.md IWX0021, assumption C464): those `--env` gives the
4//! run, never the process's own.
5
6use std::collections::BTreeMap;
7
8#[derive(Clone, Debug, Default, PartialEq, Eq)]
9pub struct Environment {
10    pub variables: BTreeMap<String, String>,
11    /// The variable DISPLAY UPON ENVIRONMENT-NAME last named.
12    pub name: Option<String>,
13}
14
15impl Environment {
16    pub fn of(variables: BTreeMap<String, String>) -> Self {
17        Self { variables, name: None }
18    }
19
20    /// DISPLAY UPON ENVIRONMENT-NAME: the variable the next ENVIRONMENT-VALUE reads or sets, the
21    /// text without its trailing spaces.
22    pub fn name(&mut self, text: &str) {
23        self.name = Some(text.trim_end().to_owned());
24    }
25
26    /// DISPLAY UPON ENVIRONMENT-VALUE: the named variable takes the text without its trailing
27    /// spaces; with no variable named, nothing changes.
28    pub fn set(&mut self, text: &str) {
29        if let Some(name) = &self.name {
30            self.variables.insert(name.clone(), text.trim_end().to_owned());
31        }
32    }
33
34    /// ACCEPT ... FROM ENVIRONMENT-VALUE: the named variable's value, None when it is not set.
35    pub fn value(&self) -> Option<&str> {
36        self.variables.get(self.name.as_ref()?).map(String::as_str)
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn a_name_selects_the_variable_its_value_reads_and_sets() {
46        let mut e = Environment::of(BTreeMap::from([("IW_ONE".to_owned(), "hello".to_owned())]));
47        assert_eq!(e.value(), None);
48        e.name("IW_ONE    ");
49        assert_eq!(e.value(), Some("hello"));
50        e.name("IW_NEW");
51        assert_eq!(e.value(), None);
52        e.set("NEWVAL    ");
53        assert_eq!(e.value(), Some("NEWVAL"));
54    }
55}