pyo3/conversions/
indexmap.rs

1#![cfg(feature = "indexmap")]
2
3//!  Conversions to and from [indexmap](https://docs.rs/indexmap/)’s
4//! `IndexMap`.
5//!
6//! [`indexmap::IndexMap`] is a hash table that is closely compatible with the standard [`std::collections::HashMap`],
7//! with the difference that it preserves the insertion order when iterating over keys. It was inspired
8//! by Python's 3.6+ dict implementation.
9//!
10//! Dictionary order is guaranteed to be insertion order in Python, hence IndexMap is a good candidate
11//! for maintaining an equivalent behaviour in Rust.
12//!
13//! # Setup
14//!
15//! To use this feature, add this to your **`Cargo.toml`**:
16//!
17//! ```toml
18//! [dependencies]
19//! # change * to the latest versions
20//! indexmap = "*"
21#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"),  "\", features = [\"indexmap\"] }")]
22//! ```
23//!
24//! Note that you must use compatible versions of indexmap and PyO3.
25//! The required indexmap version may vary based on the version of PyO3.
26//!
27//! # Examples
28//!
29//! Using [indexmap](https://docs.rs/indexmap) to return a dictionary with some statistics
30//! about a list of numbers. Because of the insertion order guarantees, the Python code will
31//! always print the same result, matching users' expectations about Python's dict.
32//! ```rust
33//! use indexmap::{indexmap, IndexMap};
34//! use pyo3::prelude::*;
35//!
36//! fn median(data: &Vec<i32>) -> f32 {
37//!     let sorted_data = data.clone().sort();
38//!     let mid = data.len() / 2;
39//!     if data.len() % 2 == 0 {
40//!         data[mid] as f32
41//!     }
42//!     else {
43//!         (data[mid] + data[mid - 1]) as f32 / 2.0
44//!     }
45//! }
46//!
47//! fn mean(data: &Vec<i32>) -> f32 {
48//!     data.iter().sum::<i32>() as f32 / data.len() as f32
49//! }
50//! fn mode(data: &Vec<i32>) -> f32 {
51//!     let mut frequency = IndexMap::new(); // we can use IndexMap as any hash table
52//!
53//!     for &element in data {
54//!         *frequency.entry(element).or_insert(0) += 1;
55//!     }
56//!
57//!     frequency
58//!         .iter()
59//!         .max_by(|a, b| a.1.cmp(&b.1))
60//!         .map(|(k, _v)| *k)
61//!         .unwrap() as f32
62//!   }
63//!
64//! #[pyfunction]
65//! fn calculate_statistics(data: Vec<i32>) -> IndexMap<&'static str, f32> {
66//!     indexmap! {
67//!        "median" => median(&data),
68//!        "mean" => mean(&data),
69//!        "mode" => mode(&data),
70//!     }
71//! }
72//!
73//! #[pymodule]
74//! fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
75//!     m.add_function(wrap_pyfunction!(calculate_statistics, m)?)?;
76//!     Ok(())
77//! }
78//! ```
79//!
80//! Python code:
81//! ```python
82//! from my_module import calculate_statistics
83//!
84//! data = [1, 1, 1, 3, 4, 5]
85//! print(calculate_statistics(data))
86//! # always prints {"median": 2.0, "mean": 2.5, "mode": 1.0} in the same order
87//! # if another hash table was used, the order could be random
88//! ```
89
90use crate::conversion::{FromPyObjectOwned, IntoPyObject};
91use crate::types::*;
92use crate::{Borrowed, Bound, FromPyObject, PyErr, Python};
93use std::{cmp, hash};
94
95impl<'py, K, V, H> IntoPyObject<'py> for indexmap::IndexMap<K, V, H>
96where
97    K: IntoPyObject<'py> + cmp::Eq + hash::Hash,
98    V: IntoPyObject<'py>,
99    H: hash::BuildHasher,
100{
101    type Target = PyDict;
102    type Output = Bound<'py, Self::Target>;
103    type Error = PyErr;
104
105    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
106        let dict = PyDict::new(py);
107        for (k, v) in self {
108            dict.set_item(k, v)?;
109        }
110        Ok(dict)
111    }
112}
113
114impl<'a, 'py, K, V, H> IntoPyObject<'py> for &'a indexmap::IndexMap<K, V, H>
115where
116    &'a K: IntoPyObject<'py> + cmp::Eq + hash::Hash,
117    &'a V: IntoPyObject<'py>,
118    H: hash::BuildHasher,
119{
120    type Target = PyDict;
121    type Output = Bound<'py, Self::Target>;
122    type Error = PyErr;
123
124    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
125        let dict = PyDict::new(py);
126        for (k, v) in self {
127            dict.set_item(k, v)?;
128        }
129        Ok(dict)
130    }
131}
132
133impl<'py, K, V, S> FromPyObject<'_, 'py> for indexmap::IndexMap<K, V, S>
134where
135    K: FromPyObjectOwned<'py> + cmp::Eq + hash::Hash,
136    V: FromPyObjectOwned<'py>,
137    S: hash::BuildHasher + Default,
138{
139    type Error = PyErr;
140
141    fn extract(ob: Borrowed<'_, 'py, PyAny>) -> Result<Self, Self::Error> {
142        let dict = ob.cast::<PyDict>()?;
143        let mut ret = indexmap::IndexMap::with_capacity_and_hasher(dict.len(), S::default());
144        for (k, v) in dict.iter() {
145            ret.insert(
146                k.extract().map_err(Into::into)?,
147                v.extract().map_err(Into::into)?,
148            );
149        }
150        Ok(ret)
151    }
152}
153
154#[cfg(test)]
155mod test_indexmap {
156
157    use crate::types::*;
158    use crate::{IntoPyObject, Python};
159
160    #[test]
161    fn test_indexmap_indexmap_into_pyobject() {
162        Python::attach(|py| {
163            let mut map = indexmap::IndexMap::<i32, i32>::new();
164            map.insert(1, 1);
165
166            let py_map = (&map).into_pyobject(py).unwrap();
167
168            assert_eq!(py_map.len(), 1);
169            assert!(
170                py_map
171                    .get_item(1)
172                    .unwrap()
173                    .unwrap()
174                    .extract::<i32>()
175                    .unwrap()
176                    == 1
177            );
178            assert_eq!(
179                map,
180                py_map.extract::<indexmap::IndexMap::<i32, i32>>().unwrap()
181            );
182        });
183    }
184
185    #[test]
186    fn test_indexmap_indexmap_into_dict() {
187        Python::attach(|py| {
188            let mut map = indexmap::IndexMap::<i32, i32>::new();
189            map.insert(1, 1);
190
191            let py_map = map.into_py_dict(py).unwrap();
192
193            assert_eq!(py_map.len(), 1);
194            assert_eq!(
195                py_map
196                    .get_item(1)
197                    .unwrap()
198                    .unwrap()
199                    .extract::<i32>()
200                    .unwrap(),
201                1
202            );
203        });
204    }
205
206    #[test]
207    fn test_indexmap_indexmap_insertion_order_round_trip() {
208        Python::attach(|py| {
209            let n = 20;
210            let mut map = indexmap::IndexMap::<i32, i32>::new();
211
212            for i in 1..=n {
213                if i % 2 == 1 {
214                    map.insert(i, i);
215                } else {
216                    map.insert(n - i, i);
217                }
218            }
219
220            let py_map = (&map).into_py_dict(py).unwrap();
221
222            let trip_map = py_map.extract::<indexmap::IndexMap<i32, i32>>().unwrap();
223
224            for (((k1, v1), (k2, v2)), (k3, v3)) in
225                map.iter().zip(py_map.iter()).zip(trip_map.iter())
226            {
227                let k2 = k2.extract::<i32>().unwrap();
228                let v2 = v2.extract::<i32>().unwrap();
229                assert_eq!((k1, v1), (&k2, &v2));
230                assert_eq!((k1, v1), (k3, v3));
231                assert_eq!((&k2, &v2), (k3, v3));
232            }
233        });
234    }
235}