Skip to main content

pyo3/conversions/std/
vec.rs

1#[cfg(feature = "experimental-inspect")]
2use crate::inspect::{PyStaticExpr, type_hint_identifier, type_hint_subscript};
3use crate::platform::prelude::*;
4use crate::{
5    Borrowed, CastError, PyResult, PyTypeInfo,
6    conversion::{FromPyObject, FromPyObjectOwned, FromPyObjectSequence, IntoPyObject},
7    exceptions::PyTypeError,
8    ffi,
9    types::{PyAnyMethods, PySequence, PyString},
10};
11use crate::{Bound, PyAny, PyErr, Python};
12
13impl<'py, T> IntoPyObject<'py> for Vec<T>
14where
15    T: IntoPyObject<'py>,
16{
17    type Target = PyAny;
18    type Output = Bound<'py, Self::Target>;
19    type Error = PyErr;
20
21    #[cfg(feature = "experimental-inspect")]
22    const OUTPUT_TYPE: PyStaticExpr = T::SEQUENCE_OUTPUT_TYPE;
23
24    /// Turns [`Vec<u8>`] into [`PyBytes`], all other `T`s will be turned into a [`PyList`]
25    ///
26    /// [`PyBytes`]: crate::types::PyBytes
27    /// [`PyList`]: crate::types::PyList
28    #[inline]
29    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
30        T::owned_sequence_into_pyobject(self, py, crate::conversion::private::Token)
31    }
32}
33
34impl<'a, 'py, T> IntoPyObject<'py> for &'a Vec<T>
35where
36    &'a T: IntoPyObject<'py>,
37{
38    type Target = PyAny;
39    type Output = Bound<'py, Self::Target>;
40    type Error = PyErr;
41
42    #[cfg(feature = "experimental-inspect")]
43    const OUTPUT_TYPE: PyStaticExpr = <&[T]>::OUTPUT_TYPE;
44
45    #[inline]
46    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
47        // NB: we could actually not cast to `PyAny`, which would be nice for
48        // `&Vec<u8>`, but that'd be inconsistent with the `IntoPyObject` impl
49        // above which always returns a `PyAny` for `Vec<T>`.
50        self.as_slice().into_pyobject(py).map(Bound::into_any)
51    }
52}
53
54impl<'py, T> FromPyObject<'_, 'py> for Vec<T>
55where
56    T: FromPyObjectOwned<'py>,
57{
58    type Error = PyErr;
59
60    // `SupportsGetItem` is the closest static approximation of `PySequence_Check`, and unlike
61    // `collections.abc.Sequence` it also accepts e.g. NumPy arrays. Type checkers therefore also
62    // accept `dict` and `str`, which extraction rejects at runtime.
63    #[cfg(feature = "experimental-inspect")]
64    const INPUT_TYPE: PyStaticExpr = type_hint_subscript!(
65        type_hint_identifier!("_typeshed", "SupportsGetItem"),
66        type_hint_identifier!("builtins", "int"),
67        T::INPUT_TYPE
68    );
69
70    fn extract(obj: Borrowed<'_, 'py, PyAny>) -> PyResult<Self> {
71        if let Some(extractor) = T::sequence_extractor(obj, crate::conversion::private::Token) {
72            return Ok(extractor.to_vec());
73        }
74
75        if obj.is_instance_of::<PyString>() {
76            return Err(PyTypeError::new_err("Can't extract `str` to `Vec`"));
77        }
78
79        extract_sequence(obj)
80    }
81}
82
83fn extract_sequence<'py, T>(obj: Borrowed<'_, 'py, PyAny>) -> PyResult<Vec<T>>
84where
85    T: FromPyObjectOwned<'py>,
86{
87    // Types that pass `PySequence_Check` usually implement enough of the sequence protocol
88    // to support this function and if not, we will only fail extraction safely.
89    // SAFETY: passing valid pointer to python API
90    if unsafe { ffi::PySequence_Check(obj.as_ptr()) } == 0 {
91        return Err(CastError::new(obj, PySequence::type_object(obj.py()).into_any()).into());
92    }
93
94    let mut v = Vec::with_capacity(obj.len().unwrap_or(0));
95    for item in obj.try_iter()? {
96        v.push(item?.extract::<T>().map_err(Into::into)?);
97    }
98    Ok(v)
99}
100
101#[cfg(test)]
102mod tests {
103    use crate::Python;
104    use crate::conversion::IntoPyObject;
105    use crate::platform::prelude::*;
106    use crate::types::{PyAnyMethods, PyBytes, PyBytesMethods, PyList};
107
108    #[test]
109    fn test_vec_intopyobject_impl() {
110        Python::attach(|py| {
111            let bytes: Vec<u8> = b"foobar".to_vec();
112            let obj = bytes.clone().into_pyobject(py).unwrap();
113            assert!(obj.is_instance_of::<PyBytes>());
114            let obj = obj.cast_into::<PyBytes>().unwrap();
115            assert_eq!(obj.as_bytes(), &bytes);
116
117            let nums: Vec<u16> = vec![0, 1, 2, 3];
118            let obj = nums.into_pyobject(py).unwrap();
119            assert!(obj.is_instance_of::<PyList>());
120        });
121    }
122
123    #[test]
124    fn test_vec_reference_intopyobject_impl() {
125        Python::attach(|py| {
126            let bytes: Vec<u8> = b"foobar".to_vec();
127            let obj = (&bytes).into_pyobject(py).unwrap();
128            assert!(obj.is_instance_of::<PyBytes>());
129            let obj = obj.cast_into::<PyBytes>().unwrap();
130            assert_eq!(obj.as_bytes(), &bytes);
131
132            let nums: Vec<u16> = vec![0, 1, 2, 3];
133            let obj = (&nums).into_pyobject(py).unwrap();
134            assert!(obj.is_instance_of::<PyList>());
135        });
136    }
137
138    #[test]
139    fn test_strings_cannot_be_extracted_to_vec() {
140        Python::attach(|py| {
141            let v = "London Calling";
142            let ob = v.into_pyobject(py).unwrap();
143
144            assert!(ob.extract::<Vec<String>>().is_err());
145            assert!(ob.extract::<Vec<char>>().is_err());
146        });
147    }
148
149    #[test]
150    fn test_extract_bytes_to_vec() {
151        Python::attach(|py| {
152            let v: Vec<u8> = PyBytes::new(py, b"abc").extract().unwrap();
153            assert_eq!(v, b"abc");
154        });
155    }
156
157    #[test]
158    fn test_extract_tuple_to_vec() {
159        Python::attach(|py| {
160            let v: Vec<i32> = py.eval(c"(1, 2)", None, None).unwrap().extract().unwrap();
161            assert_eq!(v, [1, 2]);
162        });
163    }
164
165    #[test]
166    fn test_extract_range_to_vec() {
167        Python::attach(|py| {
168            let v: Vec<i32> = py
169                .eval(c"range(1, 5)", None, None)
170                .unwrap()
171                .extract()
172                .unwrap();
173            assert_eq!(v, [1, 2, 3, 4]);
174        });
175    }
176
177    #[test]
178    fn test_extract_bytearray_to_vec() {
179        Python::attach(|py| {
180            let v: Vec<u8> = py
181                .eval(c"bytearray(b'abc')", None, None)
182                .unwrap()
183                .extract()
184                .unwrap();
185            assert_eq!(v, b"abc");
186        });
187    }
188}