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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
use std::{
    collections::hash_map::RandomState,
    fmt::Debug,
    hash::BuildHasher,
    sync::{Mutex, MutexGuard, PoisonError},
};

use crate::{budmap::BudMap, symbol::Symbol, DynamicValue, Value};

use super::{FaultKind, PoppedValues};

/// A wrapper for [`std::collections::HashMap<Value,Value>`] that prevents using
/// a [`Value`] that does not support hashing by returning an error.
///
/// This type uses a [`Mutex`] for interior mutability.
pub struct HashMap<State = RandomState>(Mutex<BudMap<Value, Value, State>>)
where
    State: BuildHasher;

impl Default for HashMap<RandomState> {
    fn default() -> Self {
        Self::new()
    }
}

impl<State> Clone for HashMap<State>
where
    State: Clone + BuildHasher,
{
    fn clone(&self) -> Self {
        Self(Mutex::new(self.map().clone()))
    }
}

// impl<State> From<std::collections::HashMap<Value, Value, State>> for HashMap<State>
// where
//     State: BuildHasher,
// {
//     fn from(collection: std::collections::HashMap<Value, Value, State>) -> Self {
//         Self(Mutex::new(collection))
//     }
// }

impl HashMap<RandomState> {
    /// Returns a new, empty hash map.
    ///
    /// Equivalent to [`std::collections::HashMap::new()`].
    #[must_use]
    pub fn new() -> Self {
        Self(Mutex::new(BudMap::default()))
    }

    // /// Returns a hash map that can contain at least `capacity` without
    // /// reallocation.
    // ///
    // /// Equivalent to [`std::collections::HashMap::with_capacity()`].
    // #[must_use]
    // pub fn with_capacity(capacity: usize) -> Self {
    //     Self(Mutex::new(std::collections::HashMap::with_capacity(
    //         capacity,
    //     )))
    // }
}

impl<State> HashMap<State>
where
    State: BuildHasher,
{
    // /// Returns a new, empty hash map that uses `hash_builder` to initialize the
    // /// hasher used for this map.
    // ///
    // /// Equivalent to [`std::collections::HashMap::with_hasher()`].
    // #[must_use]
    // pub fn with_hasher(hash_builder: State) -> Self {
    //     Self(Mutex::new(std::collections::HashMap::with_hasher(
    //         hash_builder,
    //     )))
    // }

    // /// Returns a hash map that can contain at least `capacity` without
    // /// reallocation, using `hash_builder` to initialize the hasher used for
    // /// this map.
    // ///
    // /// Equivalent to [`std::collections::HashMap::with_capacity_and_hasher()`].
    // #[must_use]
    // pub fn with_capacity_and_hasher(capacity: usize, hash_builder: State) -> Self {
    //     Self(Mutex::new(
    //         std::collections::HashMap::with_capacity_and_hasher(capacity, hash_builder),
    //     ))
    // }

    fn map(&self) -> MutexGuard<'_, BudMap<Value, Value, State>> {
        self.0.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Returns the number of items contained.
    pub fn len(&self) -> usize {
        self.map().len()
    }

    /// Returns true if this map contains no items.
    pub fn is_empty(&self) -> bool {
        self.map().is_empty()
    }

    /// Inserts a key-value pair into the map.
    ///
    /// Equivalent to [`std::collections::HashMap::insert()`], except this
    /// function checks that `key.implements_hash()` returns true. If it does
    /// not, [`FaultKind::ValueCannotBeHashed`] will be returned.
    pub fn insert(&self, k: Value, v: Value) -> Result<Option<Value>, FaultKind> {
        let mut map = self.map();
        Ok(map.insert(check_hashable(k)?, v))
    }

    /// Returns the value associated with `key`, if present.
    pub fn get(&self, key: &Value) -> Option<Value> {
        let map = self.map();
        map.get(key).cloned()
    }

    /// Removes the value associated with `key`, if present.
    pub fn remove(&self, key: &Value) -> Option<Value> {
        let mut map = self.map();
        map.remove(key)
    }

    /// Extracts the contained collection type.
    pub fn into_inner(self) -> BudMap<Value, Value, State> {
        self.0.into_inner().unwrap_or_else(PoisonError::into_inner)
    }
}

impl<'a> TryFrom<PoppedValues<'a>> for HashMap<RandomState> {
    type Error = FaultKind;

    fn try_from(mut values: PoppedValues<'a>) -> Result<Self, Self::Error> {
        if values.len() & 1 == 1 {
            return Err(FaultKind::dynamic(
                "odd number of arguments passed to map constructor",
            ));
        }
        let mut map = BudMap::with_capacity(values.len() / 2);

        while let Some(key) = values.next() {
            let value = values.next().expect("checked for odd length");

            map.insert(check_hashable(key)?, value);
        }

        Ok(Self(Mutex::new(map)))
    }
}

fn check_hashable(value: Value) -> Result<Value, FaultKind> {
    if value.implements_hash() {
        Ok(value)
    } else {
        Err(FaultKind::ValueCannotBeHashed(value))
    }
}

impl<State> Debug for HashMap<State>
where
    State: BuildHasher + Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl<State> DynamicValue for HashMap<State>
where
    State: BuildHasher + Debug + Clone + Send + Sync + 'static,
{
    fn is_truthy(&self) -> bool {
        !self.map().is_empty()
    }

    fn kind(&self) -> Symbol {
        Symbol::from("Map")
    }

    fn partial_eq(&self, other: &Value) -> Option<bool> {
        if let Some(other) = other.as_dynamic::<Self>() {
            let lhs = self.map();
            let rhs = other.map();
            if lhs.len() == rhs.len() {
                for (lkey, lvalue) in lhs.iter() {
                    if rhs.get(lkey).map_or(true, |rvalue| lvalue != rvalue) {
                        return Some(false);
                    }
                }
                Some(true)
            } else {
                Some(false)
            }
        } else {
            None
        }
    }

    fn call(&self, name: &Symbol, args: &mut PoppedValues<'_>) -> Result<Value, FaultKind> {
        match name.as_str() {
            "count" => {
                args.verify_empty()?;
                let len = i64::try_from(self.map().len())
                    .map_err(|_| FaultKind::ValueOutOfRange("count"))?;
                Ok(Value::Integer(len))
            }
            "insert" => {
                let key = args
                    .next()
                    .ok_or_else(|| FaultKind::ArgumentMissing(Symbol::from("key")))?;
                let value = args
                    .next()
                    .ok_or_else(|| FaultKind::ArgumentMissing(Symbol::from("value")))?;
                args.verify_empty()?;

                let contained_value = self.insert(key, value)?.unwrap_or_default();

                Ok(contained_value)
            }
            "get" => {
                let key = args
                    .next()
                    .ok_or_else(|| FaultKind::ArgumentMissing(Symbol::from("key")))?;
                args.verify_empty()?;

                let contained_value = self.get(&key).unwrap_or_default();

                Ok(contained_value)
            }
            "remove" => {
                let key = args
                    .next()
                    .ok_or_else(|| FaultKind::ArgumentMissing(Symbol::from("key")))?;
                args.verify_empty()?;

                let contained_value = self.remove(&key).unwrap_or_default();

                Ok(contained_value)
            }
            _ => Err(FaultKind::UnknownFunction {
                kind: super::ValueKind::Dynamic(self.kind()),
                name: name.clone(),
            }),
        }
    }

    fn to_source(&self) -> Option<String> {
        None
    }
}