Skip to content

Commit daa317c

Browse files
committed
Make SliceBox hide its internals and add a test case for SliceBox-induced type confusion.
1 parent dc72f13 commit daa317c

File tree

3 files changed

+25
-5
lines changed

3 files changed

+25
-5
lines changed

src/array.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -448,8 +448,8 @@ impl<T: Element, D: Dimension> PyArray<T, D> {
448448
ID: IntoDimension<Dim = D>,
449449
{
450450
let dims = dims.into_dimension();
451+
let data_ptr = data_ptr.unwrap_or(boxed_slice.as_ptr());
451452
let container = SliceBox::new(boxed_slice);
452-
let data_ptr = data_ptr.unwrap_or(container.data.as_ptr());
453453
let cell = pyo3::PyClassInitializer::from(container)
454454
.create_cell(py)
455455
.expect("Object creation failed.");

src/slice_box.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
use pyo3::class::impl_::{PyClassImpl, ThreadCheckerStub};
22
use pyo3::pyclass::PyClass;
33
use pyo3::pyclass_slots::PyClassDummySlot;
4-
use pyo3::{ffi, type_object, types::PyAny, PyCell};
4+
use pyo3::type_object::{LazyStaticType, PyTypeInfo};
5+
use pyo3::{ffi, types::PyAny, PyCell};
56

67
pub(crate) struct SliceBox<T> {
7-
pub(crate) data: Box<[T]>,
8+
data: Box<[T]>,
89
}
910

1011
impl<T> SliceBox<T> {
@@ -33,7 +34,7 @@ where
3334
type ThreadChecker = ThreadCheckerStub<Self>;
3435
}
3536

36-
unsafe impl<T> type_object::PyTypeInfo for SliceBox<T>
37+
unsafe impl<T> PyTypeInfo for SliceBox<T>
3738
where
3839
T: Send,
3940
{
@@ -43,7 +44,6 @@ where
4344

4445
#[inline]
4546
fn type_object_raw(py: pyo3::Python) -> *mut ffi::PyTypeObject {
46-
use pyo3::type_object::LazyStaticType;
4747
static TYPE_OBJECT: LazyStaticType = LazyStaticType::new();
4848
TYPE_OBJECT.get_or_init::<Self>(py)
4949
}

tests/to_py.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,3 +232,23 @@ fn to_pyarray_object_array() {
232232
}
233233
})
234234
}
235+
236+
#[test]
237+
fn slice_box_type_confusion() {
238+
use ndarray::Array2;
239+
use pyo3::{
240+
types::{PyDict, PyString},
241+
ToPyObject,
242+
};
243+
244+
pyo3::Python::with_gil(|py| {
245+
let mut nd_arr = Array2::from_shape_fn((2, 3), |(_, _)| py.None());
246+
nd_arr[(0, 2)] = PyDict::new(py).to_object(py);
247+
nd_arr[(1, 0)] = PyString::new(py, "Hello:)").to_object(py);
248+
249+
let _py_arr = nd_arr.into_pyarray(py);
250+
251+
let vec = vec![1, 2, 3];
252+
let _arr = vec.into_pyarray(py);
253+
});
254+
}

0 commit comments

Comments
 (0)