Skip to content

Commit b4f8b42

Browse files
committed
FEAT: Add aview_mut2
aview_mut2 is the mutable version of aview2. It lets us create (some) array views from nested arrays, without dynamic or runtime dimension checks as needed in into_shape.
1 parent 58b57ab commit b4f8b42

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/free_functions.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,40 @@ pub fn aview_mut1<A>(xs: &mut [A]) -> ArrayViewMut1<A> {
124124
ArrayViewMut::from(xs)
125125
}
126126

127+
/// Create a two-dimensional read-write array view with elements borrowing `xs`.
128+
///
129+
/// # Example
130+
///
131+
/// ```
132+
/// use ndarray::aview_mut2;
133+
///
134+
/// fn main() {
135+
/// // The inner (nested) array must be of length 1 to 16, but the outer
136+
/// // can be of any length.
137+
/// let mut data = [[0.; 2]; 128];
138+
/// {
139+
/// // Make a 128 x 2 mut array view then turn it into 2 x 128
140+
/// let mut a = aview_mut2(&mut data).reversed_axes();
141+
/// // Make the first row ones and second row minus ones.
142+
/// a.row_mut(0).fill(1.);
143+
/// a.row_mut(1).fill(-1.);
144+
/// }
145+
/// // look at the start of the result
146+
/// assert_eq!(&data[..3], [[1., -1.], [1., -1.], [1., -1.]]);
147+
/// }
148+
/// ```
149+
pub fn aview_mut2<A, V: FixedInitializer<Elem=A>>(xs: &mut [V]) -> ArrayViewMut2<A> {
150+
let cols = V::len();
151+
let rows = xs.len();
152+
let data = unsafe {
153+
slice::from_raw_parts_mut(xs.as_mut_ptr() as *mut A, cols * rows)
154+
};
155+
let dim = Ix2(rows, cols);
156+
unsafe {
157+
ArrayViewMut::from_shape_ptr(dim, data.as_mut_ptr())
158+
}
159+
}
160+
127161
/// Fixed-size array used for array initialization
128162
pub unsafe trait FixedInitializer {
129163
type Elem;

0 commit comments

Comments
 (0)