Skip to content

Commit

Permalink
Support for arbitrary arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
c410-f3r committed Sep 1, 2020
1 parent 4a05f27 commit 5a92708
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ rustversion = "1.0"
[features]
default = ["macros"]
macros = ["ctor", "indoc", "inventory", "paste", "pyo3cls", "unindent"]

# Supports arrays of arbitrary size
const-generics = []

# Optimizes PyObject to Vec conversion and so on.
nightly = []

Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![cfg_attr(feature = "const-generics", feature(min_const_generics))]
#![cfg_attr(feature = "nightly", allow(incomplete_features))]
#![cfg_attr(feature = "nightly", feature(specialization))]
#![allow(clippy::missing_safety_doc)] // FIXME (#698)

Expand Down
12 changes: 12 additions & 0 deletions src/types/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,17 @@ where
}
}

#[cfg(feature = "const-generics")]
impl<T, const N: usize> IntoPy<PyObject> for [T; N]
where
T: ToPyObject,
{
fn into_py(self, py: Python) -> PyObject {
self.as_ref().to_object(py)
}
}

#[cfg(not(feature = "const-generics"))]
macro_rules! array_impls {
($($N:expr),+) => {
$(
Expand All @@ -193,6 +204,7 @@ macro_rules! array_impls {
}
}

#[cfg(not(feature = "const-generics"))]
array_impls!(
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,
26, 27, 28, 29, 30, 31, 32
Expand Down
37 changes: 37 additions & 0 deletions src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,3 +235,40 @@ mod slice;
mod string;
mod tuple;
mod typeobject;

#[cfg(feature = "const-generics")]
struct ArrayGuard<T, const N: usize> {
dst: *mut T,
initialized: usize,
}

#[cfg(feature = "const-generics")]
impl<T, const N: usize> Drop for ArrayGuard<T, N> {
fn drop(&mut self) {
debug_assert!(self.initialized <= N);
let initialized_part = core::ptr::slice_from_raw_parts_mut(self.dst, self.initialized);
unsafe {
core::ptr::drop_in_place(initialized_part);
}
}
}

#[cfg(feature = "const-generics")]
fn try_create_array<E, F, T, const N: usize>(mut cb: F) -> Result<[T; N], E>
where
F: FnMut(usize) -> Result<T, E>,
{
let mut array: core::mem::MaybeUninit<[T; N]> = core::mem::MaybeUninit::uninit();
let mut guard: ArrayGuard<T, N> = ArrayGuard {
dst: array.as_mut_ptr() as _,
initialized: 0,
};
unsafe {
for (idx, value_ptr) in (&mut *array.as_mut_ptr()).iter_mut().enumerate() {
core::ptr::write(value_ptr, cb(idx)?);
guard.initialized += 1;
}
core::mem::forget(guard);
Ok(array.assume_init())
}
}
52 changes: 52 additions & 0 deletions src/types/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,41 @@ impl PySequence {
}
}

#[cfg(feature = "const-generics")]
impl<'a, T, const N: usize> FromPyObject<'a> for [T; N]
where
T: FromPyObject<'a>,
{
#[cfg(not(feature = "nightly"))]
fn extract(obj: &'a PyAny) -> PyResult<Self> {
create_array_from_obj(obj)
}

#[cfg(feature = "nightly")]
default fn extract(obj: &'a PyAny) -> PyResult<Self> {
create_array_from_obj(obj)
}
}

#[cfg(all(feature = "const-generics", feature = "nightly"))]
impl<'source, T, const N: usize> FromPyObject<'source> for [T; N]
where
for<'a> T: FromPyObject<'a> + crate::buffer::Element,
{
fn extract(obj: &'source PyAny) -> PyResult<Self> {
let mut array = create_array_from_obj(obj)?;
if let Ok(buf) = crate::buffer::PyBuffer::get(obj) {
if buf.dimensions() == 1 && buf.copy_to_slice(obj.py(), &mut array).is_ok() {
buf.release(obj.py());
return Ok(array);
}
buf.release(obj.py());
}
Ok(array)
}
}

#[cfg(not(feature = "const-generics"))]
macro_rules! array_impls {
($($N:expr),+) => {
$(
Expand Down Expand Up @@ -303,6 +338,7 @@ macro_rules! array_impls {
}
}

#[cfg(not(feature = "const-generics"))]
array_impls!(
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,
26, 27, 28, 29, 30, 31, 32
Expand Down Expand Up @@ -343,6 +379,21 @@ where
}
}

#[cfg(feature = "const-generics")]
fn create_array_from_obj<'s, T, const N: usize>(obj: &'s PyAny) -> PyResult<[T; N]>
where
T: FromPyObject<'s>,
{
let seq = <PySequence as PyTryFrom>::try_from(obj)?;
crate::types::try_create_array(|idx| {
seq.get_item(idx as isize)
.map_err(|_| {
exceptions::PyBufferError::py_err("Slice length does not match buffer length.")
})?
.extract::<T>()
})
}

fn extract_sequence<'s, T>(obj: &'s PyAny) -> PyResult<Vec<T>>
where
T: FromPyObject<'s>,
Expand All @@ -355,6 +406,7 @@ where
Ok(v)
}

#[cfg(not(feature = "const-generics"))]
fn extract_sequence_into_slice<'s, T>(obj: &'s PyAny, slice: &mut [T]) -> PyResult<()>
where
T: FromPyObject<'s>,
Expand Down

0 comments on commit 5a92708

Please sign in to comment.