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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Provides Rust equivalents of [collections.abc] Python classes.
//!
//! Creating a custom container is achived in Python via extending a `collections.abc.*` class:
//! ```python
//! class MySeq(collections.abc.Sequence):
//!     def __getitem__(self, index):  ...  # Required abstract method
//!     def __len__(self):  ...             # Required abstract method
//! ```
//! You just need to implement required abstract methods and you get
//! extra mixin methods for free.
//!
//! Ideally we also want to just extend abstract base classes from Python but
//! it is not supported yet: <https://github.com/PyO3/pyo3/issues/991>.
//!
//! Until then, we are providing traits with the required methods and, macros that
//! takes those types that implement those traits and provides mixin methods for them.
//!
//! [collections.abc]: https://docs.python.org/3/library/collections.abc.html

use pyo3::PyResult;

/// Rust version of [collections.abc.MutableMapping].
///
/// [collections.abc.MutableMapping]: https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping
pub trait PyMutableMapping {
    type Key;
    type Value;

    fn len(&self) -> PyResult<usize>;
    fn contains(&self, key: Self::Key) -> PyResult<bool>;
    fn get(&self, key: Self::Key) -> PyResult<Option<Self::Value>>;
    fn set(&mut self, key: Self::Key, value: Self::Value) -> PyResult<()>;
    fn del(&mut self, key: Self::Key) -> PyResult<()>;

    // TODO(Perf): This methods should return iterators instead of `Vec`s.
    fn keys(&self) -> PyResult<Vec<Self::Key>>;
    fn values(&self) -> PyResult<Vec<Self::Value>>;
}

/// Macro that provides mixin methods of [collections.abc.MutableMapping] to the implementing type.
///
/// [collections.abc.MutableMapping]: https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping
#[macro_export]
macro_rules! mutable_mapping_pymethods {
    ($ty:ident, keys_iter: $keys_iter: ident) => {
        const _: fn() = || {
            fn assert_impl<T: PyMutableMapping>() {}
            assert_impl::<$ty>();
        };

        #[pyo3::pyclass]
        struct $keys_iter(std::vec::IntoIter<<$ty as PyMutableMapping>::Key>);

        #[pyo3::pymethods]
        impl $keys_iter {
            fn __next__(&mut self) -> Option<<$ty as PyMutableMapping>::Key> {
                self.0.next()
            }
        }

        #[pyo3::pymethods]
        impl $ty {
            // -- collections.abc.Sized

            fn __len__(&self) -> pyo3::PyResult<usize> {
                self.len()
            }

            // -- collections.abc.Container

            fn __contains__(&self, key: <$ty as PyMutableMapping>::Key) -> pyo3::PyResult<bool> {
                self.contains(key)
            }

            // -- collections.abc.Iterable

            /// Returns an iterator over the keys of the dictionary.
            /// NOTE: This method currently causes all keys to be cloned.
            fn __iter__(&self) -> pyo3::PyResult<$keys_iter> {
                Ok($keys_iter(self.keys()?.into_iter()))
            }

            // -- collections.abc.Mapping

            fn __getitem__(
                &self,
                key: <$ty as PyMutableMapping>::Key,
            ) -> pyo3::PyResult<Option<<$ty as PyMutableMapping>::Value>> {
                <$ty as PyMutableMapping>::get(&self, key)
            }

            fn get(
                &self,
                key: <$ty as PyMutableMapping>::Key,
                default: Option<<$ty as PyMutableMapping>::Value>,
            ) -> pyo3::PyResult<Option<<$ty as PyMutableMapping>::Value>> {
                Ok(<$ty as PyMutableMapping>::get(&self, key)?.or(default))
            }

            /// Returns keys of the dictionary.
            /// NOTE: This method currently causes all keys to be cloned.
            fn keys(&self) -> pyo3::PyResult<Vec<<$ty as PyMutableMapping>::Key>> {
                <$ty as PyMutableMapping>::keys(&self)
            }

            /// Returns values of the dictionary.
            /// NOTE: This method currently causes all values to be cloned.
            fn values(&self) -> pyo3::PyResult<Vec<<$ty as PyMutableMapping>::Value>> {
                <$ty as PyMutableMapping>::values(&self)
            }

            /// Returns items (key, value) of the dictionary.
            /// NOTE: This method currently causes all keys and values to be cloned.
            fn items(
                &self,
            ) -> pyo3::PyResult<
                Vec<(
                    <$ty as PyMutableMapping>::Key,
                    <$ty as PyMutableMapping>::Value,
                )>,
            > {
                Ok(self
                    .keys()?
                    .into_iter()
                    .zip(self.values()?.into_iter())
                    .collect())
            }

            // -- collections.abc.MutableMapping

            fn __setitem__(
                &mut self,
                key: <$ty as PyMutableMapping>::Key,
                value: <$ty as PyMutableMapping>::Value,
            ) -> pyo3::PyResult<()> {
                self.set(key, value)
            }

            fn __delitem__(&mut self, key: <$ty as PyMutableMapping>::Key) -> pyo3::PyResult<()> {
                self.del(key)
            }

            fn pop(
                &mut self,
                key: <$ty as PyMutableMapping>::Key,
                default: Option<<$ty as PyMutableMapping>::Value>,
            ) -> pyo3::PyResult<<$ty as PyMutableMapping>::Value> {
                let val = self.__getitem__(key.clone())?;
                match val {
                    Some(val) => {
                        self.del(key)?;
                        Ok(val)
                    }
                    None => {
                        default.ok_or_else(|| pyo3::exceptions::PyKeyError::new_err("unknown key"))
                    }
                }
            }

            fn popitem(
                &mut self,
            ) -> pyo3::PyResult<(
                <$ty as PyMutableMapping>::Key,
                <$ty as PyMutableMapping>::Value,
            )> {
                let key = self
                    .keys()?
                    .iter()
                    .cloned()
                    .next()
                    .ok_or_else(|| pyo3::exceptions::PyKeyError::new_err("no key"))?;
                let value = self.pop(key.clone(), None)?;
                Ok((key, value))
            }

            fn clear(&mut self, py: pyo3::Python) -> pyo3::PyResult<()> {
                loop {
                    match self.popitem() {
                        Ok(_) => {}
                        Err(err) if err.is_instance_of::<pyo3::exceptions::PyKeyError>(py) => {
                            return Ok(())
                        }
                        Err(err) => return Err(err),
                    }
                }
            }

            fn setdefault(
                &mut self,
                key: <$ty as PyMutableMapping>::Key,
                default: Option<<$ty as PyMutableMapping>::Value>,
            ) -> pyo3::PyResult<Option<<$ty as PyMutableMapping>::Value>> {
                match self.__getitem__(key.clone())? {
                    Some(value) => Ok(Some(value)),
                    None => {
                        if let Some(value) = default.clone() {
                            self.set(key, value)?;
                        }
                        Ok(default)
                    }
                }
            }
        }
    };
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use pyo3::{prelude::*, py_run};

    use super::*;

    #[pyclass(mapping)]
    struct Map(HashMap<String, String>);

    impl PyMutableMapping for Map {
        type Key = String;
        type Value = String;

        fn len(&self) -> PyResult<usize> {
            Ok(self.0.len())
        }

        fn contains(&self, key: Self::Key) -> PyResult<bool> {
            Ok(self.0.contains_key(&key))
        }

        fn keys(&self) -> PyResult<Vec<Self::Key>> {
            Ok(self.0.keys().cloned().collect())
        }

        fn values(&self) -> PyResult<Vec<Self::Value>> {
            Ok(self.0.values().cloned().collect())
        }

        fn get(&self, key: Self::Key) -> PyResult<Option<Self::Value>> {
            Ok(self.0.get(&key).cloned())
        }

        fn set(&mut self, key: Self::Key, value: Self::Value) -> PyResult<()> {
            self.0.insert(key, value);
            Ok(())
        }

        fn del(&mut self, key: Self::Key) -> PyResult<()> {
            self.0.remove(&key);
            Ok(())
        }
    }

    mutable_mapping_pymethods!(Map, keys_iter: MapKeys);

    #[test]
    fn mutable_mapping() -> PyResult<()> {
        pyo3::prepare_freethreaded_python();

        let map = Map({
            let mut hash_map = HashMap::new();
            hash_map.insert("foo".to_string(), "bar".to_string());
            hash_map.insert("baz".to_string(), "qux".to_string());
            hash_map
        });

        Python::with_gil(|py| {
            let map = PyCell::new(py, map)?;
            py_run!(
                py,
                map,
                r#"
# collections.abc.Sized
assert len(map) == 2

# collections.abc.Container
assert "foo" in map
assert "foobar" not in map

# collections.abc.Iterable
elems = ["foo", "baz"]

for elem in map:
    assert elem in elems

it = iter(map)
assert next(it) in elems
assert next(it) in elems
try:
    next(it)
    assert False, "should stop iteration"
except StopIteration:
    pass

assert set(list(map)) == set(["foo", "baz"])

# collections.abc.Mapping
assert map["foo"] == "bar"
assert map.get("baz") == "qux"
assert map.get("foobar") == None
assert map.get("foobar", "default") == "default"

assert set(list(map.keys())) == set(["foo", "baz"])
assert set(list(map.values())) == set(["bar", "qux"])
assert set(list(map.items())) == set([("foo", "bar"), ("baz", "qux")])

# collections.abc.MutableMapping
map["foobar"] = "bazqux"
del map["foo"]

try:
    map.pop("not_exist")
    assert False, "should throw KeyError"
except KeyError:
    pass
assert map.pop("not_exist", "default") == "default"
assert map.pop("foobar") == "bazqux"
assert "foobar" not in map

# at this point there is only `baz => qux` in `map`
assert map.popitem() == ("baz", "qux")
assert len(map) == 0
try:
    map.popitem()
    assert False, "should throw KeyError"
except KeyError:
    pass

map["foo"] = "bar"
assert len(map) == 1
map.clear()
assert len(map) == 0
assert "foo" not in "bar"

assert map.setdefault("foo", "bar") == "bar"
assert map["foo"] == "bar"
assert map.setdefault("foo", "baz") == "bar"

# TODO(MissingImpl): Add tests for map.update(...)
"#
            );
            Ok(())
        })
    }
}