1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use super::immutable::ArrayView;
use super::mutable_core::ArrayViewMut;
use super::raw::{
assert_exclusive_window, checked_block_range, raw_range_from_ptr, raw_range_from_ptr_mut,
raw_slice_from_ptr_mut,
};
use crate::application::array::Array;
use crate::application::iter::{ElementIterMut, IndexedIterMut, TaskPartitionsMut};
use crate::domain::error::{LetoError, Result};
use crate::domain::slice::SliceArg;
use crate::infrastructure::storage::VecStorage;
impl<'a, T, const N: usize> ArrayViewMut<'a, T, N> {
/// Iterator over `(multi-index, &mut element)` pairs in logical row-major
/// order (leto `indexed_iter_mut` parity).
///
/// # Errors
/// Returns [`LetoError`] if the layout is out of bounds or cannot prove
/// that each logical index addresses a distinct physical element.
#[inline]
pub fn indexed_iter_mut(self) -> Result<IndexedIterMut<'a, T, N>> {
IndexedIterMut::new(self)
}
/// Iterator over mutable elements in logical row-major order.
///
/// # Errors
/// Returns [`LetoError`] if the layout is out of bounds or cannot prove
/// that each logical index addresses a distinct physical element.
#[inline]
pub fn try_iter_mut(self) -> Result<ElementIterMut<'a, T, N>> {
Ok(ElementIterMut::from_indexed(self.indexed_iter_mut()?))
}
/// Split this logical row-major domain into disjoint mutable task partitions.
///
/// Partitions expose only range-limited element iterators and never expose
/// the complete backing slice, which makes them suitable for a scheduler
/// boundary without creating overlapping mutable access paths.
///
/// # Errors
/// Returns [`LetoError`] when `chunk_size` is zero, storage is invalid, or
/// the layout is not provably injective.
#[inline]
pub fn task_partitions_mut(self, chunk_size: usize) -> Result<TaskPartitionsMut<'a, T, N>> {
TaskPartitionsMut::new(self, chunk_size)
}
/// Consume the view and return the backing mutable slice with lifetime `'a`.
///
/// # Panics
///
/// Panics when the view was yielded by a mutable lane/axis iterator over an
/// interleaved layout (see [`as_view`](Self::as_view)).
#[inline]
pub fn into_slice(self) -> &'a mut [T] {
assert_exclusive_window(self.window_shared);
// SAFETY: self.ptr is valid for self.len elements and lifetime 'a, and
// the assertion above establishes the window is exclusively owned.
unsafe { raw_slice_from_ptr_mut(self.ptr, self.len) }
}
/// Slice the mutable view, returning a sub-view.
#[inline]
pub fn slice_mut(self, ranges: &[(usize, usize, isize); N]) -> Result<ArrayViewMut<'a, T, N>> {
let sliced_layout = self.layout.slice(ranges)?;
Ok(self.with_layout(sliced_layout))
}
/// Slice the mutable view with leto-style arguments.
#[inline]
pub fn slice_with_mut<const M: usize>(
self,
args: &[SliceArg],
) -> Result<ArrayViewMut<'a, T, M>> {
let sliced_layout = self.layout.slice_with(args)?;
Ok(self.with_layout(sliced_layout))
}
/// Transpose the mutable view by permuting axes.
#[inline]
pub fn transpose_mut(self, axes: [usize; N]) -> Result<ArrayViewMut<'a, T, N>> {
let transposed_layout = self.layout.transpose(axes)?;
Ok(self.with_layout(transposed_layout))
}
/// Broadcast the mutable view to a larger dimensional shape.
///
/// Returns an error when broadcasting would introduce zero-stride aliasing.
#[inline]
pub fn broadcast_mut<const M: usize>(
self,
target_shape: [usize; M],
) -> Result<ArrayViewMut<'a, T, M>> {
let broadcasted_layout = self.layout.broadcast(target_shape)?;
if broadcasted_layout.has_zero_stride_aliasing() {
return Err(LetoError::IncompatibleBroadcast {
from: self.layout.shape().to_vec(),
to: target_shape.to_vec(),
});
}
Ok(self.with_layout(broadcasted_layout))
}
/// Reinterpret this mutable view with a new shape without copying.
///
/// The current layout must be dense row-major and the new shape must have
/// the same logical element count.
#[inline]
pub fn reshape_mut<const M: usize>(self, shape: [usize; M]) -> Result<ArrayViewMut<'a, T, M>> {
let reshaped_layout = self.layout.reshape(shape)?;
Ok(self.with_layout(reshaped_layout))
}
/// Named alias for [`transpose_mut`](Self::transpose_mut).
#[inline]
pub fn permute_mut(self, axes: [usize; N]) -> Result<ArrayViewMut<'a, T, N>> {
self.transpose_mut(axes)
}
/// Materialize this mutable view into C-contiguous row-major storage.
pub fn to_contiguous(&self) -> Array<T, VecStorage<T>, N>
where
T: Clone,
{
if self.window_shared {
// A whole-window borrow would alias sibling views' elements, so
// clone element-by-element through checked per-element access.
let size = self.size();
let shape = self.shape();
let mut values: Vec<T> = Vec::with_capacity(size);
let mut index = [0usize; N];
for _ in 0..size {
values.push(
self.get(index)
.expect("invariant: logical index is in bounds")
.clone(),
);
for d in (0..N).rev() {
index[d] += 1;
if index[d] < shape[d] {
break;
}
index[d] = 0;
}
}
return Array::<T, VecStorage<T>, N>::from_shape_vec(shape, values)
.expect("logical row-major materialization has matching shape and storage");
}
let view = ArrayView::new(self.layout, self.data());
view.to_contiguous()
}
/// Returns true when the view is canonically C-contiguous at offset 0.
#[inline]
pub fn is_c_contiguous(&self) -> bool {
self.layout.is_c_contiguous()
}
/// Returns true when the view is canonically Fortran-contiguous at offset 0.
#[inline]
pub fn is_f_contiguous(&self) -> bool {
self.layout.is_f_contiguous()
}
/// Returns true when the view's elements occupy a dense block in some
/// memory order (C or F), independent of offset.
#[inline]
pub fn is_contiguous(&self) -> bool {
self.layout.is_contiguous()
}
/// Returns true when the view's strides are canonically C (row-major),
/// independent of the base offset (offset-independent half of
/// [`is_c_contiguous`](Self::is_c_contiguous)).
#[inline]
pub fn is_c_dense(&self) -> bool {
self.layout.is_c_dense()
}
/// Returns true when the view's strides are canonically Fortran
/// (column-major), independent of the base offset (offset-independent half
/// of [`is_f_contiguous`](Self::is_f_contiguous)).
#[inline]
pub fn is_f_dense(&self) -> bool {
self.layout.is_f_dense()
}
/// Expose the underlying slice if the elements form a dense row-major
/// (C-order) block, independent of offset.
#[inline]
pub fn as_slice(&self) -> Option<&[T]> {
if self.layout.is_c_dense() {
let range = checked_block_range(&self.layout, self.len)?;
// SAFETY: `ptr` is valid for `len` elements and `range` is in
// bounds; a C-dense layout's block is exactly the view's own
// elements, so this slice never covers a sibling view's elements
// even when the window is shared.
unsafe { Some(raw_range_from_ptr(self.ptr, range)) }
} else {
None
}
}
/// Expose the underlying mutable slice if the elements form a dense
/// row-major (C-order) block, independent of offset.
#[inline]
pub fn as_mut_slice(&mut self) -> Option<&mut [T]> {
if self.layout.is_c_dense() {
let range = checked_block_range(&self.layout, self.len)?;
// SAFETY: `ptr` is valid for `len` elements and `range` is in
// bounds; a C-dense block is exactly the view's own elements,
// which the view exclusively owns even when yielded by a mutable
// iterator (sibling views' elements are disjoint).
unsafe { Some(raw_range_from_ptr_mut(self.ptr, range)) }
} else {
None
}
}
/// Expose the underlying slice if the elements form a dense block in some
/// memory order (C or F), independent of offset. Physical memory order.
#[inline]
pub fn as_slice_memory_order(&self) -> Option<&[T]> {
if self.layout.is_contiguous() {
let range = checked_block_range(&self.layout, self.len)?;
// SAFETY: `ptr` is valid for `len` elements and `range` is in
// bounds; a contiguous layout's dense block is exactly the view's
// own elements (no sibling overlap).
unsafe { Some(raw_range_from_ptr(self.ptr, range)) }
} else {
None
}
}
/// Expose the underlying mutable slice if the elements form a dense block
/// in some memory order (C or F), independent of offset. This is the
/// `leto::as_slice_memory_order_mut` analogue Apollo's in-place FFT
/// butterfly kernels require.
#[inline]
pub fn as_mut_slice_memory_order(&mut self) -> Option<&mut [T]> {
if self.layout.is_contiguous() {
let range = checked_block_range(&self.layout, self.len)?;
// SAFETY: `ptr` is valid for `len` elements and `range` is in
// bounds; a contiguous layout's dense block is exactly the view's
// own elements, exclusively owned even for iterator-yielded
// sub-views (siblings are disjoint).
unsafe { Some(raw_range_from_ptr_mut(self.ptr, range)) }
} else {
None
}
}
/// Return an iterator yielding mutable subviews of rank `M` (where `M = N - 1`) along `axis`.
#[inline]
pub fn axis_iter_mut<const M: usize>(
self,
axis: usize,
) -> Result<crate::application::iter::AxisIterMut<'a, T, N, M>>
where
crate::domain::remove_axis::RankMarker<N>: crate::domain::remove_axis::RemoveAxis<
N,
SmallerShape = [usize; M],
SmallerStrides = [isize; M],
>,
{
crate::application::iter::AxisIterMut::new(
self,
axis,
crate::domain::remove_axis::RankMarker::<N>,
)
}
/// Return an iterator yielding mutable 1-D lane views *along* `axis`
/// (leto `lanes_mut` parity; `M = N - 1` is the complement rank).
///
/// # Errors
/// [`LetoError`] if `axis >= N`, the layout does not fit its storage, or the
/// layout aliases (a zero stride).
#[inline]
pub fn lanes_mut<const M: usize>(
self,
axis: usize,
) -> Result<crate::application::iter::LanesMut<'a, T, N, M>>
where
crate::domain::remove_axis::RankMarker<N>: crate::domain::remove_axis::RemoveAxis<
N,
SmallerShape = [usize; M],
SmallerStrides = [isize; M],
>,
{
crate::application::iter::LanesMut::new(
self,
axis,
crate::domain::remove_axis::RankMarker::<N>,
)
}
}