1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use std::collections::HashMap;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum Error {
    #[error("data store disconnected")]
    NoKeyGiven,
}

pub fn interpret(code: &str) -> Result<HashMap<&str, &str>, Error> {
    let mut hashmap: HashMap<&str, &str> = HashMap::new();

    for line in code.lines() {
        match line.rsplit_once(':') {
            Some((key, value)) => {
                if key.is_empty() {
                    return Err(Error::NoKeyGiven);
                }

                hashmap.insert(key, value);
            }

            None => {
                return Err(Error::NoKeyGiven);
            }
        };
    }

    Ok(hashmap)
}

#[cfg(test)]
mod tests {
    use crate::interpret;

    #[test]
    fn parsing_works() {
        let config =
            interpret("rust_is_awesome:true\ndeno_is_uncool:false\nname_of_cute_crab:Ferris!")
                .unwrap();

        assert_eq!(config.get("rust_is_awesome").unwrap(), &"true");
        assert_eq!(config.get("deno_is_uncool").unwrap(), &"false");
        assert_eq!(config.get("name_of_cute_crab").unwrap(), &"Ferris!");
    }

    #[test]
    fn colon_in_key() {
        let config =
            interpret("this:key:has:a:colon:in:its:keyname:THIS IS THE ACTUAL VALUE OF THE KEY")
                .unwrap();

        assert_eq!(
            config.get("this:key:has:a:colon:in:its:keyname").unwrap(),
            &"THIS IS THE ACTUAL VALUE OF THE KEY"
        );
    }
}