| 1 | use std::collections::HashMap; |
| 2 | |
| 3 | use pyo3::{ |
| 4 | exceptions::{PyIndexError, PyKeyError}, |
| 5 | prelude::*, |
| 6 | types::{PyDict, PyMapping, PySequence, PyTuple}, |
| 7 | IntoPyObjectExt, |
| 8 | }; |
| 9 | use pythonize::{ |
| 10 | depythonize, pythonize_custom, PythonizeListType, PythonizeMappingType, |
| 11 | PythonizeNamedMappingType, PythonizeTypes, PythonizeUnnamedMappingAdapter, Pythonizer, |
| 12 | }; |
| 13 | use serde::Serialize; |
| 14 | use serde_json::{json, Value}; |
| 15 | |
| 16 | #[pyclass(sequence)] |
| 17 | struct CustomList { |
| 18 | items: Vec<Py<PyAny>>, |
| 19 | } |
| 20 | |
| 21 | #[pymethods] |
| 22 | impl CustomList { |
| 23 | fn __len__(&self) -> usize { |
| 24 | self.items.len() |
| 25 | } |
| 26 | |
| 27 | fn __getitem__(&self, idx: isize) -> PyResult<Py<PyAny>> { |
| 28 | self.items |
| 29 | .get(idx as usize) |
| 30 | .cloned() |
| 31 | .ok_or_else(|| PyIndexError::new_err(idx)) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | impl PythonizeListType for CustomList { |
| 36 | fn create_sequence<'py, T, U>( |
| 37 | py: Python<'py>, |
| 38 | elements: impl IntoIterator<Item = T, IntoIter = U>, |
| 39 | ) -> PyResult<Bound<'py, PySequence>> |
| 40 | where |
| 41 | T: IntoPyObject<'py>, |
| 42 | U: ExactSizeIterator<Item = T>, |
| 43 | { |
| 44 | let sequence = Bound::new( |
| 45 | py, |
| 46 | CustomList { |
| 47 | items: elements |
| 48 | .into_iter() |
| 49 | .map(|item| item.into_py_any(py)) |
| 50 | .collect::<PyResult<_>>()?, |
| 51 | }, |
| 52 | )?; |
| 53 | |
| 54 | Ok(unsafe { sequence.cast_into_unchecked() }) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | struct PythonizeCustomList; |
| 59 | impl<'py> PythonizeTypes for PythonizeCustomList { |
| 60 | type Map = PyDict; |
| 61 | type NamedMap = PythonizeUnnamedMappingAdapter<PyDict>; |
| 62 | type List = CustomList; |
| 63 | } |
| 64 | |
| 65 | #[test] |
| 66 | fn test_custom_list() { |
| 67 | Python::attach(|py| { |
| 68 | PySequence::register::<CustomList>(py).unwrap(); |
| 69 | let serialized = pythonize_custom::<PythonizeCustomList, _>(py, &json!([1, 2, 3])).unwrap(); |
| 70 | assert!(serialized.is_instance_of::<CustomList>()); |
| 71 | |
| 72 | let deserialized: Value = depythonize(&serialized).unwrap(); |
| 73 | assert_eq!(deserialized, json!([1, 2, 3])); |
| 74 | }) |
| 75 | } |
| 76 | |
| 77 | #[pyclass(mapping)] |
| 78 | struct CustomDict { |
| 79 | items: HashMap<String, Py<PyAny>>, |
| 80 | } |
| 81 | |
| 82 | #[pymethods] |
| 83 | impl CustomDict { |
| 84 | fn __len__(&self) -> usize { |
| 85 | self.items.len() |
| 86 | } |
| 87 | |
| 88 | fn __getitem__(&self, key: String) -> PyResult<Py<PyAny>> { |
| 89 | self.items |
| 90 | .get(&key) |
| 91 | .cloned() |
| 92 | .ok_or_else(|| PyKeyError::new_err(key)) |
| 93 | } |
| 94 | |
| 95 | fn __setitem__(&mut self, key: String, value: Py<PyAny>) { |
| 96 | self.items.insert(key, value); |
| 97 | } |
| 98 | |
| 99 | fn keys(&self) -> Vec<&String> { |
| 100 | self.items.keys().collect() |
| 101 | } |
| 102 | |
| 103 | fn values(&self) -> Vec<Py<PyAny>> { |
| 104 | self.items.values().cloned().collect() |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | impl PythonizeMappingType for CustomDict { |
| 109 | type Builder<'py> = Bound<'py, CustomDict>; |
| 110 | |
| 111 | fn builder<'py>(py: Python<'py>, len: Option<usize>) -> PyResult<Self::Builder<'py>> { |
| 112 | Bound::new( |
| 113 | py, |
| 114 | CustomDict { |
| 115 | items: HashMap::with_capacity(len.unwrap_or(0)), |
| 116 | }, |
| 117 | ) |
| 118 | } |
| 119 | |
| 120 | fn push_item<'py>( |
| 121 | builder: &mut Self::Builder<'py>, |
| 122 | key: Bound<'py, PyAny>, |
| 123 | value: Bound<'py, PyAny>, |
| 124 | ) -> PyResult<()> { |
| 125 | unsafe { builder.cast_unchecked::<PyMapping>() }.set_item(key, value) |
| 126 | } |
| 127 | |
| 128 | fn finish<'py>(builder: Self::Builder<'py>) -> PyResult<Bound<'py, PyMapping>> { |
| 129 | Ok(unsafe { builder.cast_into_unchecked() }) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | struct PythonizeCustomDict; |
| 134 | impl<'py> PythonizeTypes for PythonizeCustomDict { |
| 135 | type Map = CustomDict; |
| 136 | type NamedMap = PythonizeUnnamedMappingAdapter<CustomDict>; |
| 137 | type List = PyTuple; |
| 138 | } |
| 139 | |
| 140 | #[test] |
| 141 | fn test_custom_dict() { |
| 142 | Python::attach(|py| { |
| 143 | PyMapping::register::<CustomDict>(py).unwrap(); |
| 144 | let serialized = |
| 145 | pythonize_custom::<PythonizeCustomDict, _>(py, &json!({ "hello": 1, "world": 2 })) |
| 146 | .unwrap(); |
| 147 | assert!(serialized.is_instance_of::<CustomDict>()); |
| 148 | |
| 149 | let deserialized: Value = depythonize(&serialized).unwrap(); |
| 150 | assert_eq!(deserialized, json!({ "hello": 1, "world": 2 })); |
| 151 | }) |
| 152 | } |
| 153 | |
| 154 | #[test] |
| 155 | fn test_tuple() { |
| 156 | Python::attach(|py| { |
| 157 | PyMapping::register::<CustomDict>(py).unwrap(); |
| 158 | let serialized = |
| 159 | pythonize_custom::<PythonizeCustomDict, _>(py, &json!([1, 2, 3, 4])).unwrap(); |
| 160 | assert!(serialized.is_instance_of::<PyTuple>()); |
| 161 | |
| 162 | let deserialized: Value = depythonize(&serialized).unwrap(); |
| 163 | assert_eq!(deserialized, json!([1, 2, 3, 4])); |
| 164 | }) |
| 165 | } |
| 166 | |
| 167 | #[test] |
| 168 | fn test_pythonizer_can_be_created() { |
| 169 | // https://github.com/davidhewitt/pythonize/pull/56 |
| 170 | Python::attach(|py| { |
| 171 | let sample = json!({ "hello": 1, "world": 2 }); |
| 172 | assert!(sample |
| 173 | .serialize(Pythonizer::new(py)) |
| 174 | .unwrap() |
| 175 | .is_instance_of::<PyDict>()); |
| 176 | |
| 177 | assert!(sample |
| 178 | .serialize(Pythonizer::custom::<PythonizeCustomDict>(py)) |
| 179 | .unwrap() |
| 180 | .is_instance_of::<CustomDict>()); |
| 181 | }) |
| 182 | } |
| 183 | |
| 184 | #[pyclass(mapping)] |
| 185 | struct NamedCustomDict { |
| 186 | name: String, |
| 187 | items: HashMap<String, Py<PyAny>>, |
| 188 | } |
| 189 | |
| 190 | #[pymethods] |
| 191 | impl NamedCustomDict { |
| 192 | fn __len__(&self) -> usize { |
| 193 | self.items.len() |
| 194 | } |
| 195 | |
| 196 | fn __getitem__(&self, key: String) -> PyResult<Py<PyAny>> { |
| 197 | self.items |
| 198 | .get(&key) |
| 199 | .cloned() |
| 200 | .ok_or_else(|| PyKeyError::new_err(key)) |
| 201 | } |
| 202 | |
| 203 | fn __setitem__(&mut self, key: String, value: Py<PyAny>) { |
| 204 | self.items.insert(key, value); |
| 205 | } |
| 206 | |
| 207 | fn keys(&self) -> Vec<&String> { |
| 208 | self.items.keys().collect() |
| 209 | } |
| 210 | |
| 211 | fn values(&self) -> Vec<Py<PyAny>> { |
| 212 | self.items.values().cloned().collect() |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | impl PythonizeNamedMappingType for NamedCustomDict { |
| 217 | type Builder<'py> = Bound<'py, NamedCustomDict>; |
| 218 | |
| 219 | fn builder<'py>( |
| 220 | py: Python<'py>, |
| 221 | len: usize, |
| 222 | name: &'static str, |
| 223 | ) -> PyResult<Self::Builder<'py>> { |
| 224 | Bound::new( |
| 225 | py, |
| 226 | NamedCustomDict { |
| 227 | name: String::from(name), |
| 228 | items: HashMap::with_capacity(len), |
| 229 | }, |
| 230 | ) |
| 231 | } |
| 232 | |
| 233 | fn push_field<'py>( |
| 234 | builder: &mut Self::Builder<'py>, |
| 235 | name: Bound<'py, pyo3::types::PyString>, |
| 236 | value: Bound<'py, PyAny>, |
| 237 | ) -> PyResult<()> { |
| 238 | unsafe { builder.cast_unchecked::<PyMapping>() }.set_item(name, value) |
| 239 | } |
| 240 | |
| 241 | fn finish<'py>(builder: Self::Builder<'py>) -> PyResult<Bound<'py, PyMapping>> { |
| 242 | Ok(unsafe { builder.cast_into_unchecked() }) |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | struct PythonizeNamedCustomDict; |
| 247 | impl<'py> PythonizeTypes for PythonizeNamedCustomDict { |
| 248 | type Map = CustomDict; |
| 249 | type NamedMap = NamedCustomDict; |
| 250 | type List = PyTuple; |
| 251 | } |
| 252 | |
| 253 | #[derive(Serialize)] |
| 254 | struct Struct { |
| 255 | hello: u8, |
| 256 | world: i8, |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn test_custom_unnamed_dict() { |
| 261 | Python::attach(|py| { |
| 262 | PyMapping::register::<CustomDict>(py).unwrap(); |
| 263 | let serialized = |
| 264 | pythonize_custom::<PythonizeCustomDict, _>(py, &Struct { hello: 1, world: 2 }).unwrap(); |
| 265 | assert!(serialized.is_instance_of::<CustomDict>()); |
| 266 | |
| 267 | let deserialized: Value = depythonize(&serialized).unwrap(); |
| 268 | assert_eq!(deserialized, json!({ "hello": 1, "world": 2 })); |
| 269 | }) |
| 270 | } |
| 271 | |
| 272 | #[test] |
| 273 | fn test_custom_named_dict() { |
| 274 | Python::attach(|py| { |
| 275 | PyMapping::register::<NamedCustomDict>(py).unwrap(); |
| 276 | let serialized = |
| 277 | pythonize_custom::<PythonizeNamedCustomDict, _>(py, &Struct { hello: 1, world: 2 }) |
| 278 | .unwrap(); |
| 279 | let named: Bound<NamedCustomDict> = serialized.extract().unwrap(); |
| 280 | assert_eq!(named.borrow().name, "Struct"); |
| 281 | |
| 282 | let deserialized: Value = depythonize(&serialized).unwrap(); |
| 283 | assert_eq!(deserialized, json!({ "hello": 1, "world": 2 })); |
| 284 | }) |
| 285 | } |