rust-numpy icon indicating copy to clipboard operation
rust-numpy copied to clipboard

Safely access data in PyUntypedArray

Open flying-sheep opened this issue 1 year ago • 0 comments

PyUntypedArrayMethods::as_array_ptr doesn’t describe under which circumstances the returned pointer is convertible into a reference.

Since the requirements are rather hairy, it would be great to have a way to access the data safely without going through unsafe. Would it e.g. be possible to have this?

trait PyUntypedArrayMethods<'py> {
    ...
    fn bytes<'a>(&'a self) -> &'a [u8] {
        let ptr = self.as_array_ptr();
        let n_bytes = self.len() * self.dtype().itemsize();
        unsafe {
            let p = (*ptr).data.cast();
            slice::from_raw_parts(p, n_bytes)
        }
    }
}

Because we currently implement this ourselves, but without any of the aforementioned safety information, we can’t really be sure if it’s safe.

flying-sheep avatar Jan 16 '25 12:01 flying-sheep