pyo3/conversions/
smallvec.rs1#![cfg(feature = "smallvec")]
2
3#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"smallvec\"] }")]
14use crate::conversion::{FromPyObjectOwned, IntoPyObject};
19use crate::exceptions::PyTypeError;
20#[cfg(feature = "experimental-inspect")]
21use crate::inspect::PyStaticExpr;
22#[cfg(feature = "experimental-inspect")]
23use crate::type_hint_subscript;
24use crate::types::any::PyAnyMethods;
25use crate::types::{PySequence, PyString};
26use crate::{
27 err::CastError, ffi, Borrowed, Bound, FromPyObject, PyAny, PyErr, PyResult, PyTypeInfo, Python,
28};
29use smallvec::{Array, SmallVec};
30
31impl<'py, A> IntoPyObject<'py> for SmallVec<A>
32where
33 A: Array,
34 A::Item: IntoPyObject<'py>,
35{
36 type Target = PyAny;
37 type Output = Bound<'py, Self::Target>;
38 type Error = PyErr;
39
40 #[cfg(feature = "experimental-inspect")]
41 const OUTPUT_TYPE: PyStaticExpr = A::Item::SEQUENCE_OUTPUT_TYPE;
42
43 #[inline]
48 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
49 <A::Item>::owned_sequence_into_pyobject(self, py, crate::conversion::private::Token)
50 }
51}
52
53impl<'a, 'py, A> IntoPyObject<'py> for &'a SmallVec<A>
54where
55 A: Array,
56 &'a A::Item: IntoPyObject<'py>,
57{
58 type Target = PyAny;
59 type Output = Bound<'py, Self::Target>;
60 type Error = PyErr;
61
62 #[cfg(feature = "experimental-inspect")]
63 const OUTPUT_TYPE: PyStaticExpr = <&[A::Item]>::OUTPUT_TYPE;
64
65 #[inline]
66 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
67 self.as_slice().into_pyobject(py)
68 }
69}
70
71impl<'py, A> FromPyObject<'_, 'py> for SmallVec<A>
72where
73 A: Array,
74 A::Item: FromPyObjectOwned<'py>,
75{
76 type Error = PyErr;
77
78 #[cfg(feature = "experimental-inspect")]
79 const INPUT_TYPE: PyStaticExpr =
80 type_hint_subscript!(PySequence::TYPE_HINT, A::Item::INPUT_TYPE);
81
82 fn extract(obj: Borrowed<'_, 'py, PyAny>) -> Result<Self, Self::Error> {
83 if obj.is_instance_of::<PyString>() {
84 return Err(PyTypeError::new_err("Can't extract `str` to `SmallVec`"));
85 }
86 extract_sequence(obj)
87 }
88}
89
90fn extract_sequence<'py, A>(obj: Borrowed<'_, 'py, PyAny>) -> PyResult<SmallVec<A>>
91where
92 A: Array,
93 A::Item: FromPyObjectOwned<'py>,
94{
95 if unsafe { ffi::PySequence_Check(obj.as_ptr()) } == 0 {
99 return Err(CastError::new(obj, PySequence::type_object(obj.py()).into_any()).into());
100 }
101
102 let mut sv = SmallVec::with_capacity(obj.len().unwrap_or(0));
103 for item in obj.try_iter()? {
104 sv.push(item?.extract::<A::Item>().map_err(Into::into)?);
105 }
106 Ok(sv)
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112 use crate::platform::prelude::*;
113 use crate::types::{PyBytes, PyBytesMethods, PyDict, PyList};
114
115 #[test]
116 fn test_smallvec_from_py_object() {
117 Python::attach(|py| {
118 let l = PyList::new(py, [1, 2, 3, 4, 5]).unwrap();
119 let sv: SmallVec<[u64; 8]> = l.extract().unwrap();
120 assert_eq!(sv.as_slice(), [1, 2, 3, 4, 5]);
121 });
122 }
123
124 #[test]
125 fn test_smallvec_from_py_object_fails() {
126 Python::attach(|py| {
127 let dict = PyDict::new(py);
128 let sv: PyResult<SmallVec<[u64; 8]>> = dict.extract();
129 assert_eq!(
130 sv.unwrap_err().to_string(),
131 "TypeError: 'dict' object is not an instance of 'Sequence'"
132 );
133 });
134 }
135
136 #[test]
137 fn test_smallvec_into_pyobject() {
138 Python::attach(|py| {
139 let sv: SmallVec<[u64; 8]> = [1, 2, 3, 4, 5].iter().cloned().collect();
140 let hso = sv.into_pyobject(py).unwrap();
141 let l = PyList::new(py, [1, 2, 3, 4, 5]).unwrap();
142 assert!(l.eq(hso).unwrap());
143 });
144 }
145
146 #[test]
147 fn test_smallvec_intopyobject_impl() {
148 Python::attach(|py| {
149 let bytes: SmallVec<[u8; 8]> = [1, 2, 3, 4, 5].iter().cloned().collect();
150 let obj = bytes.clone().into_pyobject(py).unwrap();
151 assert!(obj.is_instance_of::<PyBytes>());
152 let obj = obj.cast_into::<PyBytes>().unwrap();
153 assert_eq!(obj.as_bytes(), &*bytes);
154
155 let nums: SmallVec<[u16; 8]> = [1, 2, 3, 4, 5].iter().cloned().collect();
156 let obj = nums.into_pyobject(py).unwrap();
157 assert!(obj.is_instance_of::<PyList>());
158 });
159 }
160}