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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
use crate::application::array::Array;
use crate::application::iter::{
AxisChunks, ElementIter, ElementIterMut, ExactChunks, IndexedIter, IndexedIterMut, Windows,
};
use crate::domain::error::{LetoError, Result};
use crate::domain::layout::Layout;
use crate::domain::slice::SliceArg;
use crate::infrastructure::storage::{SliceStorage, VecStorage};
/// Computes the physical `[offset, offset + size)` range covered by a layout
/// whose elements form a single dense block. Returns `None` only on size
/// overflow. Shared by the contiguous-slice accessors of both view types.
#[inline]
fn dense_block_range<const N: usize>(layout: &Layout<N>) -> Option<core::ops::Range<usize>> {
let start = layout.offset;
let end = start.checked_add(layout.checked_size().ok()?)?;
Some(start..end)
}
/// A read-only zero-copy view of an N-dimensional strided array.
#[derive(Clone, Copy)]
pub struct ArrayView<'a, T, const N: usize> {
pub(crate) layout: Layout<N>,
pub(crate) data: &'a [T],
}
impl<'a, T, const N: usize> ArrayView<'a, T, N> {
/// Create a new ArrayView from a layout and raw slice.
#[inline]
pub const fn new(layout: Layout<N>, data: &'a [T]) -> Self {
Self { layout, data }
}
/// Create a bounds-checked ArrayView from a layout and raw slice.
#[inline]
pub fn try_new(layout: Layout<N>, data: &'a [T]) -> Result<Self> {
layout.validate_storage_len(data.len())?;
Ok(Self { layout, data })
}
/// Returns the shape of the view.
#[inline]
pub const fn shape(&self) -> [usize; N] {
self.layout.shape
}
/// Returns the strides of the view.
#[inline]
pub const fn strides(&self) -> [isize; N] {
self.layout.strides
}
/// Returns the offset of the view.
#[inline]
pub const fn offset(&self) -> usize {
self.layout.offset
}
/// Returns the total logical size of the view.
#[inline]
pub fn size(&self) -> usize {
self.layout.size()
}
/// Returns the layout of the view.
#[inline]
pub const fn layout(&self) -> Layout<N> {
self.layout
}
/// Returns the raw data slice.
#[inline]
pub const fn data(&self) -> &'a [T] {
self.data
}
/// Iterator over the view's elements in logical row-major order
/// (leto `iter` parity). The iterator borrows the view's data for `'a`,
/// so it outlives a temporary view produced by `array.view().iter()`.
#[inline]
pub fn iter(&self) -> ElementIter<'a, T, N> {
ElementIter::new(self)
}
/// Iterator over `(multi-index, &element)` pairs in logical row-major order
/// (leto `indexed_iter` parity).
#[inline]
pub fn indexed_iter(&self) -> IndexedIter<'a, T, N> {
IndexedIter::new(self)
}
/// Zero-copy iterator over non-overlapping chunks of `chunk_shape`
/// (leto `exact_chunks` parity). Each yielded view shares this view's
/// strides and backing storage.
///
/// # Errors
/// [`LetoError`] if any `chunk_shape[i]` is `0` or the chunk grid overflows
/// `usize`.
#[inline]
pub fn exact_chunks(&self, chunk_shape: [usize; N]) -> Result<ExactChunks<'a, T, N>> {
ExactChunks::new(self, chunk_shape)
}
/// Zero-copy iterator over chunks along `axis` (leto
/// `axis_chunks_iter` parity). The final yielded view carries the
/// remainder when present.
///
/// # Errors
/// [`LetoError`] if `axis >= N` or `chunk_len == 0`.
#[inline]
pub fn axis_chunks_iter(&self, axis: usize, chunk_len: usize) -> Result<AxisChunks<'a, T, N>> {
AxisChunks::new(self, axis, chunk_len)
}
/// Zero-copy iterator over every sliding window of shape `window_shape`
/// (leto `windows` parity). Each yielded view shares this view's strides
/// and backing storage.
///
/// # Errors
/// [`LetoError`] if any `window_shape[i]` is `0` or exceeds `shape[i]`.
#[inline]
pub fn windows(&self, window_shape: [usize; N]) -> Result<Windows<'a, T, N>> {
Windows::new(self, window_shape)
}
/// Get a reference to the element at the specified index.
#[inline]
pub fn get(&self, index: [usize; N]) -> Result<&T> {
let offset = self.layout.offset_of(index)?;
if offset >= self.data.len() {
return Err(LetoError::StorageError {
reason: format!(
"physical offset {offset} exceeds backing slice length {}",
self.data.len()
),
});
}
Ok(&self.data[offset])
}
/// Slice the view, returning a sub-view.
#[inline]
pub fn slice(&self, ranges: &[(usize, usize, isize); N]) -> Result<ArrayView<'a, T, N>> {
let sliced_layout = self.layout.slice(ranges)?;
Ok(ArrayView::new(sliced_layout, self.data))
}
/// Slice the view with leto-style arguments.
#[inline]
pub fn slice_with<const M: usize>(&self, args: &[SliceArg]) -> Result<ArrayView<'a, T, M>> {
let sliced_layout = self.layout.slice_with(args)?;
Ok(ArrayView::new(sliced_layout, self.data))
}
/// Transpose the view by permuting axes.
#[inline]
pub fn transpose(&self, axes: [usize; N]) -> Result<ArrayView<'a, T, N>> {
let transposed_layout = self.layout.transpose(axes)?;
Ok(ArrayView::new(transposed_layout, self.data))
}
/// Broadcast the view to a larger dimensional shape.
#[inline]
pub fn broadcast<const M: usize>(
&self,
target_shape: [usize; M],
) -> Result<ArrayView<'a, T, M>> {
let broadcasted_layout = self.layout.broadcast(target_shape)?;
Ok(ArrayView::new(broadcasted_layout, self.data))
}
/// Reinterpret this 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<const M: usize>(&self, shape: [usize; M]) -> Result<ArrayView<'a, T, M>> {
let reshaped_layout = self.layout.reshape(shape)?;
Ok(ArrayView::new(reshaped_layout, self.data))
}
/// Named alias for [`transpose`](Self::transpose).
#[inline]
pub fn permute(&self, axes: [usize; N]) -> Result<ArrayView<'a, T, N>> {
self.transpose(axes)
}
/// Materialize this view into C-contiguous row-major storage.
///
/// Dense row-major views clone the exposed slice. Strided, transposed, or
/// broadcasted views are copied in logical row-major order.
pub fn to_contiguous(&self) -> Array<T, VecStorage<T>, N>
where
T: Clone,
{
let data = match self.as_slice() {
Some(slice) => slice.to_vec(),
None => {
let size = self.layout.size();
let mut values: Vec<T> = Vec::with_capacity(size);
values.extend(self.iter().cloned());
values
}
};
Array::<T, VecStorage<T>, N>::from_shape_vec(self.shape(), data)
.expect("logical row-major materialization has matching shape and storage")
}
/// Wrap this view as a **zero-copy** borrowed [`Array`] over [`SliceStorage`],
/// sharing the view's layout (offset + strides) and backing slice with no
/// allocation or copy.
///
/// Because the borrowed array carries the same layout, it indexes
/// identically to the view for both contiguous and strided/offset views, so
/// it can feed any storage-generic `Array<T, S, N>` consumer without the
/// [`to_contiguous`](Self::to_contiguous) materialization. Prefer this over
/// `to_contiguous` when the consumer only reads the input.
#[inline]
#[must_use]
pub fn as_array(&self) -> Array<T, SliceStorage<'a, T>, N> {
// The (layout, data) pair is exactly the one this view already indexes
// through, so the borrowed array's `get` (layout.offset_of into
// storage.as_slice) reproduces the view's element access bit-for-bit.
Array::new(self.layout, SliceStorage::new(self.data))
.expect("view layout is valid for its backing slice")
}
/// 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<&'a [T]> {
if self.layout.is_c_dense() {
self.data.get(dense_block_range(&self.layout)?)
} else {
None
}
}
/// Expose the underlying slice if the elements form a dense block in some
/// memory order (C or F), independent of offset. The returned slice is in
/// physical memory order, matching `leto::as_slice_memory_order`.
#[inline]
pub fn as_slice_memory_order(&self) -> Option<&'a [T]> {
if self.layout.is_contiguous() {
self.data.get(dense_block_range(&self.layout)?)
} else {
None
}
}
/// Return an iterator yielding read-only subviews of rank `M` (where `M = N - 1`) along `axis`.
#[inline]
pub fn axis_iter<const M: usize>(
&self,
axis: usize,
) -> Result<crate::application::iter::AxisIter<'_, 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::AxisIter::new(
self,
axis,
crate::domain::remove_axis::RankMarker::<N>,
)
}
/// Return an iterator yielding read-only 1-D lane views *along* `axis`
/// (leto `lanes` parity; `M = N - 1` is the complement rank). Dual of
/// [`axis_iter`](Self::axis_iter): one lane per complement coordinate.
///
/// # Errors
/// [`LetoError`] if `axis >= N` or the layout does not fit its storage.
#[inline]
pub fn lanes<const M: usize>(
&self,
axis: usize,
) -> Result<crate::application::iter::Lanes<'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::Lanes::new(
self,
axis,
crate::domain::remove_axis::RankMarker::<N>,
)
}
/// Reborrow the read-only view with a shorter lifetime.
#[inline]
pub fn reborrow(&self) -> ArrayView<'_, T, N> {
ArrayView::new(self.layout, self.data)
}
}
// ── ArrayViewMut ──
/// A mutable zero-copy view of an N-dimensional strided array.
pub struct ArrayViewMut<'a, T, const N: usize> {
pub(crate) layout: Layout<N>,
pub(crate) ptr: std::ptr::NonNull<T>,
pub(crate) len: usize,
pub(crate) _marker: std::marker::PhantomData<&'a mut [T]>,
}
impl<'a, T, const N: usize> ArrayViewMut<'a, T, N> {
/// Create a new ArrayViewMut from a layout and mutable slice.
#[inline]
pub fn new(layout: Layout<N>, data: &'a mut [T]) -> Self {
Self {
layout,
ptr: unsafe { std::ptr::NonNull::new_unchecked(data.as_mut_ptr()) },
len: data.len(),
_marker: std::marker::PhantomData,
}
}
/// Create a bounds-checked ArrayViewMut from a layout and mutable slice.
#[inline]
pub fn try_new(layout: Layout<N>, data: &'a mut [T]) -> Result<Self> {
layout.validate_storage_len(data.len())?;
Ok(Self::new(layout, data))
}
/// Reborrow the mutable view with a shorter lifetime.
#[inline]
pub fn reborrow(&mut self) -> ArrayViewMut<'_, T, N> {
ArrayViewMut {
layout: self.layout,
ptr: self.ptr,
len: self.len,
_marker: std::marker::PhantomData,
}
}
/// Borrow this mutable view as an immutable [`ArrayView`] (leto `.view()`
/// parity), sharing the same layout and backing memory.
#[inline]
pub fn as_view(&self) -> ArrayView<'_, T, N> {
// SAFETY: `ptr` is valid for `len` elements for the duration of the
// borrow of `self`, matching the immutable-view contract.
let data = unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) };
ArrayView::new(self.layout, data)
}
/// Returns the shape of the view.
#[inline]
pub const fn shape(&self) -> [usize; N] {
self.layout.shape
}
/// Returns the strides of the view.
#[inline]
pub const fn strides(&self) -> [isize; N] {
self.layout.strides
}
/// Returns the offset of the view.
#[inline]
pub const fn offset(&self) -> usize {
self.layout.offset
}
/// Returns the total logical size of the view.
#[inline]
pub fn size(&self) -> usize {
self.layout.size()
}
/// Returns the layout of the view.
#[inline]
pub const fn layout(&self) -> Layout<N> {
self.layout
}
/// Returns the raw data slice as read-only.
#[inline]
pub fn data(&self) -> &[T] {
// SAFETY: self.ptr is valid for self.len elements.
unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
}
/// Returns the raw mutable data slice.
#[inline]
pub fn data_mut(&mut self) -> &mut [T] {
// SAFETY: self.ptr is valid for self.len elements.
unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
}
/// 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()?))
}
/// Consume the view and return the backing mutable slice with lifetime `'a`.
#[inline]
pub fn into_slice(self) -> &'a mut [T] {
// SAFETY: self.ptr is valid for self.len elements and lifetime 'a.
unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
}
/// Get a reference to the element at the specified index.
#[inline]
pub fn get(&self, index: [usize; N]) -> Result<&T> {
let offset = self.layout.offset_of(index)?;
if offset >= self.len {
return Err(LetoError::StorageError {
reason: format!(
"physical offset {offset} exceeds backing slice length {}",
self.len
),
});
}
// SAFETY: self.ptr is valid for self.len elements.
unsafe { Ok(&*self.ptr.as_ptr().add(offset)) }
}
/// Get a mutable reference to the element at the specified index.
#[inline]
pub fn get_mut(&mut self, index: [usize; N]) -> Result<&mut T> {
let offset = self.layout.offset_of(index)?;
if offset >= self.len {
return Err(LetoError::StorageError {
reason: format!(
"physical offset {offset} exceeds backing slice length {}",
self.len
),
});
}
// SAFETY: self.ptr is valid for self.len elements.
unsafe { Ok(&mut *self.ptr.as_ptr().add(offset)) }
}
/// Set every element of the view to a clone of `value` (leto `fill`
/// parity). Walks the view in logical row-major order, so it is correct for
/// any strides.
pub fn fill(&mut self, value: T)
where
T: Clone,
{
let shape = self.shape();
let size = self.size();
if size == 0 {
return;
}
let mut index = [0usize; N];
for _ in 0..size {
*self
.get_mut(index)
.expect("invariant: logical index is in bounds") = value.clone();
// row-major odometer increment of the multi-index.
for d in (0..N).rev() {
index[d] += 1;
if index[d] < shape[d] {
break;
}
index[d] = 0;
}
}
}
/// 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(ArrayViewMut {
layout: sliced_layout,
ptr: self.ptr,
len: self.len,
_marker: std::marker::PhantomData,
})
}
/// 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(ArrayViewMut {
layout: sliced_layout,
ptr: self.ptr,
len: self.len,
_marker: std::marker::PhantomData,
})
}
/// 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(ArrayViewMut {
layout: transposed_layout,
ptr: self.ptr,
len: self.len,
_marker: std::marker::PhantomData,
})
}
/// 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(ArrayViewMut {
layout: broadcasted_layout,
ptr: self.ptr,
len: self.len,
_marker: std::marker::PhantomData,
})
}
/// 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(ArrayViewMut {
layout: reshaped_layout,
ptr: self.ptr,
len: self.len,
_marker: std::marker::PhantomData,
})
}
/// 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,
{
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 = dense_block_range(&self.layout)?;
if range.end <= self.len {
unsafe {
Some(std::slice::from_raw_parts(
self.ptr.as_ptr().add(range.start),
range.len(),
))
}
} else {
None
}
} 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 = dense_block_range(&self.layout)?;
if range.end <= self.len {
unsafe {
Some(std::slice::from_raw_parts_mut(
self.ptr.as_ptr().add(range.start),
range.len(),
))
}
} else {
None
}
} 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 = dense_block_range(&self.layout)?;
if range.end <= self.len {
unsafe {
Some(std::slice::from_raw_parts(
self.ptr.as_ptr().add(range.start),
range.len(),
))
}
} else {
None
}
} 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 = dense_block_range(&self.layout)?;
if range.end <= self.len {
unsafe {
Some(std::slice::from_raw_parts_mut(
self.ptr.as_ptr().add(range.start),
range.len(),
))
}
} else {
None
}
} 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>,
)
}
/// Copy elements from `rhs` into this mutable view (leto `assign` parity).
///
/// Walks both views in logical row-major order, so it is correct for any
/// strides. Panics when shapes differ.
///
/// # Panics
/// Panics when `rhs.shape() != self.shape()`.
pub fn assign<Rhs>(&mut self, rhs: &Rhs)
where
T: Copy,
Rhs: crate::application::array::AssignSource<T, N>,
{
let shape = self.shape();
assert_eq!(shape, rhs.assign_shape(), "assign: shape mismatch");
let size = shape.iter().product::<usize>();
let mut index = [0usize; N];
for _ in 0..size {
let src = rhs.assign_get(index).expect("rhs element in bounds");
*self.get_mut(index).expect("dst element in bounds") = *src;
// Row-major odometer increment.
for d in (0..N).rev() {
index[d] += 1;
if index[d] < shape[d] {
break;
}
index[d] = 0;
}
}
}
}
// ── Index / IndexMut for ArrayView and ArrayViewMut ──────────────────────────
/// Enable `view[[i, j, k]]` syntax, matching `leto::ArrayView` ergonomics.
impl<'a, T, const N: usize> std::ops::Index<[usize; N]> for ArrayView<'a, T, N> {
type Output = T;
#[inline]
fn index(&self, index: [usize; N]) -> &T {
let offset = self
.layout
.offset_of(index)
.expect("ArrayView index out of bounds");
&self.data[offset]
}
}
/// Enable `view[[i, j, k]]` syntax on mutable views.
impl<'a, T, const N: usize> std::ops::Index<[usize; N]> for ArrayViewMut<'a, T, N> {
type Output = T;
#[inline]
fn index(&self, index: [usize; N]) -> &T {
let offset = self
.layout
.offset_of(index)
.expect("ArrayViewMut index out of bounds");
// SAFETY: ptr is valid for len elements for the lifetime of the view.
unsafe { &*self.ptr.as_ptr().add(offset) }
}
}
/// Enable `view[[i, j, k]] = value` syntax on mutable views.
impl<'a, T, const N: usize> std::ops::IndexMut<[usize; N]> for ArrayViewMut<'a, T, N> {
#[inline]
fn index_mut(&mut self, index: [usize; N]) -> &mut T {
let offset = self
.layout
.offset_of(index)
.expect("ArrayViewMut index_mut out of bounds");
// SAFETY: ptr is valid for len elements for the lifetime of the view.
unsafe { &mut *self.ptr.as_ptr().add(offset) }
}
}
/// Enable `view[i]` (usize) syntax for 1-D views (leto `ArrayView1` parity).
impl<'a, T> std::ops::Index<usize> for ArrayView<'a, T, 1> {
type Output = T;
#[inline]
fn index(&self, index: usize) -> &T {
let offset = self
.layout
.offset_of([index])
.expect("ArrayView1 index out of bounds");
&self.data[offset]
}
}
/// Enable `view[i]` (usize) mutable syntax for 1-D views.
impl<'a, T> std::ops::Index<usize> for ArrayViewMut<'a, T, 1> {
type Output = T;
#[inline]
fn index(&self, index: usize) -> &T {
let offset = self
.layout
.offset_of([index])
.expect("ArrayViewMut1 index out of bounds");
// SAFETY: ptr is valid for len elements.
unsafe { &*self.ptr.as_ptr().add(offset) }
}
}
/// Enable `view[i] = value` syntax for 1-D mutable views.
impl<'a, T> std::ops::IndexMut<usize> for ArrayViewMut<'a, T, 1> {
#[inline]
fn index_mut(&mut self, index: usize) -> &mut T {
let offset = self
.layout
.offset_of([index])
.expect("ArrayViewMut1 index_mut out of bounds");
// SAFETY: ptr is valid for len elements.
unsafe { &mut *self.ptr.as_ptr().add(offset) }
}
}
#[cfg(test)]
mod as_array_tests {
use crate::application::array::Array;
use crate::infrastructure::storage::VecStorage;
#[test]
fn as_array_matches_view_indexing_including_strided() {
// 3x4 source; take a strided sub-view (every other column) and confirm
// the zero-copy borrowed array indexes identically to the view.
let src = Array::<f64, VecStorage<f64>, 2>::from_shape_vec(
[3, 4],
(0..12).map(|i| i as f64).collect(),
)
.unwrap();
let view = src.view();
let borrowed = view.as_array();
assert_eq!(borrowed.shape(), view.shape());
for r in 0..3 {
for c in 0..4 {
assert_eq!(*borrowed.get([r, c]).unwrap(), *view.get([r, c]).unwrap());
assert_eq!(borrowed[[r, c]], src[[r, c]]);
}
}
// Strided sub-view: columns [1,3) step is exercised via slice.
let strided = src.view().slice(&[(0, 3, 1), (1, 4, 2)]).unwrap();
let strided_borrowed = strided.as_array();
assert_eq!(strided_borrowed.shape(), strided.shape());
for r in 0..strided.shape()[0] {
for c in 0..strided.shape()[1] {
assert_eq!(
*strided_borrowed.get([r, c]).unwrap(),
*strided.get([r, c]).unwrap(),
"strided borrowed array must match the view at [{r},{c}]"
);
}
}
}
}