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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use crate::hlua::{AnyHashableLuaValue, AnyLuaValue};

use std::collections;
use std::collections::HashMap;


#[derive(Debug, Default)]
pub struct LuaMap(HashMap<AnyHashableLuaValue, AnyLuaValue>);

impl LuaMap {
    #[inline]
    pub fn new() -> LuaMap {
        LuaMap::default()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    #[inline]
    pub fn insert<K: Into<String>, V: Into<AnyLuaValue>>(&mut self, k: K, v: V) {
        self.0.insert(AnyHashableLuaValue::LuaString(k.into()), v.into());
    }

    #[inline]
    pub fn insert_str<K: Into<String>, V: Into<String>>(&mut self, k: K, v: V) {
        self.0.insert(AnyHashableLuaValue::LuaString(k.into()), AnyLuaValue::LuaString(v.into()));
    }

    #[inline]
    pub fn insert_num<K: Into<String>>(&mut self, k: K, v: f64) {
        self.0.insert(AnyHashableLuaValue::LuaString(k.into()), AnyLuaValue::LuaNumber(v));
    }
}

impl IntoIterator for LuaMap {
    type Item = (AnyHashableLuaValue, AnyLuaValue);
    type IntoIter = collections::hash_map::IntoIter<AnyHashableLuaValue, AnyLuaValue>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl From<HashMap<String, String>> for LuaMap {
    fn from(x: HashMap<String, String>) -> LuaMap {
        let mut map = LuaMap::new();
        for (k, v) in x {
            map.insert_str(k, v);
        }
        map
    }
}

impl From<HashMap<AnyHashableLuaValue, AnyLuaValue>> for LuaMap {
    fn from(x: HashMap<AnyHashableLuaValue, AnyLuaValue>) -> LuaMap {
        LuaMap(x)
    }
}

impl From<Vec<(AnyLuaValue, AnyLuaValue)>> for LuaMap {
    fn from(x: Vec<(AnyLuaValue, AnyLuaValue)>) -> LuaMap {
        let mut map = LuaMap::new();

        for (k, v) in x {
            // TODO: handle unknown types
            if let AnyLuaValue::LuaString(k) = k {
                map.insert(k, v);
            }
        }

        map
    }
}

impl From<LuaMap> for HashMap<AnyHashableLuaValue, AnyLuaValue> {
    fn from(x: LuaMap) -> HashMap<AnyHashableLuaValue, AnyLuaValue> {
        x.0
    }
}

impl From<LuaMap> for AnyLuaValue {
    fn from(x: LuaMap) -> AnyLuaValue {
        AnyLuaValue::LuaArray(
            x.into_iter()
                .filter_map(|(k, v)| {
                    match k {
                        AnyHashableLuaValue::LuaString(x) => Some((AnyLuaValue::LuaString(x), v)),
                        _ => None, // TODO: unknown types are discarded
                    }
                })
                .collect()
        )
    }
}