Skip to main content

pyo3/conversions/std/
array.rs

1use crate::conversion::{FromPyObjectOwned, FromPyObjectSequence, IntoPyObject};
2#[cfg(feature = "experimental-inspect")]
3use crate::inspect::{type_hint_subscript, PyStaticExpr};
4use crate::types::any::PyAnyMethods;
5use crate::types::PySequence;
6use crate::{err::CastError, ffi, FromPyObject, PyAny, PyResult, PyTypeInfo, Python};
7use crate::{exceptions, Borrowed, Bound, PyErr};
8
9impl<'py, T, const N: usize> IntoPyObject<'py> for [T; N]
10where
11    T: IntoPyObject<'py>,
12{
13    type Target = PyAny;
14    type Output = Bound<'py, Self::Target>;
15    type Error = PyErr;
16
17    #[cfg(feature = "experimental-inspect")]
18    const OUTPUT_TYPE: PyStaticExpr = T::SEQUENCE_OUTPUT_TYPE;
19
20    /// Turns [`[u8; N]`](std::array) into [`PyBytes`], all other `T`s will be turned into a [`PyList`]
21    ///
22    /// [`PyBytes`]: crate::types::PyBytes
23    /// [`PyList`]: crate::types::PyList
24    #[inline]
25    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
26        T::owned_sequence_into_pyobject(self, py, crate::conversion::private::Token)
27    }
28}
29
30impl<'a, 'py, T, const N: usize> IntoPyObject<'py> for &'a [T; N]
31where
32    &'a T: IntoPyObject<'py>,
33{
34    type Target = PyAny;
35    type Output = Bound<'py, Self::Target>;
36    type Error = PyErr;
37
38    #[cfg(feature = "experimental-inspect")]
39    const OUTPUT_TYPE: PyStaticExpr = <&[T]>::OUTPUT_TYPE;
40
41    #[inline]
42    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
43        self.as_slice().into_pyobject(py)
44    }
45}
46
47impl<'py, T, const N: usize> FromPyObject<'_, 'py> for [T; N]
48where
49    T: FromPyObjectOwned<'py>,
50{
51    type Error = PyErr;
52
53    #[cfg(feature = "experimental-inspect")]
54    const INPUT_TYPE: PyStaticExpr = type_hint_subscript!(PySequence::TYPE_HINT, T::INPUT_TYPE);
55
56    fn extract(obj: Borrowed<'_, 'py, PyAny>) -> PyResult<Self> {
57        if let Some(extractor) = T::sequence_extractor(obj, crate::conversion::private::Token) {
58            return extractor.to_array();
59        }
60
61        create_array_from_obj(obj)
62    }
63}
64
65fn create_array_from_obj<'py, T, const N: usize>(obj: Borrowed<'_, 'py, PyAny>) -> PyResult<[T; N]>
66where
67    T: FromPyObjectOwned<'py>,
68{
69    // Types that pass `PySequence_Check` usually implement enough of the sequence protocol
70    // to support this function and if not, we will only fail extraction safely.
71    let seq = unsafe {
72        if ffi::PySequence_Check(obj.as_ptr()) != 0 {
73            obj.cast_unchecked::<PySequence>()
74        } else {
75            return Err(CastError::new(obj, PySequence::type_object(obj.py()).into_any()).into());
76        }
77    };
78    let seq_len = seq.len()?;
79    if seq_len != N {
80        return Err(invalid_sequence_length(N, seq_len));
81    }
82    array_try_from_fn(|idx| {
83        seq.get_item(idx)
84            .and_then(|any| any.extract().map_err(Into::into))
85    })
86}
87
88// TODO use std::array::try_from_fn, if that stabilises:
89// (https://github.com/rust-lang/rust/issues/89379)
90fn array_try_from_fn<E, F, T, const N: usize>(mut cb: F) -> Result<[T; N], E>
91where
92    F: FnMut(usize) -> Result<T, E>,
93{
94    // Helper to safely create arrays since the standard library doesn't
95    // provide one yet. Shouldn't be necessary in the future.
96    struct ArrayGuard<T, const N: usize> {
97        dst: *mut T,
98        initialized: usize,
99    }
100
101    impl<T, const N: usize> Drop for ArrayGuard<T, N> {
102        fn drop(&mut self) {
103            debug_assert!(self.initialized <= N);
104            let initialized_part = core::ptr::slice_from_raw_parts_mut(self.dst, self.initialized);
105            unsafe {
106                core::ptr::drop_in_place(initialized_part);
107            }
108        }
109    }
110
111    // [MaybeUninit<T>; N] would be "nicer" but is actually difficult to create - there are nightly
112    // APIs which would make this easier.
113    let mut array: core::mem::MaybeUninit<[T; N]> = core::mem::MaybeUninit::uninit();
114    let mut guard: ArrayGuard<T, N> = ArrayGuard {
115        dst: array.as_mut_ptr() as _,
116        initialized: 0,
117    };
118    unsafe {
119        let mut value_ptr = array.as_mut_ptr() as *mut T;
120        for i in 0..N {
121            core::ptr::write(value_ptr, cb(i)?);
122            value_ptr = value_ptr.offset(1);
123            guard.initialized += 1;
124        }
125        core::mem::forget(guard);
126        Ok(array.assume_init())
127    }
128}
129
130pub(crate) fn invalid_sequence_length(expected: usize, actual: usize) -> PyErr {
131    exceptions::PyValueError::new_err(format!(
132        "expected a sequence of length {expected} (got {actual})"
133    ))
134}
135
136#[cfg(test)]
137mod tests {
138    #[cfg(panic = "unwind")]
139    use std::{
140        panic,
141        sync::atomic::{AtomicUsize, Ordering},
142    };
143
144    use crate::{
145        conversion::IntoPyObject,
146        types::{any::PyAnyMethods, PyBytes, PyBytesMethods},
147    };
148    use crate::{types::PyList, PyResult, Python};
149
150    #[test]
151    #[cfg(panic = "unwind")]
152    fn array_try_from_fn() {
153        static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0);
154        struct CountDrop;
155        impl Drop for CountDrop {
156            fn drop(&mut self) {
157                DROP_COUNTER.fetch_add(1, Ordering::SeqCst);
158            }
159        }
160        let _ = catch_unwind_silent(move || {
161            let _: Result<[CountDrop; 4], ()> = super::array_try_from_fn(|idx| {
162                #[expect(clippy::manual_assert, reason = "testing panic during array creation")]
163                if idx == 2 {
164                    panic!("peek a boo");
165                }
166                Ok(CountDrop)
167            });
168        });
169        assert_eq!(DROP_COUNTER.load(Ordering::SeqCst), 2);
170    }
171
172    #[test]
173    fn test_extract_bytes_to_array() {
174        Python::attach(|py| {
175            let v: [u8; 33] = py
176                .eval(c"b'abcabcabcabcabcabcabcabcabcabcabc'", None, None)
177                .unwrap()
178                .extract()
179                .unwrap();
180            assert_eq!(&v, b"abcabcabcabcabcabcabcabcabcabcabc");
181        })
182    }
183
184    #[test]
185    fn test_extract_bytes_wrong_length() {
186        Python::attach(|py| {
187            let v: PyResult<[u8; 3]> = py.eval(c"b'abcdefg'", None, None).unwrap().extract();
188            assert_eq!(
189                v.unwrap_err().to_string(),
190                "ValueError: expected a sequence of length 3 (got 7)"
191            );
192        })
193    }
194
195    #[test]
196    fn test_extract_bytearray_to_array() {
197        Python::attach(|py| {
198            let v: [u8; 33] = py
199                .eval(
200                    c"bytearray(b'abcabcabcabcabcabcabcabcabcabcabc')",
201                    None,
202                    None,
203                )
204                .unwrap()
205                .extract()
206                .unwrap();
207            assert_eq!(&v, b"abcabcabcabcabcabcabcabcabcabcabc");
208        })
209    }
210
211    #[test]
212    fn test_extract_small_bytearray_to_array() {
213        Python::attach(|py| {
214            let v: [u8; 3] = py
215                .eval(c"bytearray(b'abc')", None, None)
216                .unwrap()
217                .extract()
218                .unwrap();
219            assert_eq!(&v, b"abc");
220        });
221    }
222    #[test]
223    fn test_into_pyobject_array_conversion() {
224        Python::attach(|py| {
225            let array: [f32; 4] = [0.0, -16.0, 16.0, 42.0];
226            let pyobject = array.into_pyobject(py).unwrap();
227            let pylist = pyobject.cast::<PyList>().unwrap();
228            assert_eq!(pylist.get_item(0).unwrap().extract::<f32>().unwrap(), 0.0);
229            assert_eq!(pylist.get_item(1).unwrap().extract::<f32>().unwrap(), -16.0);
230            assert_eq!(pylist.get_item(2).unwrap().extract::<f32>().unwrap(), 16.0);
231            assert_eq!(pylist.get_item(3).unwrap().extract::<f32>().unwrap(), 42.0);
232        });
233    }
234
235    #[test]
236    fn test_extract_invalid_sequence_length() {
237        Python::attach(|py| {
238            let v: PyResult<[u8; 3]> = py
239                .eval(c"bytearray(b'abcdefg')", None, None)
240                .unwrap()
241                .extract();
242            assert_eq!(
243                v.unwrap_err().to_string(),
244                "ValueError: expected a sequence of length 3 (got 7)"
245            );
246        })
247    }
248
249    #[test]
250    fn test_intopyobject_array_conversion() {
251        Python::attach(|py| {
252            let array: [f32; 4] = [0.0, -16.0, 16.0, 42.0];
253            let pylist = array
254                .into_pyobject(py)
255                .unwrap()
256                .cast_into::<PyList>()
257                .unwrap();
258
259            assert_eq!(pylist.get_item(0).unwrap().extract::<f32>().unwrap(), 0.0);
260            assert_eq!(pylist.get_item(1).unwrap().extract::<f32>().unwrap(), -16.0);
261            assert_eq!(pylist.get_item(2).unwrap().extract::<f32>().unwrap(), 16.0);
262            assert_eq!(pylist.get_item(3).unwrap().extract::<f32>().unwrap(), 42.0);
263        });
264    }
265
266    #[test]
267    fn test_array_intopyobject_impl() {
268        Python::attach(|py| {
269            let bytes: [u8; 6] = *b"foobar";
270            let obj = bytes.into_pyobject(py).unwrap();
271            assert!(obj.is_instance_of::<PyBytes>());
272            let obj = obj.cast_into::<PyBytes>().unwrap();
273            assert_eq!(obj.as_bytes(), &bytes);
274
275            let nums: [u16; 4] = [0, 1, 2, 3];
276            let obj = nums.into_pyobject(py).unwrap();
277            assert!(obj.is_instance_of::<PyList>());
278        });
279    }
280
281    #[test]
282    fn test_extract_non_iterable_to_array() {
283        Python::attach(|py| {
284            let v = py.eval(c"42", None, None).unwrap();
285            v.extract::<i32>().unwrap();
286            v.extract::<[i32; 1]>().unwrap_err();
287        });
288    }
289
290    #[cfg(feature = "macros")]
291    #[test]
292    fn test_pyclass_intopy_array_conversion() {
293        #[crate::pyclass(crate = "crate")]
294        struct Foo;
295
296        Python::attach(|py| {
297            let array: [Foo; 8] = [Foo, Foo, Foo, Foo, Foo, Foo, Foo, Foo];
298            let list = array
299                .into_pyobject(py)
300                .unwrap()
301                .cast_into::<PyList>()
302                .unwrap();
303            let _bound = list.get_item(4).unwrap().cast::<Foo>().unwrap();
304        });
305    }
306
307    // https://stackoverflow.com/a/59211505
308    #[cfg(panic = "unwind")]
309    fn catch_unwind_silent<F, R>(f: F) -> std::thread::Result<R>
310    where
311        F: FnOnce() -> R + panic::UnwindSafe,
312    {
313        let prev_hook = panic::take_hook();
314        panic::set_hook(Box::new(|_| {}));
315        let result = panic::catch_unwind(f);
316        panic::set_hook(prev_hook);
317        result
318    }
319}