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::IntoPyObject;
91use crate::types::*;
92use crate::{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: FromPyObject<'py> + cmp::Eq + hash::Hash,
136 V: FromPyObject<'py>,
137 S: hash::BuildHasher + Default,
138{
139 fn extract_bound(ob: &Bound<'py, PyAny>) -> Result<Self, PyErr> {
140 let dict = ob.downcast::<PyDict>()?;
141 let mut ret = indexmap::IndexMap::with_capacity_and_hasher(dict.len(), S::default());
142 for (k, v) in dict {
143 ret.insert(k.extract()?, v.extract()?);
144 }
145 Ok(ret)
146 }
147}
148
149#[cfg(test)]
150mod test_indexmap {
151
152 use crate::types::*;
153 use crate::{IntoPyObject, Python};
154
155 #[test]
156 fn test_indexmap_indexmap_into_pyobject() {
157 Python::with_gil(|py| {
158 let mut map = indexmap::IndexMap::<i32, i32>::new();
159 map.insert(1, 1);
160
161 let py_map = (&map).into_pyobject(py).unwrap();
162
163 assert!(py_map.len() == 1);
164 assert!(
165 py_map
166 .get_item(1)
167 .unwrap()
168 .unwrap()
169 .extract::<i32>()
170 .unwrap()
171 == 1
172 );
173 assert_eq!(
174 map,
175 py_map.extract::<indexmap::IndexMap::<i32, i32>>().unwrap()
176 );
177 });
178 }
179
180 #[test]
181 fn test_indexmap_indexmap_into_dict() {
182 Python::with_gil(|py| {
183 let mut map = indexmap::IndexMap::<i32, i32>::new();
184 map.insert(1, 1);
185
186 let py_map = map.into_py_dict(py).unwrap();
187
188 assert_eq!(py_map.len(), 1);
189 assert_eq!(
190 py_map
191 .get_item(1)
192 .unwrap()
193 .unwrap()
194 .extract::<i32>()
195 .unwrap(),
196 1
197 );
198 });
199 }
200
201 #[test]
202 fn test_indexmap_indexmap_insertion_order_round_trip() {
203 Python::with_gil(|py| {
204 let n = 20;
205 let mut map = indexmap::IndexMap::<i32, i32>::new();
206
207 for i in 1..=n {
208 if i % 2 == 1 {
209 map.insert(i, i);
210 } else {
211 map.insert(n - i, i);
212 }
213 }
214
215 let py_map = (&map).into_py_dict(py).unwrap();
216
217 let trip_map = py_map.extract::<indexmap::IndexMap<i32, i32>>().unwrap();
218
219 for (((k1, v1), (k2, v2)), (k3, v3)) in
220 map.iter().zip(py_map.iter()).zip(trip_map.iter())
221 {
222 let k2 = k2.extract::<i32>().unwrap();
223 let v2 = v2.extract::<i32>().unwrap();
224 assert_eq!((k1, v1), (&k2, &v2));
225 assert_eq!((k1, v1), (k3, v3));
226 assert_eq!((&k2, &v2), (k3, v3));
227 }
228 });
229 }
230}