Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make ArrayBase::get_ptr(_mut) public to enable indexing into raw views. #1151

Merged
merged 2 commits into from Jul 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 34 additions & 4 deletions src/impl_methods.rs
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
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