Skip to content

Commit

Permalink
Merge pull request #1151 from adamreichold/pub-get-ptr
Browse files Browse the repository at this point in the history
Make ArrayBase::get_ptr(_mut) public to enable indexing into raw views.
  • Loading branch information
jturner314 committed Jul 30, 2022
2 parents dedb15f + eb50663 commit 853384a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
38 changes: 34 additions & 4 deletions src/impl_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -732,13 +732,26 @@ where
/// ```
pub fn get<I>(&self, index: I) -> Option<&A>
where
I: NdIndex<D>,
S: Data,
I: NdIndex<D>,
{
unsafe { self.get_ptr(index).map(|ptr| &*ptr) }
}

pub(crate) fn get_ptr<I>(&self, index: I) -> Option<*const A>
/// Return a raw pointer to the element at `index`, or return `None`
/// if the index is out of bounds.
///
/// ```
/// use ndarray::arr2;
///
/// let a = arr2(&[[1., 2.], [3., 4.]]);
///
/// let v = a.raw_view();
/// let p = a.get_ptr((0, 1)).unwrap();
///
/// assert_eq!(unsafe { *p }, 2.);
/// ```
pub fn get_ptr<I>(&self, index: I) -> Option<*const A>
where
I: NdIndex<D>,
{
Expand All @@ -755,10 +768,27 @@ where
S: DataMut,
I: NdIndex<D>,
{
unsafe { self.get_ptr_mut(index).map(|ptr| &mut *ptr) }
unsafe { self.get_mut_ptr(index).map(|ptr| &mut *ptr) }
}

pub(crate) fn get_ptr_mut<I>(&mut self, index: I) -> Option<*mut A>
/// Return a raw pointer to the element at `index`, or return `None`
/// if the index is out of bounds.
///
/// ```
/// use ndarray::arr2;
///
/// let mut a = arr2(&[[1., 2.], [3., 4.]]);
///
/// let v = a.raw_view_mut();
/// let p = a.get_mut_ptr((0, 1)).unwrap();
///
/// unsafe {
/// *p = 5.;
/// }
///
/// assert_eq!(a.get((0, 1)), Some(&5.));
/// ```
pub fn get_mut_ptr<I>(&mut self, index: I) -> Option<*mut A>
where
S: RawDataMut,
I: NdIndex<D>,
Expand Down
4 changes: 2 additions & 2 deletions src/impl_views/indexing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ where
fn index(mut self, index: I) -> &'a mut A {
debug_bounds_check!(self, index);
unsafe {
match self.get_ptr_mut(index) {
match self.get_mut_ptr(index) {
Some(ptr) => &mut *ptr,
None => array_out_of_bounds(),
}
Expand All @@ -182,7 +182,7 @@ where
fn get(mut self, index: I) -> Option<&'a mut A> {
debug_bounds_check!(self, index);
unsafe {
match self.get_ptr_mut(index) {
match self.get_mut_ptr(index) {
Some(ptr) => Some(&mut *ptr),
None => None,
}
Expand Down

0 comments on commit 853384a

Please sign in to comment.