Skip to content

Commit 4b75206

Browse files
authored
Merge pull request #372 from termoshtt/elem_ref
Get a correct reference to an element from ArrayView
2 parents 2e8aba8 + 7c42e19 commit 4b75206

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

src/arraytraits.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,62 @@ impl<S, D, I> IndexMut<I> for ArrayBase<S, D>
9494
}
9595
}
9696

97+
impl<'a, A, D> ArrayView<'a, A, D>
98+
where
99+
D: Dimension,
100+
{
101+
/// Get a reference of a element through the view.
102+
///
103+
/// This is a replacement of `Index::index` since it forces us a wrong lifetime
104+
/// https://github.com/bluss/rust-ndarray/issues/371
105+
pub fn elem<I: NdIndex<D>>(&self, index: I) -> &'a A {
106+
debug_bounds_check!(self, index);
107+
unsafe {
108+
&*self.as_ptr().offset(
109+
index
110+
.index_checked(&self.dim, &self.strides)
111+
.unwrap_or_else(|| array_out_of_bounds()),
112+
)
113+
}
114+
}
115+
116+
/// Get a reference of a element through the view without boundary check
117+
///
118+
/// This is a replacement of `Index::index` since it forces us a wrong lifetime
119+
/// https://github.com/bluss/rust-ndarray/issues/371
120+
pub fn uelem<I: NdIndex<D>>(&self, index: I) -> &'a A {
121+
debug_bounds_check!(self, index);
122+
unsafe { &*self.as_ptr().offset(index.index_unchecked(&self.strides)) }
123+
}
124+
}
125+
126+
impl<'a, A, D> ArrayViewMut<'a, A, D>
127+
where
128+
D: Dimension,
129+
{
130+
/// Convert a mutable array view to a mutable reference of a element.
131+
pub fn into_elem<I: NdIndex<D>>(mut self, index: I) -> &'a mut A {
132+
debug_bounds_check!(self, index);
133+
unsafe {
134+
&mut *self.as_mut_ptr().offset(
135+
index
136+
.index_checked(&self.dim, &self.strides)
137+
.unwrap_or_else(|| array_out_of_bounds()),
138+
)
139+
}
140+
}
141+
142+
/// Convert a mutable array view to a mutable reference of a element without boundary check
143+
pub fn into_elem_unchecked<I: NdIndex<D>>(mut self, index: I) -> &'a mut A {
144+
debug_bounds_check!(self, index);
145+
unsafe {
146+
&mut *self.as_mut_ptr().offset(
147+
index.index_unchecked(&self.strides),
148+
)
149+
}
150+
}
151+
}
152+
97153
/// Return `true` if the array shapes and all elements of `self` and
98154
/// `rhs` are equal. Return `false` otherwise.
99155
impl<S, S2, D> PartialEq<ArrayBase<S2, D>> for ArrayBase<S, D>

0 commit comments

Comments
 (0)