|
| 1 | +use std::ptr; |
| 2 | + |
| 3 | +use crate::conversion::ToPyObject; |
| 4 | +use crate::err::{self, PyErr, PyResult}; |
| 5 | +use crate::ffi; |
| 6 | +use crate::objects::{PyObject, PyTuple}; |
| 7 | +use crate::python::{Python, PythonObject, ToPythonPointer}; |
| 8 | + |
| 9 | +/// Represents a read-only Python dictionary |
| 10 | +pub struct PyDictProxy(PyObject); |
| 11 | + |
| 12 | +pyobject_newtype!(PyDictProxy, PyDictProxy_Check, PyDictProxy_Type); |
| 13 | + |
| 14 | +impl PyDictProxy { |
| 15 | + #[inline] |
| 16 | + pub fn len(&self, _py: Python) -> usize { |
| 17 | + unsafe { ffi::PyObject_Size(self.0.as_ptr()) as usize } |
| 18 | + } |
| 19 | + |
| 20 | + pub fn get_item<K>(&self, py: Python, key: K) -> Option<PyObject> |
| 21 | + where |
| 22 | + K: ToPyObject, |
| 23 | + { |
| 24 | + key.with_borrowed_ptr(py, |key| unsafe { |
| 25 | + PyObject::from_borrowed_ptr_opt(py, ffi::PyObject_GetItem(self.0.as_ptr(), key)) |
| 26 | + }) |
| 27 | + } |
| 28 | + |
| 29 | + pub fn contains<K>(&self, py: Python, key: K) -> PyResult<bool> |
| 30 | + where |
| 31 | + K: ToPyObject, |
| 32 | + { |
| 33 | + key.with_borrowed_ptr(py, |key| unsafe { |
| 34 | + match ffi::PyMapping_HasKey(self.0.as_ptr(), key) { |
| 35 | + 1 => Ok(true), |
| 36 | + 0 => Ok(false), |
| 37 | + _ => Err(PyErr::fetch(py)), |
| 38 | + } |
| 39 | + }) |
| 40 | + } |
| 41 | + |
| 42 | + pub fn keys(&self, py: Python) -> PyObject { |
| 43 | + // Returns a PySequence object |
| 44 | + unsafe { |
| 45 | + PyObject::from_borrowed_ptr(py, ffi::PyMapping_Keys(self.0.as_ptr())) |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + pub fn values(&self, py: Python) -> PyObject { |
| 50 | + // Returns a PySequence object |
| 51 | + unsafe { |
| 52 | + PyObject::from_borrowed_ptr(py, ffi::PyMapping_Values(self.0.as_ptr())) |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + pub fn items(&self, py: Python) -> PyObject { |
| 57 | + // Returns a PySequence object |
| 58 | + unsafe { |
| 59 | + PyObject::from_borrowed_ptr(py, ffi::PyMapping_Items(self.0.as_ptr())) |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | + |
0 commit comments