Skip to content

Commit c2995ec

Browse files
committed
Support for arbitrary arrays
1 parent 83f71d8 commit c2995ec

File tree

3 files changed

+80
-77
lines changed

3 files changed

+80
-77
lines changed

src/types/list.rs

+6-17
Original file line numberDiff line numberDiff line change
@@ -178,26 +178,15 @@ where
178178
}
179179
}
180180

181-
macro_rules! array_impls {
182-
($($N:expr),+) => {
183-
$(
184-
impl<T> IntoPy<PyObject> for [T; $N]
185-
where
186-
T: ToPyObject
187-
{
188-
fn into_py(self, py: Python) -> PyObject {
189-
self.as_ref().to_object(py)
190-
}
191-
}
192-
)+
181+
impl<T, const N: usize> IntoPy<PyObject> for [T; N]
182+
where
183+
T: ToPyObject,
184+
{
185+
fn into_py(self, py: Python) -> PyObject {
186+
self.as_ref().to_object(py)
193187
}
194188
}
195189

196-
array_impls!(
197-
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
198-
26, 27, 28, 29, 30, 31, 32
199-
);
200-
201190
impl<T> ToPyObject for Vec<T>
202191
where
203192
T: ToPyObject,

src/types/mod.rs

+34
Original file line numberDiff line numberDiff line change
@@ -246,3 +246,37 @@ mod slice;
246246
mod string;
247247
mod tuple;
248248
mod typeobject;
249+
250+
struct ArrayGuard<T, const N: usize> {
251+
dst: *mut T,
252+
initialized: usize,
253+
}
254+
255+
impl<T, const N: usize> Drop for ArrayGuard<T, N> {
256+
fn drop(&mut self) {
257+
debug_assert!(self.initialized <= N);
258+
let initialized_part = core::ptr::slice_from_raw_parts_mut(self.dst, self.initialized);
259+
unsafe {
260+
core::ptr::drop_in_place(initialized_part);
261+
}
262+
}
263+
}
264+
265+
fn try_create_array<E, F, T, const N: usize>(mut cb: F) -> Result<[T; N], E>
266+
where
267+
F: FnMut(usize) -> Result<T, E>,
268+
{
269+
let mut array: core::mem::MaybeUninit<[T; N]> = core::mem::MaybeUninit::uninit();
270+
let mut guard: ArrayGuard<T, N> = ArrayGuard {
271+
dst: array.as_mut_ptr() as _,
272+
initialized: 0,
273+
};
274+
unsafe {
275+
for (idx, value_ptr) in (&mut *array.as_mut_ptr()).iter_mut().enumerate() {
276+
core::ptr::write(value_ptr, cb(idx)?);
277+
guard.initialized += 1;
278+
}
279+
core::mem::forget(guard);
280+
Ok(array.assume_init())
281+
}
282+
}

src/types/sequence.rs

+40-60
Original file line numberDiff line numberDiff line change
@@ -257,57 +257,39 @@ impl PySequence {
257257
}
258258
}
259259

260-
macro_rules! array_impls {
261-
($($N:expr),+) => {
262-
$(
263-
impl<'a, T> FromPyObject<'a> for [T; $N]
264-
where
265-
T: Copy + Default + FromPyObject<'a>,
266-
{
267-
#[cfg(not(feature = "nightly"))]
268-
fn extract(obj: &'a PyAny) -> PyResult<Self> {
269-
let mut array = [T::default(); $N];
270-
extract_sequence_into_slice(obj, &mut array)?;
271-
Ok(array)
272-
}
260+
impl<'a, T, const N: usize> FromPyObject<'a> for [T; N]
261+
where
262+
T: FromPyObject<'a>,
263+
{
264+
#[cfg(not(feature = "nightly"))]
265+
fn extract(obj: &'a PyAny) -> PyResult<Self> {
266+
create_array_from_obj(obj)
267+
}
273268

274-
#[cfg(feature = "nightly")]
275-
default fn extract(obj: &'a PyAny) -> PyResult<Self> {
276-
let mut array = [T::default(); $N];
277-
extract_sequence_into_slice(obj, &mut array)?;
278-
Ok(array)
279-
}
280-
}
269+
#[cfg(feature = "nightly")]
270+
default fn extract(obj: &'a PyAny) -> PyResult<Self> {
271+
create_array_from_obj(obj)
272+
}
273+
}
281274

282-
#[cfg(feature = "nightly")]
283-
impl<'source, T> FromPyObject<'source> for [T; $N]
284-
where
285-
for<'a> T: Default + FromPyObject<'a> + crate::buffer::Element,
286-
{
287-
fn extract(obj: &'source PyAny) -> PyResult<Self> {
288-
let mut array = [T::default(); $N];
289-
// first try buffer protocol
290-
if let Ok(buf) = crate::buffer::PyBuffer::get(obj) {
291-
if buf.dimensions() == 1 && buf.copy_to_slice(obj.py(), &mut array).is_ok() {
292-
buf.release(obj.py());
293-
return Ok(array);
294-
}
295-
buf.release(obj.py());
296-
}
297-
// fall back to sequence protocol
298-
extract_sequence_into_slice(obj, &mut array)?;
299-
Ok(array)
300-
}
275+
#[cfg(feature = "nightly")]
276+
impl<'source, T, const N: usize> FromPyObject<'source> for [T; N]
277+
where
278+
for<'a> T: FromPyObject<'a> + crate::buffer::Element,
279+
{
280+
fn extract(obj: &'source PyAny) -> PyResult<Self> {
281+
let mut array = create_array_from_obj(obj)?;
282+
if let Ok(buf) = crate::buffer::PyBuffer::get(obj) {
283+
if buf.dimensions() == 1 && buf.copy_to_slice(obj.py(), &mut array).is_ok() {
284+
buf.release(obj.py());
285+
return Ok(array);
301286
}
302-
)+
287+
buf.release(obj.py());
288+
}
289+
Ok(array)
303290
}
304291
}
305292

306-
array_impls!(
307-
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
308-
26, 27, 28, 29, 30, 31, 32
309-
);
310-
311293
impl<'a, T> FromPyObject<'a> for Vec<T>
312294
where
313295
T: FromPyObject<'a>,
@@ -343,32 +325,30 @@ where
343325
}
344326
}
345327

346-
fn extract_sequence<'s, T>(obj: &'s PyAny) -> PyResult<Vec<T>>
328+
fn create_array_from_obj<'s, T, const N: usize>(obj: &'s PyAny) -> PyResult<[T; N]>
347329
where
348330
T: FromPyObject<'s>,
349331
{
350332
let seq = <PySequence as PyTryFrom>::try_from(obj)?;
351-
let mut v = Vec::with_capacity(seq.len().unwrap_or(0) as usize);
352-
for item in seq.iter()? {
353-
v.push(item?.extract::<T>()?);
354-
}
355-
Ok(v)
333+
crate::types::try_create_array(|idx| {
334+
seq.get_item(idx as isize)
335+
.map_err(|_| {
336+
exceptions::PyBufferError::new_err("Slice length does not match buffer length.")
337+
})?
338+
.extract::<T>()
339+
})
356340
}
357341

358-
fn extract_sequence_into_slice<'s, T>(obj: &'s PyAny, slice: &mut [T]) -> PyResult<()>
342+
fn extract_sequence<'s, T>(obj: &'s PyAny) -> PyResult<Vec<T>>
359343
where
360344
T: FromPyObject<'s>,
361345
{
362346
let seq = <PySequence as PyTryFrom>::try_from(obj)?;
363-
if seq.len()? as usize != slice.len() {
364-
return Err(exceptions::PyBufferError::new_err(
365-
"Slice length does not match buffer length.",
366-
));
367-
}
368-
for (value, item) in slice.iter_mut().zip(seq.iter()?) {
369-
*value = item?.extract::<T>()?;
347+
let mut v = Vec::with_capacity(seq.len().unwrap_or(0) as usize);
348+
for item in seq.iter()? {
349+
v.push(item?.extract::<T>()?);
370350
}
371-
Ok(())
351+
Ok(v)
372352
}
373353

374354
impl<'v> PyTryFrom<'v> for PySequence {

0 commit comments

Comments
 (0)