strided-view 0.4.0

Device-agnostic strided view types and metadata operations (ported from Julia StridedViews.jl).
Documentation
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
//! Borrowed raw strided layout types.
//!
//! These are the prepared-replay counterparts to [`crate::StridedView`] and
//! [`crate::StridedViewMut`]. They borrow shape/stride metadata instead of
//! owning it, so compiled kernels can reuse already-validated layout
//! descriptors without rebuilding dynamic-rank view wrappers.

use crate::element_op::Identity;
use crate::view::validate_bounds;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ptr::NonNull;
use num_complex::{Complex32, Complex64};

mod private {
    pub trait Sealed {}
}

/// A scalar type that can safely witness storage for an erased kernel view.
pub trait KernelStorageElement: private::Sealed + Copy + 'static {
    const DTYPE: KernelDType;
}

macro_rules! kernel_storage_element {
    ($($ty:ty => $dtype:ident),* $(,)?) => {$ (
        impl private::Sealed for $ty {}
        impl KernelStorageElement for $ty {
            const DTYPE: KernelDType = KernelDType::$dtype;
        }
    )* };
}

kernel_storage_element! {
    f32 => F32,
    f64 => F64,
    i32 => I32,
    i64 => I64,
    bool => Bool,
    Complex32 => C32,
    Complex64 => C64,
}

use crate::{Result, StridedError, StridedView, StridedViewMut};

/// Dtypes supported by dtype-erased kernel entry points.
///
/// The enum is intentionally limited to the scalar set currently used by the
/// tensor runtime callers. Later FFI layers should map their ABI dtype tags to
/// this enum before dispatching into prepared kernels.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(u8)]
pub enum KernelDType {
    F32 = 1,
    F64 = 2,
    I32 = 3,
    I64 = 4,
    Bool = 5,
    C32 = 6,
    C64 = 7,
}

impl KernelDType {
    #[inline]
    pub const fn label(self) -> &'static str {
        match self {
            Self::F32 => "f32",
            Self::F64 => "f64",
            Self::I32 => "i32",
            Self::I64 => "i64",
            Self::Bool => "bool",
            Self::C32 => "c32",
            Self::C64 => "c64",
        }
    }

    #[inline]
    pub const fn size_of(self) -> usize {
        match self {
            Self::F32 => core::mem::size_of::<f32>(),
            Self::F64 => core::mem::size_of::<f64>(),
            Self::I32 => core::mem::size_of::<i32>(),
            Self::I64 => core::mem::size_of::<i64>(),
            Self::Bool => core::mem::size_of::<bool>(),
            Self::C32 => core::mem::size_of::<Complex32>(),
            Self::C64 => core::mem::size_of::<Complex64>(),
        }
    }

    #[inline]
    pub const fn alignment(self) -> usize {
        match self {
            Self::F32 => core::mem::align_of::<f32>(),
            Self::F64 => core::mem::align_of::<f64>(),
            Self::I32 => core::mem::align_of::<i32>(),
            Self::I64 => core::mem::align_of::<i64>(),
            Self::Bool => core::mem::align_of::<bool>(),
            Self::C32 => core::mem::align_of::<Complex32>(),
            Self::C64 => core::mem::align_of::<Complex64>(),
        }
    }

    #[inline]
    pub const fn requires_valid_byte_values(self) -> bool {
        matches!(self, Self::Bool)
    }
}

fn validate_erased_buffer(dtype: KernelDType, data: &[u8]) -> Result<usize> {
    let element_size = dtype.size_of();
    if data.len() % element_size != 0 {
        return Err(StridedError::ByteLengthMismatch {
            dtype: dtype.label(),
            byte_len: data.len(),
            element_size,
        });
    }

    let element_count = data.len() / element_size;
    if element_count == 0 {
        return Ok(0);
    }

    let alignment = dtype.alignment();
    if data.as_ptr() as usize % alignment != 0 {
        return Err(StridedError::DataAlignmentMismatch {
            dtype: dtype.label(),
            alignment,
        });
    }
    if dtype.requires_valid_byte_values() {
        if let Some(&value) = data.iter().find(|&&value| value > 1) {
            return Err(StridedError::InvalidBoolByte { value });
        }
    }
    Ok(element_count)
}

fn validate_erased_buffer_layout(
    dtype: KernelDType,
    data: NonNull<u8>,
    byte_len: usize,
) -> Result<usize> {
    let element_size = dtype.size_of();
    if byte_len % element_size != 0 {
        return Err(StridedError::ByteLengthMismatch {
            dtype: dtype.label(),
            byte_len,
            element_size,
        });
    }
    if byte_len != 0 && data.as_ptr() as usize % dtype.alignment() != 0 {
        return Err(StridedError::DataAlignmentMismatch {
            dtype: dtype.label(),
            alignment: dtype.alignment(),
        });
    }
    Ok(byte_len / element_size)
}

/// Pointer-backed dtype-erased input used by one-shot write entry points.
///
/// Unlike [`ErasedRawStridedRef`], this descriptor does not create a shared
/// Rust reference at construction time. That lets the entry point reject an
/// input/output overlap before forming references to either side.
#[derive(Clone, Copy, Debug)]
pub struct ErasedRawStridedPtr<'a> {
    dtype: KernelDType,
    data: NonNull<u8>,
    byte_len: usize,
    dims: &'a [usize],
    strides: &'a [isize],
    offset: isize,
    marker: PhantomData<&'a [MaybeUninit<u8>]>,
}

impl<'a> ErasedRawStridedPtr<'a> {
    /// Create a pointer-backed descriptor from erased storage.
    ///
    /// # Safety
    ///
    /// `data` must point into an allocation whose alignment is suitable for
    /// `dtype`, independently of the observed address. The allocation must
    /// provide `byte_len` initialized, readable bytes with valid provenance
    /// for `'a`, and remain alive for `'a`. For `bool`, the bytes may contain
    /// invalid values temporarily. They must not be read or used to form a
    /// typed reference until a caller has rejected overlap and
    /// [`Self::try_as_ref_after_no_overlap`] has validated the complete extent.
    /// The allocation may overlap a destination.
    /// The original owner may perform synchronized sequential mutation through
    /// the same-provenance raw pointer before conversion. No concurrent
    /// mutation or conflicting access is permitted during overlap checking,
    /// conversion, or consumer access.
    pub unsafe fn from_raw_parts(
        dtype: KernelDType,
        data: NonNull<u8>,
        byte_len: usize,
        dims: &'a [usize],
        strides: &'a [isize],
        offset: isize,
    ) -> Result<Self> {
        let element_count = validate_erased_buffer_layout(dtype, data, byte_len)?;
        validate_bounds(element_count, dims, strides, offset)?;
        Ok(Self {
            dtype,
            data,
            byte_len,
            dims,
            strides,
            offset,
            marker: PhantomData,
        })
    }

    /// Borrow a safe erased input as a pointer descriptor.
    pub fn from_ref(input: &ErasedRawStridedRef<'a>) -> Self {
        Self {
            dtype: input.dtype,
            data: NonNull::new(input.data.as_ptr().cast_mut()).unwrap_or_else(NonNull::dangling),
            byte_len: input.data.len(),
            dims: input.dims,
            strides: input.strides,
            offset: input.offset,
            marker: PhantomData,
        }
    }

    /// Convert this pointer to an initialized descriptor after overlap checks.
    ///
    /// # Safety
    ///
    /// The caller must have proved that no mutable allocation overlaps this
    /// pointer's complete byte extent.
    /// The allocation contract from [`Self::from_raw_parts`] must still hold.
    /// No mutation or other conflicting access may occur during this conversion
    /// or for the duration of the returned descriptor's consumer access.
    /// Bool bytes are validated here, immediately before typed access.
    pub unsafe fn try_as_ref_after_no_overlap(&self) -> Result<ErasedRawStridedRef<'_>> {
        let bytes = core::slice::from_raw_parts(self.data.as_ptr(), self.byte_len);
        validate_erased_buffer(self.dtype, bytes)?;
        ErasedRawStridedRef::from_raw_parts(
            self.dtype,
            self.data,
            self.byte_len,
            self.dims,
            self.strides,
            self.offset,
        )
    }

    #[inline]
    pub fn dtype(&self) -> KernelDType {
        self.dtype
    }

    /// Check overlap with initialized mutable storage without reading it.
    pub fn overlaps_mut(&self, dest: &ErasedRawStridedMut<'_>) -> Result<bool> {
        ranges_overlap(
            self.data.as_ptr() as usize,
            self.byte_len,
            dest.data.as_ptr() as usize,
            dest.data.len(),
        )
    }

    /// Check overlap with uninitialized mutable storage without reading it.
    pub fn overlaps_uninit_mut(&self, dest: &ErasedRawStridedUninitMut<'_>) -> Result<bool> {
        ranges_overlap(
            self.data.as_ptr() as usize,
            self.byte_len,
            dest.data.as_ptr() as usize,
            dest.data.len(),
        )
    }

    #[inline]
    pub fn dims(&self) -> &'a [usize] {
        self.dims
    }

    #[inline]
    pub fn strides(&self) -> &'a [isize] {
        self.strides
    }

    #[inline]
    pub fn offset(&self) -> isize {
        self.offset
    }
}

/// Borrowed dtype-erased raw strided input layout.
///
/// `dims`, `strides`, and `offset` are expressed in dtype elements, not bytes.
#[derive(Clone, Copy, Debug)]
pub struct ErasedRawStridedRef<'a> {
    dtype: KernelDType,
    data: &'a [u8],
    dims: &'a [usize],
    strides: &'a [isize],
    offset: isize,
}

impl<'a> ErasedRawStridedRef<'a> {
    /// Create an erased input descriptor from typed, initialized storage.
    pub fn from_slice<T: KernelStorageElement>(
        data: &'a [T],
        dims: &'a [usize],
        strides: &'a [isize],
        offset: isize,
    ) -> Result<Self> {
        let dtype = T::DTYPE;
        let byte_len = data
            .len()
            .checked_mul(core::mem::size_of::<T>())
            .ok_or(StridedError::OffsetOverflow)?;
        let bytes = unsafe { core::slice::from_raw_parts(data.as_ptr().cast::<u8>(), byte_len) };
        let element_count = validate_erased_buffer(dtype, bytes)?;
        validate_bounds(element_count, dims, strides, offset)?;
        Ok(Self {
            dtype,
            data: bytes,
            dims,
            strides,
            offset,
        })
    }

    /// Construct from erased storage.
    ///
    /// # Safety
    /// `data` must be the start of an allocation aligned for `dtype`; the
    /// allocation must contain `byte_len` initialized, readable bytes for
    /// `'a`, and every byte extent must represent valid values for `dtype`.
    /// The allocation and metadata must outlive `'a`; no mutable alias may
    /// exist while this descriptor is used. Alignment is an allocation
    /// property and must not be inferred from the observed address alone.
    pub unsafe fn from_raw_parts(
        dtype: KernelDType,
        data: NonNull<u8>,
        byte_len: usize,
        dims: &'a [usize],
        strides: &'a [isize],
        offset: isize,
    ) -> Result<Self> {
        let count = validate_erased_buffer_layout(dtype, data, byte_len)?;
        let bytes = core::slice::from_raw_parts(data.as_ptr(), byte_len);
        validate_bounds(count, dims, strides, offset)?;
        Ok(Self {
            dtype,
            data: bytes,
            dims,
            strides,
            offset,
        })
    }

    /// Borrow the initialized storage as its concrete scalar type.
    pub fn data_as<T: KernelStorageElement>(&self) -> Result<&[T]> {
        if self.dtype != T::DTYPE {
            return Err(StridedError::DTypeMismatch {
                expected: T::DTYPE.label(),
                actual: self.dtype.label(),
            });
        }
        Ok(unsafe {
            core::slice::from_raw_parts(
                self.data.as_ptr().cast::<T>(),
                self.data.len() / core::mem::size_of::<T>(),
            )
        })
    }

    #[inline]
    pub fn dtype(&self) -> KernelDType {
        self.dtype
    }

    #[inline]
    pub fn dims(&self) -> &'a [usize] {
        self.dims
    }

    #[inline]
    pub fn strides(&self) -> &'a [isize] {
        self.strides
    }

    #[inline]
    pub fn offset(&self) -> isize {
        self.offset
    }
}

/// Borrowed dtype-erased raw strided output layout.
///
/// `dims`, `strides`, and `offset` are expressed in dtype elements, not bytes.
#[derive(Debug)]
pub struct ErasedRawStridedMut<'a> {
    dtype: KernelDType,
    data: &'a mut [u8],
    dims: &'a [usize],
    strides: &'a [isize],
    offset: isize,
}

impl<'a> ErasedRawStridedMut<'a> {
    /// Create an erased output descriptor from typed, initialized storage.
    pub fn from_slice_mut<T: KernelStorageElement>(
        data: &'a mut [T],
        dims: &'a [usize],
        strides: &'a [isize],
        offset: isize,
    ) -> Result<Self> {
        let dtype = T::DTYPE;
        let byte_len = data
            .len()
            .checked_mul(core::mem::size_of::<T>())
            .ok_or(StridedError::OffsetOverflow)?;
        let data =
            unsafe { core::slice::from_raw_parts_mut(data.as_mut_ptr().cast::<u8>(), byte_len) };
        let element_count = validate_erased_buffer(dtype, data)?;
        validate_bounds(element_count, dims, strides, offset)?;
        Ok(Self {
            dtype,
            data,
            dims,
            strides,
            offset,
        })
    }

    /// Construct from erased storage.
    ///
    /// # Safety
    /// `data..data + byte_len` must be an aligned, writable allocation valid
    /// for `'a`, with valid initialized values for `dtype` throughout the
    /// complete byte extent; its provenance, extent, lifetime, and exclusive
    /// aliasing must be upheld by the caller.
    /// The alignment requirement is on the allocation, not merely the observed
    /// address. The caller must retain exclusive access: no mutable alias or
    /// concurrent mutation may exist while this descriptor is used.
    pub unsafe fn from_raw_parts(
        dtype: KernelDType,
        data: NonNull<u8>,
        byte_len: usize,
        dims: &'a [usize],
        strides: &'a [isize],
        offset: isize,
    ) -> Result<Self> {
        let count = validate_erased_buffer_layout(dtype, data, byte_len)?;
        let data = core::slice::from_raw_parts_mut(data.as_ptr(), byte_len);
        validate_erased_buffer(dtype, data)?;
        validate_bounds(count, dims, strides, offset)?;
        Ok(Self {
            dtype,
            data,
            dims,
            strides,
            offset,
        })
    }

    /// Borrow initialized storage as its concrete scalar type.
    pub fn data_as<T: KernelStorageElement>(&self) -> Result<&[T]> {
        if self.dtype != T::DTYPE {
            return Err(StridedError::DTypeMismatch {
                expected: T::DTYPE.label(),
                actual: self.dtype.label(),
            });
        }
        Ok(unsafe {
            core::slice::from_raw_parts(
                self.data.as_ptr().cast::<T>(),
                self.data.len() / core::mem::size_of::<T>(),
            )
        })
    }

    /// Borrow initialized storage mutably as its concrete scalar type.
    pub fn data_as_mut<T: KernelStorageElement>(&mut self) -> Result<&mut [T]> {
        if self.dtype != T::DTYPE {
            return Err(StridedError::DTypeMismatch {
                expected: T::DTYPE.label(),
                actual: self.dtype.label(),
            });
        }
        Ok(unsafe {
            core::slice::from_raw_parts_mut(
                self.data.as_mut_ptr().cast::<T>(),
                self.data.len() / core::mem::size_of::<T>(),
            )
        })
    }

    #[inline]
    pub fn dtype(&self) -> KernelDType {
        self.dtype
    }

    #[inline]
    pub fn dims(&self) -> &'a [usize] {
        self.dims
    }

    #[inline]
    pub fn strides(&self) -> &'a [isize] {
        self.strides
    }

    #[inline]
    pub fn offset(&self) -> isize {
        self.offset
    }
}

/// Borrowed dtype-erased raw strided output whose reachable elements may be
/// uninitialized.
///
/// This descriptor is only accepted by operations that prove and perform a
/// full overwrite of every reachable logical destination element. The backing
/// allocation may contain non-reachable holes, which remain uninitialized.
#[derive(Debug)]
pub struct ErasedRawStridedUninitMut<'a> {
    dtype: KernelDType,
    data: &'a mut [MaybeUninit<u8>],
    dims: &'a [usize],
    strides: &'a [isize],
    offset: isize,
}

impl<'a> ErasedRawStridedUninitMut<'a> {
    /// Create an uninitialized erased output descriptor from typed storage.
    pub fn from_uninit_slice<T: KernelStorageElement>(
        data: &'a mut [MaybeUninit<T>],
        dims: &'a [usize],
        strides: &'a [isize],
        offset: isize,
    ) -> Result<Self> {
        let dtype = T::DTYPE;
        let byte_len = data
            .len()
            .checked_mul(core::mem::size_of::<T>())
            .ok_or(StridedError::OffsetOverflow)?;
        let data = unsafe {
            core::slice::from_raw_parts_mut(data.as_mut_ptr().cast::<MaybeUninit<u8>>(), byte_len)
        };
        let data_ptr =
            NonNull::new(data.as_mut_ptr().cast::<u8>()).unwrap_or_else(NonNull::dangling);
        let element_count = validate_erased_buffer_layout(dtype, data_ptr, byte_len)?;
        validate_bounds(element_count, dims, strides, offset)?;
        Ok(Self {
            dtype,
            data,
            dims,
            strides,
            offset,
        })
    }

    /// Construct from erased uninitialized storage.
    ///
    /// # Safety
    /// `data..data + byte_len` must be an aligned, writable allocation valid
    /// for `'a`, with provenance and extent sufficient for all reachable
    /// elements. The caller must ensure every reachable element is completely
    /// overwritten before it is read or exposed as initialized storage. The
    /// allocation's alignment is an allocation property independent of the
    /// observed address, and the descriptor must have exclusive access with no
    /// mutable alias or concurrent mutation during use.
    pub unsafe fn from_raw_parts(
        dtype: KernelDType,
        data: NonNull<u8>,
        byte_len: usize,
        dims: &'a [usize],
        strides: &'a [isize],
        offset: isize,
    ) -> Result<Self> {
        let count = validate_erased_buffer_layout(dtype, data, byte_len)?;
        let data =
            core::slice::from_raw_parts_mut(data.as_ptr().cast::<MaybeUninit<u8>>(), byte_len);
        validate_bounds(count, dims, strides, offset)?;
        Ok(Self {
            dtype,
            data,
            dims,
            strides,
            offset,
        })
    }

    /// Borrow the uninitialized storage as its concrete scalar type.
    pub fn data_as_uninit_mut<T: KernelStorageElement>(&mut self) -> Result<&mut [MaybeUninit<T>]> {
        if self.dtype != T::DTYPE {
            return Err(StridedError::DTypeMismatch {
                expected: T::DTYPE.label(),
                actual: self.dtype.label(),
            });
        }
        Ok(unsafe {
            core::slice::from_raw_parts_mut(
                self.data.as_mut_ptr().cast::<MaybeUninit<T>>(),
                self.data.len() / core::mem::size_of::<T>(),
            )
        })
    }

    #[inline]
    pub fn dtype(&self) -> KernelDType {
        self.dtype
    }

    #[inline]
    pub fn dims(&self) -> &'a [usize] {
        self.dims
    }

    #[inline]
    pub fn strides(&self) -> &'a [isize] {
        self.strides
    }

    #[inline]
    pub fn offset(&self) -> isize {
        self.offset
    }
}

fn ranges_overlap(a_start: usize, a_len: usize, b_start: usize, b_len: usize) -> Result<bool> {
    let a_end = a_start
        .checked_add(a_len)
        .ok_or(StridedError::OffsetOverflow)?;
    let b_end = b_start
        .checked_add(b_len)
        .ok_or(StridedError::OffsetOverflow)?;
    Ok(a_start < b_end && b_start < a_end)
}

/// Borrowed raw strided input layout.
///
/// Use [`RawStridedRef::new`] for checked construction, or
/// [`RawStridedRef::new_unchecked`] when a higher-level compiled plan has
/// already validated bounds.
#[derive(Clone, Copy, Debug)]
pub struct RawStridedRef<'a, T> {
    data: &'a [T],
    dims: &'a [usize],
    strides: &'a [isize],
    offset: isize,
}

impl<'a, T> RawStridedRef<'a, T> {
    /// Create a raw strided input after validating reachable offsets.
    pub fn new(
        data: &'a [T],
        dims: &'a [usize],
        strides: &'a [isize],
        offset: isize,
    ) -> Result<Self> {
        validate_bounds(data.len(), dims, strides, offset)?;
        Ok(Self {
            data,
            dims,
            strides,
            offset,
        })
    }

    /// Create a raw strided input without bounds checking.
    ///
    /// # Safety
    /// The caller must ensure every index reachable by `dims`/`strides` from
    /// `offset` lies inside `data`.
    pub unsafe fn new_unchecked(
        data: &'a [T],
        dims: &'a [usize],
        strides: &'a [isize],
        offset: isize,
    ) -> Self {
        Self {
            data,
            dims,
            strides,
            offset,
        }
    }

    #[inline]
    pub fn data(&self) -> &'a [T] {
        self.data
    }

    #[inline]
    pub fn dims(&self) -> &'a [usize] {
        self.dims
    }

    #[inline]
    pub fn strides(&self) -> &'a [isize] {
        self.strides
    }

    #[inline]
    pub fn offset(&self) -> isize {
        self.offset
    }

    #[inline]
    pub fn ptr(&self) -> *const T {
        if self.dims.iter().any(|&dim| dim == 0) {
            NonNull::<T>::dangling().as_ptr()
        } else {
            unsafe { self.data.as_ptr().offset(self.offset) }
        }
    }

    /// Convert to an immutable owning-metadata view.
    ///
    /// This is for compatibility paths. Hot prepared paths should use the raw
    /// accessors directly and avoid this conversion.
    #[inline]
    pub fn as_view(&self) -> StridedView<'a, T, Identity> {
        unsafe { StridedView::new_unchecked(self.data, self.dims, self.strides, self.offset) }
    }
}

/// Borrowed raw strided output layout.
///
/// This is the mutable counterpart to [`RawStridedRef`]. It avoids allocating
/// owned shape/stride metadata in prepared replay paths.
#[derive(Debug)]
pub struct RawStridedMut<'a, T> {
    data: &'a mut [T],
    dims: &'a [usize],
    strides: &'a [isize],
    offset: isize,
}

impl<'a, T> RawStridedMut<'a, T> {
    /// Create a raw strided output after validating reachable offsets.
    pub fn new(
        data: &'a mut [T],
        dims: &'a [usize],
        strides: &'a [isize],
        offset: isize,
    ) -> Result<Self> {
        validate_bounds(data.len(), dims, strides, offset)?;
        Ok(Self {
            data,
            dims,
            strides,
            offset,
        })
    }

    /// Create a raw strided output without bounds checking.
    ///
    /// # Safety
    /// The caller must ensure every index reachable by `dims`/`strides` from
    /// `offset` lies inside `data`, and no aliases violate mutable access.
    pub unsafe fn new_unchecked(
        data: &'a mut [T],
        dims: &'a [usize],
        strides: &'a [isize],
        offset: isize,
    ) -> Self {
        Self {
            data,
            dims,
            strides,
            offset,
        }
    }

    #[inline]
    pub fn data(&self) -> &[T] {
        self.data
    }

    #[inline]
    pub fn data_mut(&mut self) -> &mut [T] {
        self.data
    }

    #[inline]
    pub fn dims(&self) -> &'a [usize] {
        self.dims
    }

    #[inline]
    pub fn strides(&self) -> &'a [isize] {
        self.strides
    }

    #[inline]
    pub fn offset(&self) -> isize {
        self.offset
    }

    #[inline]
    pub fn ptr(&self) -> *const T {
        if self.dims.iter().any(|&dim| dim == 0) {
            NonNull::<T>::dangling().as_ptr()
        } else {
            unsafe { self.data.as_ptr().offset(self.offset) }
        }
    }

    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut T {
        if self.dims.iter().any(|&dim| dim == 0) {
            NonNull::<T>::dangling().as_ptr()
        } else {
            unsafe { self.data.as_mut_ptr().offset(self.offset) }
        }
    }

    /// Convert to an immutable owning-metadata view.
    ///
    /// This is for compatibility paths. Hot prepared paths should use the raw
    /// accessors directly and avoid this conversion.
    #[inline]
    pub fn as_view(&self) -> StridedView<'_, T, Identity> {
        unsafe { StridedView::new_unchecked(self.data, self.dims, self.strides, self.offset) }
    }

    /// Convert to a mutable owning-metadata view.
    ///
    /// This is for compatibility paths. Hot prepared paths should use the raw
    /// accessors directly and avoid this conversion.
    #[inline]
    pub fn as_view_mut(&mut self) -> StridedViewMut<'_, T> {
        unsafe { StridedViewMut::new_unchecked(self.data, self.dims, self.strides, self.offset) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn typed_erased_storage_covers_all_kernel_dtypes() {
        macro_rules! check {
            ($ty:ty, $value:expr) => {{
                let mut initialized = [$value, $value];
                let dims = [2usize];
                let strides = [1isize];
                let reference =
                    ErasedRawStridedRef::from_slice(&initialized, &dims, &strides, 0).unwrap();
                assert_eq!(reference.data_as::<$ty>().unwrap().len(), 2);
                let mut mutable =
                    ErasedRawStridedMut::from_slice_mut(&mut initialized, &dims, &strides, 0)
                        .unwrap();
                assert_eq!(mutable.data_as::<$ty>().unwrap().len(), 2);
                assert_eq!(mutable.data_as_mut::<$ty>().unwrap().len(), 2);
                let mut uninitialized = [MaybeUninit::<$ty>::uninit(); 2];
                let mut destination = ErasedRawStridedUninitMut::from_uninit_slice(
                    &mut uninitialized,
                    &dims,
                    &strides,
                    0,
                )
                .unwrap();
                assert_eq!(destination.data_as_uninit_mut::<$ty>().unwrap().len(), 2);
            }};
        }

        check!(f32, 1.0f32);
        check!(f64, 1.0f64);
        check!(i32, 1i32);
        check!(i64, 1i64);
        check!(bool, true);
        check!(Complex32, Complex32::new(1.0, 0.0));
        check!(Complex64, Complex64::new(1.0, 0.0));
    }

    #[test]
    fn rejects_usize_max_dimension_before_isize_truncation() {
        let data = [false; 1];
        let dims = [usize::MAX];
        let strides = [-1isize];
        assert!(matches!(
            RawStridedRef::new(&data, &dims, &strides, 0),
            Err(crate::StridedError::OffsetOverflow)
        ));
        let mut data = [false; 1];
        assert!(matches!(
            RawStridedMut::new(&mut data, &dims, &strides, 0),
            Err(crate::StridedError::OffsetOverflow)
        ));
        assert!(matches!(
            ErasedRawStridedRef::from_slice(&data, &dims, &strides, 0),
            Err(crate::StridedError::OffsetOverflow)
        ));
        let mut data = [false; 1];
        assert!(matches!(
            ErasedRawStridedMut::from_slice_mut(&mut data, &dims, &strides, 0),
            Err(crate::StridedError::OffsetOverflow)
        ));
        let ptr = NonNull::new(data.as_mut_ptr()).unwrap();
        assert!(matches!(
            unsafe {
                ErasedRawStridedPtr::from_raw_parts(
                    KernelDType::Bool,
                    ptr.cast(),
                    data.len(),
                    &dims,
                    &strides,
                    0,
                )
            },
            Err(crate::StridedError::OffsetOverflow)
        ));
        let mut data = vec![MaybeUninit::<bool>::uninit(); 1];
        assert!(matches!(
            ErasedRawStridedUninitMut::from_uninit_slice(&mut data, &dims, &strides, 0),
            Err(crate::StridedError::OffsetOverflow)
        ));
    }

    #[test]
    fn empty_raw_views_use_dangling_base_pointers_for_extreme_offsets() {
        let dims = [0usize];
        let strides = [1isize];
        let data: [f64; 0] = [];
        let raw = RawStridedRef::new(&data, &dims, &strides, isize::MAX).unwrap();
        assert_eq!(raw.ptr(), NonNull::<f64>::dangling().as_ptr());

        let mut data: [f64; 0] = [];
        let mut raw = RawStridedMut::new(&mut data, &dims, &strides, isize::MAX).unwrap();
        assert_eq!(raw.ptr(), NonNull::<f64>::dangling().as_ptr());
        assert_eq!(raw.as_mut_ptr(), NonNull::<f64>::dangling().as_ptr());
    }

    #[test]
    fn raw_ref_rejects_out_of_bounds_layout() {
        let data = [0.0f64; 4];
        let err = RawStridedRef::new(&data, &[2, 3], &[3, 1], 0).unwrap_err();
        assert!(matches!(err, crate::StridedError::OffsetOverflow));
    }

    #[test]
    fn raw_mut_can_reborrow_as_view() {
        let mut data = [1, 2, 3, 4];
        let mut raw = RawStridedMut::new(&mut data, &[2, 2], &[2, 1], 0).unwrap();
        {
            let view = raw.as_view();
            assert_eq!(view.dims(), &[2, 2]);
        }
        let view_mut = raw.as_view_mut();
        assert_eq!(view_mut.get(&[1, 1]), 4);
    }
}