pyo3/types/
mappingproxy.rs

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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
// Copyright (c) 2017-present PyO3 Project and Contributors

use super::PyMapping;
use crate::err::PyResult;
use crate::ffi_ptr_ext::FfiPtrExt;
use crate::instance::Bound;
use crate::types::any::PyAnyMethods;
use crate::types::{PyAny, PyIterator, PyList};
use crate::{ffi, Python};

use std::os::raw::c_int;

/// Represents a Python `mappingproxy`.
#[repr(transparent)]
pub struct PyMappingProxy(PyAny);

#[inline]
unsafe fn dict_proxy_check(op: *mut ffi::PyObject) -> c_int {
    ffi::Py_IS_TYPE(op, std::ptr::addr_of_mut!(ffi::PyDictProxy_Type))
}

pyobject_native_type_core!(
    PyMappingProxy,
    pyobject_native_static_type_object!(ffi::PyDictProxy_Type),
    #checkfunction=dict_proxy_check
);

impl PyMappingProxy {
    /// Creates a mappingproxy from an object.
    pub fn new<'py>(
        py: Python<'py>,
        elements: &Bound<'py, PyMapping>,
    ) -> Bound<'py, PyMappingProxy> {
        unsafe {
            ffi::PyDictProxy_New(elements.as_ptr())
                .assume_owned(py)
                .downcast_into_unchecked()
        }
    }
}

/// Implementation of functionality for [`PyMappingProxy`].
///
/// These methods are defined for the `Bound<'py, PyMappingProxy>` smart pointer, so to use method call
/// syntax these methods are separated into a trait, because stable Rust does not yet support
/// `arbitrary_self_types`.
#[doc(alias = "PyMappingProxy")]
pub trait PyMappingProxyMethods<'py, 'a>: crate::sealed::Sealed {
    /// Checks if the mappingproxy is empty, i.e. `len(self) == 0`.
    fn is_empty(&self) -> PyResult<bool>;

    /// Returns a list containing all keys in the mapping.
    fn keys(&self) -> PyResult<Bound<'py, PyList>>;

    /// Returns a list containing all values in the mapping.
    fn values(&self) -> PyResult<Bound<'py, PyList>>;

    /// Returns a list of tuples of all (key, value) pairs in the mapping.
    fn items(&self) -> PyResult<Bound<'py, PyList>>;

    /// Returns `self` cast as a `PyMapping`.
    fn as_mapping(&self) -> &Bound<'py, PyMapping>;

    /// Takes an object and returns an iterator for it. Returns an error if the object is not
    /// iterable.
    fn try_iter(&'a self) -> PyResult<BoundMappingProxyIterator<'py, 'a>>;
}

impl<'py, 'a> PyMappingProxyMethods<'py, 'a> for Bound<'py, PyMappingProxy> {
    fn is_empty(&self) -> PyResult<bool> {
        Ok(self.len()? == 0)
    }

    #[inline]
    fn keys(&self) -> PyResult<Bound<'py, PyList>> {
        unsafe {
            Ok(ffi::PyMapping_Keys(self.as_ptr())
                .assume_owned_or_err(self.py())?
                .downcast_into_unchecked())
        }
    }

    #[inline]
    fn values(&self) -> PyResult<Bound<'py, PyList>> {
        unsafe {
            Ok(ffi::PyMapping_Values(self.as_ptr())
                .assume_owned_or_err(self.py())?
                .downcast_into_unchecked())
        }
    }

    #[inline]
    fn items(&self) -> PyResult<Bound<'py, PyList>> {
        unsafe {
            Ok(ffi::PyMapping_Items(self.as_ptr())
                .assume_owned_or_err(self.py())?
                .downcast_into_unchecked())
        }
    }

    fn as_mapping(&self) -> &Bound<'py, PyMapping> {
        unsafe { self.downcast_unchecked() }
    }

    fn try_iter(&'a self) -> PyResult<BoundMappingProxyIterator<'py, 'a>> {
        Ok(BoundMappingProxyIterator {
            iterator: PyIterator::from_object(self)?,
            mappingproxy: self,
        })
    }
}

pub struct BoundMappingProxyIterator<'py, 'a> {
    iterator: Bound<'py, PyIterator>,
    mappingproxy: &'a Bound<'py, PyMappingProxy>,
}

impl<'py> Iterator for BoundMappingProxyIterator<'py, '_> {
    type Item = PyResult<(Bound<'py, PyAny>, Bound<'py, PyAny>)>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iterator.next().map(|key| match key {
            Ok(key) => match self.mappingproxy.get_item(&key) {
                Ok(value) => Ok((key, value)),
                Err(e) => Err(e),
            },
            Err(e) => Err(e),
        })
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::types::dict::*;
    use crate::Python;
    use crate::{
        exceptions::PyKeyError,
        types::{PyInt, PyTuple},
    };
    use std::collections::{BTreeMap, HashMap};

    #[test]
    fn test_new() {
        Python::with_gil(|py| {
            let pydict = [(7, 32)].into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, pydict.as_mapping());
            mappingproxy.get_item(7i32).unwrap();
            assert_eq!(
                32,
                mappingproxy
                    .get_item(7i32)
                    .unwrap()
                    .extract::<i32>()
                    .unwrap()
            );
            assert!(mappingproxy
                .get_item(8i32)
                .unwrap_err()
                .is_instance_of::<PyKeyError>(py));
        });
    }

    #[test]
    fn test_len() {
        Python::with_gil(|py| {
            let mut v = HashMap::new();
            let dict = v.clone().into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, dict.as_mapping());
            assert_eq!(mappingproxy.len().unwrap(), 0);
            v.insert(7, 32);
            let dict2 = v.clone().into_py_dict(py).unwrap();
            let mp2 = PyMappingProxy::new(py, dict2.as_mapping());
            assert_eq!(mp2.len().unwrap(), 1);
        });
    }

    #[test]
    fn test_contains() {
        Python::with_gil(|py| {
            let mut v = HashMap::new();
            v.insert(7, 32);
            let dict = v.clone().into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, dict.as_mapping());
            assert!(mappingproxy.contains(7i32).unwrap());
            assert!(!mappingproxy.contains(8i32).unwrap());
        });
    }

    #[test]
    fn test_get_item() {
        Python::with_gil(|py| {
            let mut v = HashMap::new();
            v.insert(7, 32);
            let dict = v.clone().into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, dict.as_mapping());
            assert_eq!(
                32,
                mappingproxy
                    .get_item(7i32)
                    .unwrap()
                    .extract::<i32>()
                    .unwrap()
            );
            assert!(mappingproxy
                .get_item(8i32)
                .unwrap_err()
                .is_instance_of::<PyKeyError>(py));
        });
    }

    #[test]
    fn test_set_item_refcnt() {
        Python::with_gil(|py| {
            let cnt;
            {
                let none = py.None();
                cnt = none.get_refcnt(py);
                let dict = [(10, none)].into_py_dict(py).unwrap();
                let _mappingproxy = PyMappingProxy::new(py, dict.as_mapping());
            }
            {
                assert_eq!(cnt, py.None().get_refcnt(py));
            }
        });
    }

    #[test]
    fn test_isempty() {
        Python::with_gil(|py| {
            let map: HashMap<usize, usize> = HashMap::new();
            let dict = map.into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, dict.as_mapping());
            assert!(mappingproxy.is_empty().unwrap());
        });
    }

    #[test]
    fn test_keys() {
        Python::with_gil(|py| {
            let mut v = HashMap::new();
            v.insert(7, 32);
            v.insert(8, 42);
            v.insert(9, 123);
            let dict = v.into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, dict.as_mapping());
            // Can't just compare against a vector of tuples since we don't have a guaranteed ordering.
            let mut key_sum = 0;
            for el in mappingproxy.keys().unwrap().try_iter().unwrap() {
                key_sum += el.unwrap().extract::<i32>().unwrap();
            }
            assert_eq!(7 + 8 + 9, key_sum);
        });
    }

    #[test]
    fn test_values() {
        Python::with_gil(|py| {
            let mut v: HashMap<i32, i32> = HashMap::new();
            v.insert(7, 32);
            v.insert(8, 42);
            v.insert(9, 123);
            let dict = v.into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, dict.as_mapping());
            // Can't just compare against a vector of tuples since we don't have a guaranteed ordering.
            let mut values_sum = 0;
            for el in mappingproxy.values().unwrap().try_iter().unwrap() {
                values_sum += el.unwrap().extract::<i32>().unwrap();
            }
            assert_eq!(32 + 42 + 123, values_sum);
        });
    }

    #[test]
    fn test_items() {
        Python::with_gil(|py| {
            let mut v = HashMap::new();
            v.insert(7, 32);
            v.insert(8, 42);
            v.insert(9, 123);
            let dict = v.into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, dict.as_mapping());
            // Can't just compare against a vector of tuples since we don't have a guaranteed ordering.
            let mut key_sum = 0;
            let mut value_sum = 0;
            for res in mappingproxy.items().unwrap().try_iter().unwrap() {
                let el = res.unwrap();
                let tuple = el.downcast::<PyTuple>().unwrap();
                key_sum += tuple.get_item(0).unwrap().extract::<i32>().unwrap();
                value_sum += tuple.get_item(1).unwrap().extract::<i32>().unwrap();
            }
            assert_eq!(7 + 8 + 9, key_sum);
            assert_eq!(32 + 42 + 123, value_sum);
        });
    }

    #[test]
    fn test_iter() {
        Python::with_gil(|py| {
            let mut v = HashMap::new();
            v.insert(7, 32);
            v.insert(8, 42);
            v.insert(9, 123);
            let dict = v.into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, dict.as_mapping());
            let mut key_sum = 0;
            let mut value_sum = 0;
            for res in mappingproxy.try_iter().unwrap() {
                let (key, value) = res.unwrap();
                key_sum += key.extract::<i32>().unwrap();
                value_sum += value.extract::<i32>().unwrap();
            }
            assert_eq!(7 + 8 + 9, key_sum);
            assert_eq!(32 + 42 + 123, value_sum);
        });
    }

    #[test]
    fn test_hashmap_into_python() {
        Python::with_gil(|py| {
            let mut map = HashMap::<i32, i32>::new();
            map.insert(1, 1);

            let dict = map.clone().into_py_dict(py).unwrap();
            let py_map = PyMappingProxy::new(py, dict.as_mapping());

            assert_eq!(py_map.len().unwrap(), 1);
            assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1);
        });
    }

    #[test]
    fn test_hashmap_into_mappingproxy() {
        Python::with_gil(|py| {
            let mut map = HashMap::<i32, i32>::new();
            map.insert(1, 1);

            let dict = map.clone().into_py_dict(py).unwrap();
            let py_map = PyMappingProxy::new(py, dict.as_mapping());

            assert_eq!(py_map.len().unwrap(), 1);
            assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1);
        });
    }

    #[test]
    fn test_btreemap_into_py() {
        Python::with_gil(|py| {
            let mut map = BTreeMap::<i32, i32>::new();
            map.insert(1, 1);

            let dict = map.clone().into_py_dict(py).unwrap();
            let py_map = PyMappingProxy::new(py, dict.as_mapping());

            assert_eq!(py_map.len().unwrap(), 1);
            assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1);
        });
    }

    #[test]
    fn test_btreemap_into_mappingproxy() {
        Python::with_gil(|py| {
            let mut map = BTreeMap::<i32, i32>::new();
            map.insert(1, 1);

            let dict = map.clone().into_py_dict(py).unwrap();
            let py_map = PyMappingProxy::new(py, dict.as_mapping());

            assert_eq!(py_map.len().unwrap(), 1);
            assert_eq!(py_map.get_item(1).unwrap().extract::<i32>().unwrap(), 1);
        });
    }

    #[test]
    fn test_vec_into_mappingproxy() {
        Python::with_gil(|py| {
            let vec = vec![("a", 1), ("b", 2), ("c", 3)];
            let dict = vec.clone().into_py_dict(py).unwrap();
            let py_map = PyMappingProxy::new(py, dict.as_mapping());

            assert_eq!(py_map.len().unwrap(), 3);
            assert_eq!(py_map.get_item("b").unwrap().extract::<i32>().unwrap(), 2);
        });
    }

    #[test]
    fn test_slice_into_mappingproxy() {
        Python::with_gil(|py| {
            let arr = [("a", 1), ("b", 2), ("c", 3)];

            let dict = arr.into_py_dict(py).unwrap();
            let py_map = PyMappingProxy::new(py, dict.as_mapping());

            assert_eq!(py_map.len().unwrap(), 3);
            assert_eq!(py_map.get_item("b").unwrap().extract::<i32>().unwrap(), 2);
        });
    }

    #[test]
    fn mappingproxy_as_mapping() {
        Python::with_gil(|py| {
            let mut map = HashMap::<i32, i32>::new();
            map.insert(1, 1);

            let dict = map.clone().into_py_dict(py).unwrap();
            let py_map = PyMappingProxy::new(py, dict.as_mapping());

            assert_eq!(py_map.as_mapping().len().unwrap(), 1);
            assert_eq!(
                py_map
                    .as_mapping()
                    .get_item(1)
                    .unwrap()
                    .extract::<i32>()
                    .unwrap(),
                1
            );
        });
    }

    #[cfg(not(PyPy))]
    fn abc_mappingproxy(py: Python<'_>) -> Bound<'_, PyMappingProxy> {
        let mut map = HashMap::<&'static str, i32>::new();
        map.insert("a", 1);
        map.insert("b", 2);
        map.insert("c", 3);
        let dict = map.clone().into_py_dict(py).unwrap();
        PyMappingProxy::new(py, dict.as_mapping())
    }

    #[test]
    #[cfg(not(PyPy))]
    fn mappingproxy_keys_view() {
        Python::with_gil(|py| {
            let mappingproxy = abc_mappingproxy(py);
            let keys = mappingproxy.call_method0("keys").unwrap();
            assert!(keys.is_instance(&py.get_type::<PyDictKeys>()).unwrap());
        })
    }

    #[test]
    #[cfg(not(PyPy))]
    fn mappingproxy_values_view() {
        Python::with_gil(|py| {
            let mappingproxy = abc_mappingproxy(py);
            let values = mappingproxy.call_method0("values").unwrap();
            assert!(values.is_instance(&py.get_type::<PyDictValues>()).unwrap());
        })
    }

    #[test]
    #[cfg(not(PyPy))]
    fn mappingproxy_items_view() {
        Python::with_gil(|py| {
            let mappingproxy = abc_mappingproxy(py);
            let items = mappingproxy.call_method0("items").unwrap();
            assert!(items.is_instance(&py.get_type::<PyDictItems>()).unwrap());
        })
    }

    #[test]
    fn get_value_from_mappingproxy_of_strings() {
        Python::with_gil(|py: Python<'_>| {
            let mut map = HashMap::new();
            map.insert("first key".to_string(), "first value".to_string());
            map.insert("second key".to_string(), "second value".to_string());
            map.insert("third key".to_string(), "third value".to_string());

            let dict = map.clone().into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, dict.as_mapping());

            assert_eq!(
                map.into_iter().collect::<Vec<(String, String)>>(),
                mappingproxy
                    .try_iter()
                    .unwrap()
                    .map(|object| {
                        let tuple = object.unwrap();
                        (
                            tuple.0.extract::<String>().unwrap(),
                            tuple.1.extract::<String>().unwrap(),
                        )
                    })
                    .collect::<Vec<(String, String)>>()
            );
        })
    }

    #[test]
    fn get_value_from_mappingproxy_of_integers() {
        Python::with_gil(|py: Python<'_>| {
            const LEN: usize = 10_000;
            let items: Vec<(usize, usize)> = (1..LEN).map(|i| (i, i - 1)).collect();

            let dict = items.clone().into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, dict.as_mapping());

            assert_eq!(
                items,
                mappingproxy
                    .clone()
                    .try_iter()
                    .unwrap()
                    .map(|object| {
                        let tuple = object.unwrap();
                        (
                            tuple
                                .0
                                .downcast::<PyInt>()
                                .unwrap()
                                .extract::<usize>()
                                .unwrap(),
                            tuple
                                .1
                                .downcast::<PyInt>()
                                .unwrap()
                                .extract::<usize>()
                                .unwrap(),
                        )
                    })
                    .collect::<Vec<(usize, usize)>>()
            );
            for index in 1..LEN {
                assert_eq!(
                    mappingproxy
                        .clone()
                        .get_item(index)
                        .unwrap()
                        .extract::<usize>()
                        .unwrap(),
                    index - 1
                );
            }
        })
    }

    #[test]
    fn iter_mappingproxy_nosegv() {
        Python::with_gil(|py| {
            const LEN: usize = 10_000_000;
            let items = (0..LEN as u64).map(|i| (i, i * 2));

            let dict = items.clone().into_py_dict(py).unwrap();
            let mappingproxy = PyMappingProxy::new(py, dict.as_mapping());

            let mut sum = 0;
            for result in mappingproxy.try_iter().unwrap() {
                let (k, _v) = result.unwrap();
                let i: u64 = k.extract().unwrap();
                sum += i;
            }
            assert_eq!(sum, 49_999_995_000_000);
        })
    }
}
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here