| 722 | /// Implementation of functionality for [`PyArray<T, D>`]. |
| 723 | #[doc(alias = "PyArray")] |
| 724 | pub trait PyArrayMethods<'py, T, D>: PyUntypedArrayMethods<'py> + Sized { |
| 725 | /// Access an untyped representation of this array. |
| 726 | fn as_untyped(&self) -> &Bound<'py, PyUntypedArray>; |
| 727 | |
| 728 | /// Returns a pointer to the first element of the array. |
| 729 | fn data(&self) -> *mut T; |
| 730 | |
| 731 | /// Same as [`shape`][PyUntypedArrayMethods::shape], but returns `D` instead of `&[usize]`. |
| 732 | #[inline(always)] |
| 733 | fn dims(&self) -> D |
| 734 | where |
| 735 | D: Dimension, |
| 736 | { |
| 737 | D::from_dimension(&Dim(self.shape())).expect(DIMENSIONALITY_MISMATCH_ERR) |
| 738 | } |
| 739 | |
| 740 | /// Returns an immutable view of the internal data as a slice. |
| 741 | /// |
| 742 | /// # Safety |
| 743 | /// |
| 744 | /// Calling this method is undefined behaviour if the underlying array |
| 745 | /// is aliased mutably by other instances of `PyArray` |
| 746 | /// or concurrently modified by Python or other native code. |
| 747 | /// |
| 748 | /// Please consider the safe alternative [`PyReadonlyArray::as_slice`]. |
| 749 | unsafe fn as_slice(&self) -> Result<&[T], AsSliceError> |
| 750 | where |
| 751 | T: Element, |
| 752 | D: Dimension, |
| 753 | { |
| 754 | let len = self.len(); |
| 755 | if len == 0 { |
| 756 | // We can still produce a slice over zero objects regardless of whether |
| 757 | // the underlying pointer is aligned or not. |
| 758 | Ok(&[]) |
| 759 | } else if self.is_aligned() && self.is_contiguous() { |
| 760 | Ok(slice::from_raw_parts(self.data(), len)) |
| 761 | } else { |
| 762 | Err(AsSliceError) |
| 763 | } |
| 764 | } |
| 765 | |
| 766 | /// Returns a mutable view of the internal data as a slice. |
| 767 | /// |
| 768 | /// # Safety |
| 769 | /// |
| 770 | /// Calling this method is undefined behaviour if the underlying array |
| 771 | /// is aliased immutably or mutably by other instances of [`PyArray`] |
| 772 | /// or concurrently modified by Python or other native code. |
| 773 | /// |
| 774 | /// Please consider the safe alternative [`PyReadwriteArray::as_slice_mut`]. |
| 775 | #[allow(clippy::mut_from_ref)] |
| 776 | unsafe fn as_slice_mut(&self) -> Result<&mut [T], AsSliceError> |
| 777 | where |
| 778 | T: Element, |
| 779 | D: Dimension, |
| 780 | { |
| 781 | let len = self.len(); |
no outgoing calls
no test coverage detected