Skip to main content

strided_kernel/
erased.rs

1use crate::*;
2use num_complex::{Complex32, Complex64};
3use strided_basic::execution::check_static_indexing_dtype;
4use strided_basic::execution::{check_dtype, validate_uninit_no_overlap};
5
6mod uninit;
7pub use uninit::{
8    erased_broadcast_mul_into_uninit, erased_clamp_into_uninit, erased_compare_into_uninit,
9    erased_map_into_uninit, erased_select_into_uninit, erased_zip_into_uninit,
10};
11/// Runtime unary operation for [`erased_map_into`].
12#[non_exhaustive]
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum ErasedMapOp {
15    Negate,
16    Conj,
17    Abs,
18    Sign,
19}
20
21impl ErasedMapOp {
22    const fn label(self) -> &'static str {
23        match self {
24            Self::Negate => "negate",
25            Self::Conj => "conj",
26            Self::Abs => "abs",
27            Self::Sign => "sign",
28        }
29    }
30}
31
32/// Runtime binary operation for [`erased_zip_into`].
33#[non_exhaustive]
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub enum ErasedZipOp {
36    Add,
37    Subtract,
38    Multiply,
39    Divide,
40    Remainder,
41    Maximum,
42    Minimum,
43}
44
45impl ErasedZipOp {
46    const fn label(self) -> &'static str {
47        match self {
48            Self::Add => "add",
49            Self::Subtract => "subtract",
50            Self::Multiply => "multiply",
51            Self::Divide => "divide",
52            Self::Remainder => "remainder",
53            Self::Maximum => "maximum",
54            Self::Minimum => "minimum",
55        }
56    }
57}
58
59/// Apply one runtime-selected unary operation without compiling a plan.
60///
61/// The destination must not overlap the input. Real and complex dtypes support
62/// every [`ErasedMapOp`], signed integers use wrapping negate/abs semantics,
63/// and `bool` supports only [`ErasedMapOp::Conj`]. Complex absolute value has
64/// the real output contract `c32 -> f32` and `c64 -> f64`; all other supported
65/// unary operations preserve dtype.
66///
67/// # Errors
68///
69/// Returns [`StridedError::DTypeMismatch`] when `input` or `dest` does not
70/// carry the dtype that `input_dtype` and `op` imply,
71/// [`StridedError::UnsupportedOp`] for a `bool` input with any op other than
72/// [`ErasedMapOp::Conj`], [`StridedError::OverlappingInputOutput`] when the
73/// input allocation overlaps the destination,
74/// [`StridedError::InvalidBoolByte`] when a `bool` input holds a byte other
75/// than 0 or 1, [`StridedError::NonInjectiveOutputLayout`] when the
76/// destination layout cannot be proven to place logical elements on distinct
77/// offsets, and [`StridedError::RankMismatch`] or
78/// [`StridedError::ShapeMismatch`] when the destination dims differ from the
79/// input dims. Validation completes before any write.
80pub fn erased_map_into(
81    input_dtype: KernelDType,
82    op: ErasedMapOp,
83    dest: &mut ErasedRawStridedMut<'_>,
84    input: &ErasedRawStridedPtr<'_>,
85    exec: Exec<'_>,
86) -> Result<()> {
87    check_dtype(input_dtype, input.dtype())?;
88    check_dtype(map_output_dtype(input_dtype, op)?, dest.dtype())?;
89    validate_no_overlap(dest, input, 0)?;
90    // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things. No
91    // mutable allocation may overlap `input`'s byte extent: `dest` is the only one in this call,
92    // and `validate_no_overlap` (erased.rs:1916) checked `input` against it at erased.rs:89 by
93    // comparing whole byte ranges (`overlaps_mut`, strided-view/src/raw.rs:338). The allocation
94    // contract `input` was built under (strided-view/src/raw.rs:204) must still hold; that is the
95    // obligation of whoever built `input`. No conflicting access may happen while the result is
96    // used: within this call the only writer is `dest`, which does not overlap, and the `input`
97    // contract (strided-view/src/raw.rs:212) rules out concurrent mutation from outside.
98    let input = unsafe { input.try_as_ref_after_no_overlap() }?;
99
100    match (input_dtype, op) {
101        (KernelDType::C32, ErasedMapOp::Abs) => {
102            execute_one_shot_map_with::<f32, Complex32>(dest, &input, |value| value.norm(), exec)
103        }
104        (KernelDType::C64, ErasedMapOp::Abs) => {
105            execute_one_shot_map_with::<f64, Complex64>(dest, &input, |value| value.norm(), exec)
106        }
107        (KernelDType::F32, _) => execute_one_shot_map::<f32>(op, dest, &input, exec),
108        (KernelDType::F64, _) => execute_one_shot_map::<f64>(op, dest, &input, exec),
109        (KernelDType::I32, _) => execute_one_shot_map::<i32>(op, dest, &input, exec),
110        (KernelDType::I64, _) => execute_one_shot_map::<i64>(op, dest, &input, exec),
111        (KernelDType::Bool, _) => execute_one_shot_map::<bool>(op, dest, &input, exec),
112        (KernelDType::C32, _) => execute_one_shot_map::<Complex32>(op, dest, &input, exec),
113        (KernelDType::C64, _) => execute_one_shot_map::<Complex64>(op, dest, &input, exec),
114        _ => Err(StridedError::UnsupportedDType {
115            dtype: input_dtype.label(),
116        }),
117    }
118}
119
120/// Apply one runtime-selected binary operation without compiling a plan.
121///
122/// The destination must not overlap either input. Real dtypes support every
123/// [`ErasedZipOp`]. Signed integers support every operation with wrapping
124/// arithmetic and a pre-write zero-divisor check. Complex dtypes support
125/// add/subtract/multiply/divide. `bool` has no binary one-shot operations.
126///
127/// # Errors
128///
129/// Returns [`StridedError::DTypeMismatch`] when `dest`, `lhs`, or `rhs` does
130/// not carry `dtype`, [`StridedError::UnsupportedOp`] for `bool` operands or
131/// for a complex remainder/maximum/minimum,
132/// [`StridedError::OverlappingInputOutput`] when either input allocation
133/// overlaps the destination, [`StridedError::InvalidBoolByte`] when an input
134/// holds a `bool` byte other than 0 or 1,
135/// [`StridedError::IntegerDivisionByZero`] when an integer divide or
136/// remainder finds a zero divisor, [`StridedError::NonInjectiveOutputLayout`]
137/// when the destination layout cannot be proven to place logical elements on
138/// distinct offsets, and [`StridedError::RankMismatch`] or
139/// [`StridedError::ShapeMismatch`] when the destination dims differ from
140/// either input's dims. Validation completes before any write.
141pub fn erased_zip_into(
142    dtype: KernelDType,
143    op: ErasedZipOp,
144    dest: &mut ErasedRawStridedMut<'_>,
145    lhs: &ErasedRawStridedPtr<'_>,
146    rhs: &ErasedRawStridedPtr<'_>,
147    exec: Exec<'_>,
148) -> Result<()> {
149    check_dtype(dtype, dest.dtype())?;
150    check_dtype(dtype, lhs.dtype())?;
151    check_dtype(dtype, rhs.dtype())?;
152    validate_no_overlap(dest, lhs, 0)?;
153    validate_no_overlap(dest, rhs, 1)?;
154    // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things. No
155    // mutable allocation may overlap `lhs`'s byte extent: `dest` is the only one in this call,
156    // and `validate_no_overlap` (erased.rs:1916) checked `lhs` against it at erased.rs:152 by
157    // comparing whole byte ranges (`overlaps_mut`, strided-view/src/raw.rs:338). The allocation
158    // contract `lhs` was built under (strided-view/src/raw.rs:204) must still hold; that is the
159    // obligation of whoever built `lhs`. No conflicting access may happen while the result is
160    // used: within this call the only writer is `dest`, which does not overlap, and the `lhs`
161    // contract (strided-view/src/raw.rs:212) rules out concurrent mutation from outside.
162    let lhs = unsafe { lhs.try_as_ref_after_no_overlap() }?;
163    // SAFETY: as for `lhs` above: `validate_no_overlap` checked `rhs` against `dest` at
164    // erased.rs:153, and the same allocation contract and exclusive `dest` borrow apply.
165    let rhs = unsafe { rhs.try_as_ref_after_no_overlap() }?;
166
167    match dtype {
168        KernelDType::F32 => execute_one_shot_zip::<f32>(op, dest, &lhs, &rhs, exec),
169        KernelDType::F64 => execute_one_shot_zip::<f64>(op, dest, &lhs, &rhs, exec),
170        KernelDType::I32 => execute_one_shot_zip::<i32>(op, dest, &lhs, &rhs, exec),
171        KernelDType::I64 => execute_one_shot_zip::<i64>(op, dest, &lhs, &rhs, exec),
172        KernelDType::Bool => execute_one_shot_zip::<bool>(op, dest, &lhs, &rhs, exec),
173        KernelDType::C32 => execute_one_shot_zip::<Complex32>(op, dest, &lhs, &rhs, exec),
174        KernelDType::C64 => execute_one_shot_zip::<Complex64>(op, dest, &lhs, &rhs, exec),
175        _ => Err(StridedError::UnsupportedDType {
176            dtype: dtype.label(),
177        }),
178    }
179}
180
181/// Dtype-erased static-slice wrapper.
182#[derive(Clone, Debug)]
183pub struct ErasedSlicePlan {
184    dtype: KernelDType,
185    plan: SlicePlan,
186}
187
188/// Dtype-erased reverse wrapper.
189#[derive(Clone, Debug)]
190pub struct ErasedReversePlan {
191    dtype: KernelDType,
192    plan: ReversePlan,
193}
194
195/// Dtype-erased pad wrapper.
196#[derive(Clone, Debug)]
197pub struct ErasedPadPlan {
198    dtype: KernelDType,
199    plan: PadPlan,
200}
201
202impl ErasedSlicePlan {
203    /// Validate and store a static slice plan for one dtype and fixed layout set.
204    ///
205    /// # Errors
206    ///
207    /// Returns [`StridedError::StrideLengthMismatch`] when the operand or
208    /// destination layout lengths differ from the operand rank,
209    /// [`StridedError::RankMismatch`] when `starts`, `limits`, or
210    /// `slice_strides` differ from it, [`StridedError::InvalidAxis`] for a
211    /// window with `start > limit`, a `limit` beyond the operand extent, or a
212    /// zero slice stride, [`StridedError::ShapeMismatch`] when `dest_dims` is
213    /// not the sliced extents, [`StridedError::NonInjectiveOutputLayout`]
214    /// when the destination layout cannot be proven injective, and
215    /// [`StridedError::OffsetOverflow`] when an element count, a scaled
216    /// source stride, or the source offset delta overflows.
217    // Dtype plus operand/destination layouts and the three slice vectors: the plan key.
218    #[allow(clippy::too_many_arguments)]
219    pub fn compile(
220        dtype: KernelDType,
221        operand_dims: &[usize],
222        operand_strides: &[isize],
223        dest_dims: &[usize],
224        dest_strides: &[isize],
225        starts: &[usize],
226        limits: &[usize],
227        slice_strides: &[usize],
228    ) -> Result<Self> {
229        check_static_indexing_dtype(dtype)?;
230        Ok(Self {
231            dtype,
232            plan: SlicePlan::compile(
233                operand_dims,
234                operand_strides,
235                dest_dims,
236                dest_strides,
237                starts,
238                limits,
239                slice_strides,
240            )?,
241        })
242    }
243
244    #[inline]
245    pub fn dtype(&self) -> KernelDType {
246        self.dtype
247    }
248
249    #[inline]
250    pub fn plan(&self) -> &SlicePlan {
251        &self.plan
252    }
253
254    /// Execute a static slice into an erased output descriptor.
255    ///
256    /// # Errors
257    ///
258    /// Returns [`StridedError::DTypeMismatch`] when `dest` or `operand`
259    /// carries a different dtype than the plan,
260    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry the
261    /// compiled extents and strides, and [`StridedError::OffsetOverflow`]
262    /// when the operand offset plus the compiled source offset delta
263    /// overflows, which an empty operand view whose offset the descriptor
264    /// contract does not bound can reach. Nothing is written unless every
265    /// check succeeds.
266    pub fn execute(
267        &self,
268        dest: &mut ErasedRawStridedMut<'_>,
269        operand: &ErasedRawStridedRef<'_>,
270        exec: Exec<'_>,
271    ) -> Result<()> {
272        check_dtype(self.dtype, dest.dtype())?;
273        check_dtype(self.dtype, operand.dtype())?;
274
275        match self.dtype {
276            KernelDType::F32 => execute_slice::<f32>(&self.plan, dest, operand, exec),
277            KernelDType::F64 => execute_slice::<f64>(&self.plan, dest, operand, exec),
278            KernelDType::I32 => execute_slice::<i32>(&self.plan, dest, operand, exec),
279            KernelDType::I64 => execute_slice::<i64>(&self.plan, dest, operand, exec),
280            KernelDType::Bool => execute_slice::<bool>(&self.plan, dest, operand, exec),
281            KernelDType::C32 => execute_slice::<Complex32>(&self.plan, dest, operand, exec),
282            KernelDType::C64 => execute_slice::<Complex64>(&self.plan, dest, operand, exec),
283            _ => Err(StridedError::UnsupportedDType {
284                dtype: self.dtype.label(),
285            }),
286        }
287    }
288
289    /// Execute a static slice as a full overwrite of uninitialized output storage.
290    /// On success, every reachable destination slot is fully overwritten;
291    /// unreachable holes are neither read nor initialized. Validation errors
292    /// are returned before any destination write. A panic during execution
293    /// may leave a partially initialized `MaybeUninit` destination, which is
294    /// still safely droppable; no readable value is promised for unwritten
295    /// reachable slots.
296    ///
297    /// # Errors
298    ///
299    /// Returns [`StridedError::DTypeMismatch`] when `dest` or `operand`
300    /// carries a different dtype than the plan,
301    /// [`StridedError::OverlappingInputOutput`] when the input allocation
302    /// overlaps the destination, [`StridedError::InvalidBoolByte`] when a
303    /// `bool` input holds a byte other than 0 or 1,
304    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry the
305    /// compiled extents and strides, and [`StridedError::OffsetOverflow`]
306    /// when the operand offset plus the compiled source offset delta
307    /// overflows. Every rejection above is returned before any destination
308    /// write.
309    pub fn execute_uninit(
310        &self,
311        dest: &mut ErasedRawStridedUninitMut<'_>,
312        operand: &ErasedRawStridedPtr<'_>,
313        exec: Exec<'_>,
314    ) -> Result<()> {
315        check_dtype(self.dtype, dest.dtype())?;
316        check_dtype(self.dtype, operand.dtype())?;
317        validate_uninit_no_overlap(dest, operand, 0)?;
318        // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things.
319        // No mutable allocation may overlap `operand`'s byte extent: `dest` is the only one in
320        // this call, and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18)
321        // checked `operand` against it at erased.rs:317 by comparing whole byte ranges
322        // (`overlaps_uninit_mut`, strided-view/src/raw.rs:355). The allocation contract
323        // `operand` was built under (strided-view/src/raw.rs:204) must still hold; that is the
324        // obligation of whoever built `operand`. No conflicting access may happen while the
325        // result is used: within this call the only writer is `dest`, which does not overlap, and
326        // the `operand` contract (strided-view/src/raw.rs:212) rules out concurrent mutation from
327        // outside.
328        let operand = unsafe { operand.try_as_ref_after_no_overlap() }?;
329
330        match self.dtype {
331            KernelDType::F32 => execute_slice_uninit::<f32>(&self.plan, dest, &operand, exec),
332            KernelDType::F64 => execute_slice_uninit::<f64>(&self.plan, dest, &operand, exec),
333            KernelDType::I32 => execute_slice_uninit::<i32>(&self.plan, dest, &operand, exec),
334            KernelDType::I64 => execute_slice_uninit::<i64>(&self.plan, dest, &operand, exec),
335            KernelDType::Bool => execute_slice_uninit::<bool>(&self.plan, dest, &operand, exec),
336            KernelDType::C32 => execute_slice_uninit::<Complex32>(&self.plan, dest, &operand, exec),
337            KernelDType::C64 => execute_slice_uninit::<Complex64>(&self.plan, dest, &operand, exec),
338            _ => Err(StridedError::UnsupportedDType {
339                dtype: self.dtype.label(),
340            }),
341        }
342    }
343}
344
345impl ErasedReversePlan {
346    /// Validate and store a reverse plan for one dtype and fixed layout set.
347    ///
348    /// # Errors
349    ///
350    /// Returns [`StridedError::StrideLengthMismatch`] when the operand or
351    /// destination stride list does not match the operand rank,
352    /// [`StridedError::InvalidAxis`] when a listed axis is out of range,
353    /// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
354    /// cannot be proven injective, and [`StridedError::OffsetOverflow`] when
355    /// an element count, a negated source stride, or the source offset delta
356    /// overflows.
357    pub fn compile(
358        dtype: KernelDType,
359        operand_dims: &[usize],
360        operand_strides: &[isize],
361        dest_strides: &[isize],
362        axes: &[usize],
363    ) -> Result<Self> {
364        check_static_indexing_dtype(dtype)?;
365        Ok(Self {
366            dtype,
367            plan: ReversePlan::compile(operand_dims, operand_strides, dest_strides, axes)?,
368        })
369    }
370
371    #[inline]
372    pub fn dtype(&self) -> KernelDType {
373        self.dtype
374    }
375
376    #[inline]
377    pub fn plan(&self) -> &ReversePlan {
378        &self.plan
379    }
380
381    /// Execute a reverse into an erased output descriptor.
382    ///
383    /// # Errors
384    ///
385    /// Returns [`StridedError::DTypeMismatch`] when `dest` or `operand`
386    /// carries a different dtype than the plan,
387    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry the
388    /// compiled extents and strides, and [`StridedError::OffsetOverflow`]
389    /// when the operand offset plus the compiled source offset delta
390    /// overflows, which an empty operand view whose offset the descriptor
391    /// contract does not bound can reach. Nothing is written unless every
392    /// check succeeds.
393    pub fn execute(
394        &self,
395        dest: &mut ErasedRawStridedMut<'_>,
396        operand: &ErasedRawStridedRef<'_>,
397        exec: Exec<'_>,
398    ) -> Result<()> {
399        check_dtype(self.dtype, dest.dtype())?;
400        check_dtype(self.dtype, operand.dtype())?;
401
402        match self.dtype {
403            KernelDType::F32 => execute_reverse::<f32>(&self.plan, dest, operand, exec),
404            KernelDType::F64 => execute_reverse::<f64>(&self.plan, dest, operand, exec),
405            KernelDType::I32 => execute_reverse::<i32>(&self.plan, dest, operand, exec),
406            KernelDType::I64 => execute_reverse::<i64>(&self.plan, dest, operand, exec),
407            KernelDType::Bool => execute_reverse::<bool>(&self.plan, dest, operand, exec),
408            KernelDType::C32 => execute_reverse::<Complex32>(&self.plan, dest, operand, exec),
409            KernelDType::C64 => execute_reverse::<Complex64>(&self.plan, dest, operand, exec),
410            _ => Err(StridedError::UnsupportedDType {
411                dtype: self.dtype.label(),
412            }),
413        }
414    }
415
416    /// Execute reverse as a full overwrite of uninitialized output storage.
417    /// On success, every reachable destination slot is fully overwritten;
418    /// unreachable holes are neither read nor initialized. Validation errors
419    /// are returned before any destination write. A panic during execution
420    /// may leave a partially initialized `MaybeUninit` destination, which is
421    /// still safely droppable; no readable value is promised for unwritten
422    /// reachable slots.
423    ///
424    /// # Errors
425    ///
426    /// Returns [`StridedError::DTypeMismatch`] when `dest` or `operand`
427    /// carries a different dtype than the plan,
428    /// [`StridedError::OverlappingInputOutput`] when the input allocation
429    /// overlaps the destination, [`StridedError::InvalidBoolByte`] when a
430    /// `bool` input holds a byte other than 0 or 1,
431    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry the
432    /// compiled extents and strides, and [`StridedError::OffsetOverflow`]
433    /// when the operand offset plus the compiled source offset delta
434    /// overflows. Every rejection above is returned before any destination
435    /// write.
436    pub fn execute_uninit(
437        &self,
438        dest: &mut ErasedRawStridedUninitMut<'_>,
439        operand: &ErasedRawStridedPtr<'_>,
440        exec: Exec<'_>,
441    ) -> Result<()> {
442        check_dtype(self.dtype, dest.dtype())?;
443        check_dtype(self.dtype, operand.dtype())?;
444        validate_uninit_no_overlap(dest, operand, 0)?;
445        // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things.
446        // No mutable allocation may overlap `operand`'s byte extent: `dest` is the only one in
447        // this call, and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18)
448        // checked `operand` against it at erased.rs:444 by comparing whole byte ranges
449        // (`overlaps_uninit_mut`, strided-view/src/raw.rs:355). The allocation contract
450        // `operand` was built under (strided-view/src/raw.rs:204) must still hold; that is the
451        // obligation of whoever built `operand`. No conflicting access may happen while the
452        // result is used: within this call the only writer is `dest`, which does not overlap, and
453        // the `operand` contract (strided-view/src/raw.rs:212) rules out concurrent mutation from
454        // outside.
455        let operand = unsafe { operand.try_as_ref_after_no_overlap() }?;
456
457        match self.dtype {
458            KernelDType::F32 => execute_reverse_uninit::<f32>(&self.plan, dest, &operand, exec),
459            KernelDType::F64 => execute_reverse_uninit::<f64>(&self.plan, dest, &operand, exec),
460            KernelDType::I32 => execute_reverse_uninit::<i32>(&self.plan, dest, &operand, exec),
461            KernelDType::I64 => execute_reverse_uninit::<i64>(&self.plan, dest, &operand, exec),
462            KernelDType::Bool => execute_reverse_uninit::<bool>(&self.plan, dest, &operand, exec),
463            KernelDType::C32 => {
464                execute_reverse_uninit::<Complex32>(&self.plan, dest, &operand, exec)
465            }
466            KernelDType::C64 => {
467                execute_reverse_uninit::<Complex64>(&self.plan, dest, &operand, exec)
468            }
469            _ => Err(StridedError::UnsupportedDType {
470                dtype: self.dtype.label(),
471            }),
472        }
473    }
474}
475
476impl ErasedPadPlan {
477    /// Validate and store a pad plan for one dtype and fixed layout set.
478    ///
479    /// # Errors
480    ///
481    /// Returns [`StridedError::StrideLengthMismatch`] when the operand or
482    /// destination layout lengths differ from the operand rank,
483    /// [`StridedError::RankMismatch`] when the edge or interior padding
484    /// lengths differ from it, [`StridedError::InvalidAxis`] for a negative
485    /// interior padding or a padded extent that does not fit `usize`,
486    /// [`StridedError::ShapeMismatch`] when `dest_dims` is not the padded
487    /// extents, [`StridedError::NonInjectiveOutputLayout`] when the
488    /// destination layout cannot be proven injective, and
489    /// [`StridedError::OffsetOverflow`] when an element count, a padded
490    /// extent, or a cursor stride computation overflows.
491    // Dtype plus both layouts and the three padding vectors: the compile key.
492    #[allow(clippy::too_many_arguments)]
493    pub fn compile(
494        dtype: KernelDType,
495        operand_dims: &[usize],
496        operand_strides: &[isize],
497        dest_dims: &[usize],
498        dest_strides: &[isize],
499        edge_padding_low: &[i64],
500        edge_padding_high: &[i64],
501        interior_padding: &[i64],
502    ) -> Result<Self> {
503        check_static_indexing_dtype(dtype)?;
504        Ok(Self {
505            dtype,
506            plan: PadPlan::compile(
507                operand_dims,
508                operand_strides,
509                dest_dims,
510                dest_strides,
511                edge_padding_low,
512                edge_padding_high,
513                interior_padding,
514            )?,
515        })
516    }
517
518    #[inline]
519    pub fn dtype(&self) -> KernelDType {
520        self.dtype
521    }
522
523    #[inline]
524    pub fn plan(&self) -> &PadPlan {
525        &self.plan
526    }
527
528    /// Execute pad into an erased output descriptor using one dtype scalar as fill.
529    ///
530    /// # Errors
531    ///
532    /// Returns [`StridedError::DTypeMismatch`] when `dest` or `operand`
533    /// carries a different dtype than the plan,
534    /// [`StridedError::ByteLengthMismatch`] when `fill` is not exactly one
535    /// element wide, [`StridedError::InvalidBoolByte`] when a `bool` fill
536    /// holds a byte other than 0 or 1, and
537    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry the
538    /// compiled extents and strides. Nothing is written unless every check
539    /// succeeds.
540    pub fn execute(
541        &self,
542        dest: &mut ErasedRawStridedMut<'_>,
543        operand: &ErasedRawStridedRef<'_>,
544        fill: &[u8],
545        exec: Exec<'_>,
546    ) -> Result<()> {
547        check_dtype(self.dtype, dest.dtype())?;
548        check_dtype(self.dtype, operand.dtype())?;
549        validate_scalar_bytes(self.dtype, fill)?;
550
551        match self.dtype {
552            KernelDType::F32 => execute_pad::<f32>(&self.plan, dest, operand, fill, exec),
553            KernelDType::F64 => execute_pad::<f64>(&self.plan, dest, operand, fill, exec),
554            KernelDType::I32 => execute_pad::<i32>(&self.plan, dest, operand, fill, exec),
555            KernelDType::I64 => execute_pad::<i64>(&self.plan, dest, operand, fill, exec),
556            KernelDType::Bool => execute_pad::<bool>(&self.plan, dest, operand, fill, exec),
557            KernelDType::C32 => execute_pad::<Complex32>(&self.plan, dest, operand, fill, exec),
558            KernelDType::C64 => execute_pad::<Complex64>(&self.plan, dest, operand, fill, exec),
559            _ => Err(StridedError::UnsupportedDType {
560                dtype: self.dtype.label(),
561            }),
562        }
563    }
564
565    /// Execute pad as a full overwrite of uninitialized output storage.
566    /// On success, every reachable destination slot is fully overwritten;
567    /// unreachable holes are neither read nor initialized. Validation errors
568    /// are returned before any destination write. A panic during execution
569    /// may leave a partially initialized `MaybeUninit` destination, which is
570    /// still safely droppable; no readable value is promised for unwritten
571    /// reachable slots.
572    ///
573    /// # Errors
574    ///
575    /// Returns [`StridedError::DTypeMismatch`] when `dest` or `operand`
576    /// carries a different dtype than the plan,
577    /// [`StridedError::ByteLengthMismatch`] when `fill` is not exactly one
578    /// element wide, [`StridedError::InvalidBoolByte`] when a `bool` fill or
579    /// a `bool` operand holds a byte other than 0 or 1,
580    /// [`StridedError::OverlappingInputOutput`] when the input allocation
581    /// overlaps the destination, and
582    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry the
583    /// compiled extents and strides. Every rejection above is returned before
584    /// any destination write.
585    pub fn execute_uninit(
586        &self,
587        dest: &mut ErasedRawStridedUninitMut<'_>,
588        operand: &ErasedRawStridedPtr<'_>,
589        fill: &[u8],
590        exec: Exec<'_>,
591    ) -> Result<()> {
592        check_dtype(self.dtype, dest.dtype())?;
593        check_dtype(self.dtype, operand.dtype())?;
594        validate_scalar_bytes(self.dtype, fill)?;
595        validate_uninit_no_overlap(dest, operand, 0)?;
596        // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things.
597        // No mutable allocation may overlap `operand`'s byte extent: `dest` is the only one in
598        // this call, and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18)
599        // checked `operand` against it at erased.rs:595 by comparing whole byte ranges
600        // (`overlaps_uninit_mut`, strided-view/src/raw.rs:355). The allocation contract
601        // `operand` was built under (strided-view/src/raw.rs:204) must still hold; that is the
602        // obligation of whoever built `operand`. No conflicting access may happen while the
603        // result is used: within this call the only writer is `dest`, which does not overlap, and
604        // the `operand` contract (strided-view/src/raw.rs:212) rules out concurrent mutation from
605        // outside.
606        let operand = unsafe { operand.try_as_ref_after_no_overlap() }?;
607
608        match self.dtype {
609            KernelDType::F32 => execute_pad_uninit::<f32>(&self.plan, dest, &operand, fill, exec),
610            KernelDType::F64 => execute_pad_uninit::<f64>(&self.plan, dest, &operand, fill, exec),
611            KernelDType::I32 => execute_pad_uninit::<i32>(&self.plan, dest, &operand, fill, exec),
612            KernelDType::I64 => execute_pad_uninit::<i64>(&self.plan, dest, &operand, fill, exec),
613            KernelDType::Bool => execute_pad_uninit::<bool>(&self.plan, dest, &operand, fill, exec),
614            KernelDType::C32 => {
615                execute_pad_uninit::<Complex32>(&self.plan, dest, &operand, fill, exec)
616            }
617            KernelDType::C64 => {
618                execute_pad_uninit::<Complex64>(&self.plan, dest, &operand, fill, exec)
619            }
620            _ => Err(StridedError::UnsupportedDType {
621                dtype: self.dtype.label(),
622            }),
623        }
624    }
625}
626
627/// Dtype-erased gather wrapper.
628///
629/// This is the erased replay boundary for indexed reads. Value buffers use the
630/// configured value dtype, while the index descriptor must use `i32` or `i64`.
631#[derive(Clone, Debug)]
632pub struct ErasedGatherPlan {
633    dtype: KernelDType,
634    index_dtype: KernelDType,
635    plan: GatherPlan,
636}
637
638/// Dtype-erased fixed-window dynamic-slice wrapper.
639#[derive(Clone, Debug)]
640pub struct ErasedDynamicSlicePlan {
641    dtype: KernelDType,
642    index_dtype: KernelDType,
643    plan: DynamicSlicePlan,
644}
645
646/// Dtype-erased dynamic-update-slice wrapper.
647#[derive(Clone, Debug)]
648pub struct ErasedDynamicUpdateSlicePlan {
649    dtype: KernelDType,
650    index_dtype: KernelDType,
651    plan: DynamicUpdateSlicePlan,
652}
653
654/// Dtype-erased additive scatter wrapper.
655#[derive(Clone, Debug)]
656pub struct ErasedScatterPlan {
657    dtype: KernelDType,
658    index_dtype: KernelDType,
659    plan: ScatterPlan,
660}
661
662impl ErasedGatherPlan {
663    /// Validate and store a gather plan for one value dtype, index dtype, and layout set.
664    ///
665    /// # Errors
666    ///
667    /// Returns [`StridedError::UnsupportedDType`] when `index_dtype` is not
668    /// `i32`/`i64`, [`StridedError::StrideLengthMismatch`] when a stride list
669    /// does not match its dimension list, [`StridedError::OffsetOverflow`]
670    /// when an element count or a layout span does not fit `usize`/`isize`,
671    /// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
672    /// cannot be proven injective, [`StridedError::RankMismatch`] when
673    /// `spec.slice_sizes` or `spec.offset_dims` has the wrong length or an
674    /// index vector does not match `spec.start_index_map`,
675    /// [`StridedError::InvalidAxis`] for a listed axis outside its rank, a
676    /// repeating axis, an `index_vector_dim` beyond the index rank, a slice
677    /// size beyond its operand extent, or a collapsed axis whose slice size
678    /// is not one, and [`StridedError::ShapeMismatch`] when `dest_dims` is
679    /// not the gathered window/batch shape.
680    // Dtype pair plus the operand, index and destination layouts and the gather
681    // spec: the compile key.
682    #[allow(clippy::too_many_arguments)]
683    pub fn compile(
684        dtype: KernelDType,
685        index_dtype: KernelDType,
686        operand_dims: &[usize],
687        operand_strides: &[isize],
688        index_dims: &[usize],
689        index_strides: &[isize],
690        dest_dims: &[usize],
691        dest_strides: &[isize],
692        spec: GatherSpec,
693    ) -> Result<Self> {
694        check_index_dtype(index_dtype)?;
695        check_gather_value_dtype(dtype)?;
696        Ok(Self {
697            dtype,
698            index_dtype,
699            plan: GatherPlan::compile(
700                operand_dims,
701                operand_strides,
702                index_dims,
703                index_strides,
704                dest_dims,
705                dest_strides,
706                spec,
707            )?,
708        })
709    }
710
711    #[inline]
712    pub fn dtype(&self) -> KernelDType {
713        self.dtype
714    }
715
716    #[inline]
717    pub fn index_dtype(&self) -> KernelDType {
718        self.index_dtype
719    }
720
721    #[inline]
722    pub fn plan(&self) -> &GatherPlan {
723        &self.plan
724    }
725
726    /// Execute an indexed read into an erased output descriptor.
727    ///
728    /// # Errors
729    ///
730    /// Returns [`StridedError::DTypeMismatch`] when `dest`, `operand`, or
731    /// `start_indices` does not carry its compiled dtype,
732    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry its
733    /// compiled extents and strides, and [`StridedError::OffsetOverflow`]
734    /// when a replayed chunk's offset arithmetic cannot be represented. Start
735    /// indices are clamped into the operand window, so an out-of-range index
736    /// is not an error. The dtype and layout checks precede every write, but
737    /// the offset arithmetic runs per worker, so a destination split across
738    /// workers may be partially written when that error surfaces.
739    pub fn execute(
740        &self,
741        dest: &mut ErasedRawStridedMut<'_>,
742        operand: &ErasedRawStridedRef<'_>,
743        start_indices: &ErasedRawStridedRef<'_>,
744        exec: Exec<'_>,
745    ) -> Result<()> {
746        check_dtype(self.dtype, dest.dtype())?;
747        check_dtype(self.dtype, operand.dtype())?;
748        check_dtype(self.index_dtype, start_indices.dtype())?;
749
750        match self.dtype {
751            KernelDType::F32 => dispatch_gather_index::<f32>(
752                &self.plan,
753                self.index_dtype,
754                dest,
755                operand,
756                start_indices,
757                exec,
758            ),
759            KernelDType::F64 => dispatch_gather_index::<f64>(
760                &self.plan,
761                self.index_dtype,
762                dest,
763                operand,
764                start_indices,
765                exec,
766            ),
767            KernelDType::I32 => dispatch_gather_index::<i32>(
768                &self.plan,
769                self.index_dtype,
770                dest,
771                operand,
772                start_indices,
773                exec,
774            ),
775            KernelDType::I64 => dispatch_gather_index::<i64>(
776                &self.plan,
777                self.index_dtype,
778                dest,
779                operand,
780                start_indices,
781                exec,
782            ),
783            KernelDType::Bool => dispatch_gather_index::<bool>(
784                &self.plan,
785                self.index_dtype,
786                dest,
787                operand,
788                start_indices,
789                exec,
790            ),
791            KernelDType::C32 => dispatch_gather_index::<Complex32>(
792                &self.plan,
793                self.index_dtype,
794                dest,
795                operand,
796                start_indices,
797                exec,
798            ),
799            KernelDType::C64 => dispatch_gather_index::<Complex64>(
800                &self.plan,
801                self.index_dtype,
802                dest,
803                operand,
804                start_indices,
805                exec,
806            ),
807            _ => Err(StridedError::UnsupportedDType {
808                dtype: self.dtype.label(),
809            }),
810        }
811    }
812
813    /// Execute gather into a destination whose reachable slots may be
814    /// uninitialized. On success, every reachable destination slot is fully
815    /// overwritten; unreachable holes are neither read nor initialized. The
816    /// dtype, overlap and layout checks are returned before any destination
817    /// write. A panic during execution may leave a partially initialized
818    /// `MaybeUninit` destination, which is still safely droppable; no
819    /// readable value is promised for unwritten reachable slots.
820    ///
821    /// # Errors
822    ///
823    /// Returns [`StridedError::DTypeMismatch`] when `dest`, `operand`, or
824    /// `start_indices` does not carry its compiled dtype,
825    /// [`StridedError::OverlappingInputOutput`] when an input allocation
826    /// overlaps the destination, [`StridedError::InvalidBoolByte`] when a
827    /// `bool` operand holds a byte other than 0 or 1,
828    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry its
829    /// compiled extents and strides, and [`StridedError::OffsetOverflow`]
830    /// when a replayed chunk's offset arithmetic cannot be represented. Every
831    /// rejection except the last is returned before any destination write;
832    /// the offset arithmetic runs per worker, so a destination split across
833    /// workers may be partially initialized when that error surfaces.
834    pub fn execute_uninit(
835        &self,
836        dest: &mut ErasedRawStridedUninitMut<'_>,
837        operand: &ErasedRawStridedPtr<'_>,
838        start_indices: &ErasedRawStridedPtr<'_>,
839        exec: Exec<'_>,
840    ) -> Result<()> {
841        check_dtype(self.dtype, dest.dtype())?;
842        check_dtype(self.dtype, operand.dtype())?;
843        check_dtype(self.index_dtype, start_indices.dtype())?;
844        validate_uninit_no_overlap(dest, operand, 0)?;
845        validate_uninit_no_overlap(dest, start_indices, 1)?;
846        // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things.
847        // No mutable allocation may overlap `operand`'s byte extent: `dest` is the only one in
848        // this call, and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18)
849        // checked `operand` against it at erased.rs:844 by comparing whole byte ranges
850        // (`overlaps_uninit_mut`, strided-view/src/raw.rs:355). The allocation contract
851        // `operand` was built under (strided-view/src/raw.rs:204) must still hold; that is the
852        // obligation of whoever built `operand`. No conflicting access may happen while the
853        // result is used: within this call the only writer is `dest`, which does not overlap, and
854        // the `operand` contract (strided-view/src/raw.rs:212) rules out concurrent mutation from
855        // outside.
856        let operand = &unsafe { operand.try_as_ref_after_no_overlap() }?;
857        // SAFETY: as for `operand` above: `validate_uninit_no_overlap` checked `start_indices`
858        // against `dest` at erased.rs:845, and the same allocation contract and exclusive `dest`
859        // borrow apply.
860        let start_indices = &unsafe { start_indices.try_as_ref_after_no_overlap() }?;
861        match self.dtype {
862            KernelDType::F32 => execute_gather_uninit_dispatch::<f32>(
863                &self.plan,
864                self.index_dtype,
865                dest,
866                operand,
867                start_indices,
868                exec,
869            ),
870            KernelDType::F64 => execute_gather_uninit_dispatch::<f64>(
871                &self.plan,
872                self.index_dtype,
873                dest,
874                operand,
875                start_indices,
876                exec,
877            ),
878            KernelDType::I32 => execute_gather_uninit_dispatch::<i32>(
879                &self.plan,
880                self.index_dtype,
881                dest,
882                operand,
883                start_indices,
884                exec,
885            ),
886            KernelDType::I64 => execute_gather_uninit_dispatch::<i64>(
887                &self.plan,
888                self.index_dtype,
889                dest,
890                operand,
891                start_indices,
892                exec,
893            ),
894            KernelDType::Bool => execute_gather_uninit_dispatch::<bool>(
895                &self.plan,
896                self.index_dtype,
897                dest,
898                operand,
899                start_indices,
900                exec,
901            ),
902            KernelDType::C32 => execute_gather_uninit_dispatch::<Complex32>(
903                &self.plan,
904                self.index_dtype,
905                dest,
906                operand,
907                start_indices,
908                exec,
909            ),
910            KernelDType::C64 => execute_gather_uninit_dispatch::<Complex64>(
911                &self.plan,
912                self.index_dtype,
913                dest,
914                operand,
915                start_indices,
916                exec,
917            ),
918            _ => Err(StridedError::UnsupportedDType {
919                dtype: self.dtype.label(),
920            }),
921        }
922    }
923}
924
925impl ErasedDynamicSlicePlan {
926    /// Validate and store a dynamic-slice plan for one value dtype, index dtype, and layout set.
927    ///
928    /// # Errors
929    ///
930    /// Returns [`StridedError::UnsupportedDType`] when `index_dtype` is not
931    /// `i32`/`i64`, [`StridedError::StrideLengthMismatch`] when a stride list
932    /// does not match its dimension list, [`StridedError::RankMismatch`] when
933    /// `slice_sizes` differs from the operand rank, or the start layout is
934    /// not a rank-1 vector of that same length,
935    /// [`StridedError::OffsetOverflow`] when an element count or a layout
936    /// span does not fit `usize`/`isize`, [`StridedError::ShapeMismatch`]
937    /// when `dest_dims` differs from `slice_sizes`,
938    /// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
939    /// cannot be proven injective, and [`StridedError::InvalidAxis`] when a
940    /// slice size exceeds its operand extent.
941    // Dtype pair plus the operand, start and destination layouts and the slice sizes: the plan key.
942    #[allow(clippy::too_many_arguments)]
943    pub fn compile(
944        dtype: KernelDType,
945        index_dtype: KernelDType,
946        operand_dims: &[usize],
947        operand_strides: &[isize],
948        start_dims: &[usize],
949        start_strides: &[isize],
950        dest_dims: &[usize],
951        dest_strides: &[isize],
952        slice_sizes: &[usize],
953    ) -> Result<Self> {
954        check_index_dtype(index_dtype)?;
955        check_gather_value_dtype(dtype)?;
956        Ok(Self {
957            dtype,
958            index_dtype,
959            plan: DynamicSlicePlan::compile(
960                operand_dims,
961                operand_strides,
962                start_dims,
963                start_strides,
964                dest_dims,
965                dest_strides,
966                slice_sizes,
967            )?,
968        })
969    }
970
971    #[inline]
972    pub fn dtype(&self) -> KernelDType {
973        self.dtype
974    }
975
976    #[inline]
977    pub fn index_dtype(&self) -> KernelDType {
978        self.index_dtype
979    }
980
981    #[inline]
982    pub fn plan(&self) -> &DynamicSlicePlan {
983        &self.plan
984    }
985
986    /// Execute a fixed-window dynamic slice into an erased output descriptor.
987    ///
988    /// # Errors
989    ///
990    /// Returns [`StridedError::DTypeMismatch`] when `dest`, `operand`, or
991    /// `starts` does not carry its compiled dtype, and
992    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry its
993    /// compiled extents and strides. Starts are clamped to `operand_dims -
994    /// slice_sizes`, so an out-of-range start is not an error, and nothing is
995    /// written unless every check succeeds.
996    pub fn execute(
997        &self,
998        dest: &mut ErasedRawStridedMut<'_>,
999        operand: &ErasedRawStridedRef<'_>,
1000        starts: &ErasedRawStridedRef<'_>,
1001        exec: Exec<'_>,
1002    ) -> Result<()> {
1003        check_dtype(self.dtype, dest.dtype())?;
1004        check_dtype(self.dtype, operand.dtype())?;
1005        check_dtype(self.index_dtype, starts.dtype())?;
1006
1007        match self.dtype {
1008            KernelDType::F32 => dispatch_dynamic_slice_index::<f32>(
1009                &self.plan,
1010                self.index_dtype,
1011                dest,
1012                operand,
1013                starts,
1014                exec,
1015            ),
1016            KernelDType::F64 => dispatch_dynamic_slice_index::<f64>(
1017                &self.plan,
1018                self.index_dtype,
1019                dest,
1020                operand,
1021                starts,
1022                exec,
1023            ),
1024            KernelDType::I32 => dispatch_dynamic_slice_index::<i32>(
1025                &self.plan,
1026                self.index_dtype,
1027                dest,
1028                operand,
1029                starts,
1030                exec,
1031            ),
1032            KernelDType::I64 => dispatch_dynamic_slice_index::<i64>(
1033                &self.plan,
1034                self.index_dtype,
1035                dest,
1036                operand,
1037                starts,
1038                exec,
1039            ),
1040            KernelDType::Bool => dispatch_dynamic_slice_index::<bool>(
1041                &self.plan,
1042                self.index_dtype,
1043                dest,
1044                operand,
1045                starts,
1046                exec,
1047            ),
1048            KernelDType::C32 => dispatch_dynamic_slice_index::<Complex32>(
1049                &self.plan,
1050                self.index_dtype,
1051                dest,
1052                operand,
1053                starts,
1054                exec,
1055            ),
1056            KernelDType::C64 => dispatch_dynamic_slice_index::<Complex64>(
1057                &self.plan,
1058                self.index_dtype,
1059                dest,
1060                operand,
1061                starts,
1062                exec,
1063            ),
1064            _ => Err(StridedError::UnsupportedDType {
1065                dtype: self.dtype.label(),
1066            }),
1067        }
1068    }
1069
1070    /// Execute dynamic slice into a destination whose reachable slots may be
1071    /// uninitialized.
1072    /// On success, every reachable destination slot is fully overwritten;
1073    /// unreachable holes are neither read nor initialized. Validation errors
1074    /// are returned before any destination write. A panic during execution may
1075    /// leave reachable slots partially initialized, but the `MaybeUninit`
1076    /// destination remains safely droppable.
1077    ///
1078    /// # Errors
1079    ///
1080    /// Returns [`StridedError::DTypeMismatch`] when `dest`, `operand`, or
1081    /// `starts` does not carry its compiled dtype,
1082    /// [`StridedError::OverlappingInputOutput`] when an input allocation
1083    /// overlaps the destination, [`StridedError::InvalidBoolByte`] when a
1084    /// `bool` operand holds a byte other than 0 or 1,
1085    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry its
1086    /// compiled extents and strides. Every rejection above is returned before
1087    /// any destination write.
1088    pub fn execute_uninit(
1089        &self,
1090        dest: &mut ErasedRawStridedUninitMut<'_>,
1091        operand: &ErasedRawStridedPtr<'_>,
1092        starts: &ErasedRawStridedPtr<'_>,
1093        exec: Exec<'_>,
1094    ) -> Result<()> {
1095        check_dtype(self.dtype, dest.dtype())?;
1096        check_dtype(self.dtype, operand.dtype())?;
1097        check_dtype(self.index_dtype, starts.dtype())?;
1098        validate_uninit_no_overlap(dest, operand, 0)?;
1099        validate_uninit_no_overlap(dest, starts, 1)?;
1100        // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things.
1101        // No mutable allocation may overlap `operand`'s byte extent: `dest` is the only one in
1102        // this call, and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18)
1103        // checked `operand` against it at erased.rs:1098 by comparing whole byte ranges
1104        // (`overlaps_uninit_mut`, strided-view/src/raw.rs:355). The allocation contract
1105        // `operand` was built under (strided-view/src/raw.rs:204) must still hold; that is the
1106        // obligation of whoever built `operand`. No conflicting access may happen while the
1107        // result is used: within this call the only writer is `dest`, which does not overlap, and
1108        // the `operand` contract (strided-view/src/raw.rs:212) rules out concurrent mutation from
1109        // outside.
1110        let operand = &unsafe { operand.try_as_ref_after_no_overlap() }?;
1111        // SAFETY: as for `operand` above: `validate_uninit_no_overlap` checked `starts` against
1112        // `dest` at erased.rs:1099, and the same allocation contract and exclusive `dest` borrow
1113        // apply.
1114        let starts = &unsafe { starts.try_as_ref_after_no_overlap() }?;
1115        match self.dtype {
1116            KernelDType::F32 => execute_dynamic_slice_uninit_dispatch::<f32>(
1117                &self.plan,
1118                self.index_dtype,
1119                dest,
1120                operand,
1121                starts,
1122                exec,
1123            ),
1124            KernelDType::F64 => execute_dynamic_slice_uninit_dispatch::<f64>(
1125                &self.plan,
1126                self.index_dtype,
1127                dest,
1128                operand,
1129                starts,
1130                exec,
1131            ),
1132            KernelDType::I32 => execute_dynamic_slice_uninit_dispatch::<i32>(
1133                &self.plan,
1134                self.index_dtype,
1135                dest,
1136                operand,
1137                starts,
1138                exec,
1139            ),
1140            KernelDType::I64 => execute_dynamic_slice_uninit_dispatch::<i64>(
1141                &self.plan,
1142                self.index_dtype,
1143                dest,
1144                operand,
1145                starts,
1146                exec,
1147            ),
1148            KernelDType::Bool => execute_dynamic_slice_uninit_dispatch::<bool>(
1149                &self.plan,
1150                self.index_dtype,
1151                dest,
1152                operand,
1153                starts,
1154                exec,
1155            ),
1156            KernelDType::C32 => execute_dynamic_slice_uninit_dispatch::<Complex32>(
1157                &self.plan,
1158                self.index_dtype,
1159                dest,
1160                operand,
1161                starts,
1162                exec,
1163            ),
1164            KernelDType::C64 => execute_dynamic_slice_uninit_dispatch::<Complex64>(
1165                &self.plan,
1166                self.index_dtype,
1167                dest,
1168                operand,
1169                starts,
1170                exec,
1171            ),
1172            _ => Err(StridedError::UnsupportedDType {
1173                dtype: self.dtype.label(),
1174            }),
1175        }
1176    }
1177}
1178
1179impl ErasedDynamicUpdateSlicePlan {
1180    /// Validate and store a dynamic-update-slice plan for one value dtype, index dtype, and layout set.
1181    ///
1182    /// # Errors
1183    ///
1184    /// Returns [`StridedError::UnsupportedDType`] when `index_dtype` is not
1185    /// `i32`/`i64`, [`StridedError::StrideLengthMismatch`] when a stride list
1186    /// does not match its dimension list, [`StridedError::RankMismatch`]
1187    /// when `update_dims` differs from the operand rank, or the start layout
1188    /// is not a rank-1 vector of that same length,
1189    /// [`StridedError::OffsetOverflow`] when an element count or a layout
1190    /// span does not fit `usize`/`isize`, [`StridedError::ShapeMismatch`]
1191    /// when `dest_dims` differs from `operand_dims`,
1192    /// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
1193    /// cannot be proven injective, and [`StridedError::InvalidAxis`] when
1194    /// an update extent exceeds its operand extent.
1195    // Dtype pair plus the operand, start, update and destination layouts: the plan key.
1196    #[allow(clippy::too_many_arguments)]
1197    pub fn compile(
1198        dtype: KernelDType,
1199        index_dtype: KernelDType,
1200        operand_dims: &[usize],
1201        operand_strides: &[isize],
1202        start_dims: &[usize],
1203        start_strides: &[isize],
1204        update_dims: &[usize],
1205        update_strides: &[isize],
1206        dest_dims: &[usize],
1207        dest_strides: &[isize],
1208    ) -> Result<Self> {
1209        check_index_dtype(index_dtype)?;
1210        check_gather_value_dtype(dtype)?;
1211        Ok(Self {
1212            dtype,
1213            index_dtype,
1214            plan: DynamicUpdateSlicePlan::compile(
1215                operand_dims,
1216                operand_strides,
1217                start_dims,
1218                start_strides,
1219                update_dims,
1220                update_strides,
1221                dest_dims,
1222                dest_strides,
1223            )?,
1224        })
1225    }
1226
1227    #[inline]
1228    pub fn dtype(&self) -> KernelDType {
1229        self.dtype
1230    }
1231
1232    #[inline]
1233    pub fn index_dtype(&self) -> KernelDType {
1234        self.index_dtype
1235    }
1236
1237    #[inline]
1238    pub fn plan(&self) -> &DynamicUpdateSlicePlan {
1239        &self.plan
1240    }
1241
1242    /// Execute a dynamic update slice into an erased output descriptor.
1243    ///
1244    /// # Errors
1245    ///
1246    /// Returns [`StridedError::DTypeMismatch`] when `dest`, `operand`,
1247    /// `update`, or `starts` does not carry its compiled dtype, and
1248    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry its
1249    /// compiled extents and strides. Starts are clamped to
1250    /// `operand_dims - update_dims`, so an out-of-range start is not an
1251    /// error, and the operand copy rejects everything above before it runs.
1252    pub fn execute(
1253        &self,
1254        dest: &mut ErasedRawStridedMut<'_>,
1255        operand: &ErasedRawStridedRef<'_>,
1256        update: &ErasedRawStridedRef<'_>,
1257        starts: &ErasedRawStridedRef<'_>,
1258        exec: Exec<'_>,
1259    ) -> Result<()> {
1260        check_dtype(self.dtype, dest.dtype())?;
1261        check_dtype(self.dtype, operand.dtype())?;
1262        check_dtype(self.dtype, update.dtype())?;
1263        check_dtype(self.index_dtype, starts.dtype())?;
1264
1265        match self.dtype {
1266            KernelDType::F32 => dispatch_dynamic_update_slice_index::<f32>(
1267                &self.plan,
1268                self.index_dtype,
1269                dest,
1270                operand,
1271                update,
1272                starts,
1273                exec,
1274            ),
1275            KernelDType::F64 => dispatch_dynamic_update_slice_index::<f64>(
1276                &self.plan,
1277                self.index_dtype,
1278                dest,
1279                operand,
1280                update,
1281                starts,
1282                exec,
1283            ),
1284            KernelDType::I32 => dispatch_dynamic_update_slice_index::<i32>(
1285                &self.plan,
1286                self.index_dtype,
1287                dest,
1288                operand,
1289                update,
1290                starts,
1291                exec,
1292            ),
1293            KernelDType::I64 => dispatch_dynamic_update_slice_index::<i64>(
1294                &self.plan,
1295                self.index_dtype,
1296                dest,
1297                operand,
1298                update,
1299                starts,
1300                exec,
1301            ),
1302            KernelDType::Bool => dispatch_dynamic_update_slice_index::<bool>(
1303                &self.plan,
1304                self.index_dtype,
1305                dest,
1306                operand,
1307                update,
1308                starts,
1309                exec,
1310            ),
1311            KernelDType::C32 => dispatch_dynamic_update_slice_index::<Complex32>(
1312                &self.plan,
1313                self.index_dtype,
1314                dest,
1315                operand,
1316                update,
1317                starts,
1318                exec,
1319            ),
1320            KernelDType::C64 => dispatch_dynamic_update_slice_index::<Complex64>(
1321                &self.plan,
1322                self.index_dtype,
1323                dest,
1324                operand,
1325                update,
1326                starts,
1327                exec,
1328            ),
1329            _ => Err(StridedError::UnsupportedDType {
1330                dtype: self.dtype.label(),
1331            }),
1332        }
1333    }
1334
1335    /// On success, the copy phase initializes every reachable destination
1336    /// slot before the read-modify-write phase. Unreachable holes are neither
1337    /// read nor initialized. Validation errors before the copy leave the
1338    /// destination untouched; an error or panic after the copy may leave a
1339    /// mixture of old and new reachable values, all initialized and safely
1340    /// droppable.
1341    ///
1342    /// # Errors
1343    ///
1344    /// Returns [`StridedError::DTypeMismatch`] when `dest`, `operand`,
1345    /// `update`, or `starts` does not carry its compiled dtype,
1346    /// [`StridedError::OverlappingInputOutput`] when an input allocation
1347    /// overlaps the destination, [`StridedError::InvalidBoolByte`] when a
1348    /// `bool` operand or update holds a byte other than 0 or 1,
1349    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry its
1350    /// compiled extents and strides. Every rejection above is returned before
1351    /// the operand copy runs.
1352    pub fn execute_uninit(
1353        &self,
1354        dest: &mut ErasedRawStridedUninitMut<'_>,
1355        operand: &ErasedRawStridedPtr<'_>,
1356        update: &ErasedRawStridedPtr<'_>,
1357        starts: &ErasedRawStridedPtr<'_>,
1358        exec: Exec<'_>,
1359    ) -> Result<()> {
1360        check_dtype(self.dtype, dest.dtype())?;
1361        check_dtype(self.dtype, operand.dtype())?;
1362        check_dtype(self.dtype, update.dtype())?;
1363        check_dtype(self.index_dtype, starts.dtype())?;
1364        validate_uninit_no_overlap(dest, operand, 0)?;
1365        validate_uninit_no_overlap(dest, update, 1)?;
1366        validate_uninit_no_overlap(dest, starts, 2)?;
1367        // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things.
1368        // No mutable allocation may overlap `operand`'s byte extent: `dest` is the only one in
1369        // this call, and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18)
1370        // checked `operand` against it at erased.rs:1364 by comparing whole byte ranges
1371        // (`overlaps_uninit_mut`, strided-view/src/raw.rs:355). The allocation contract
1372        // `operand` was built under (strided-view/src/raw.rs:204) must still hold; that is the
1373        // obligation of whoever built `operand`. No conflicting access may happen while the
1374        // result is used: within this call the only writer is `dest`, which does not overlap, and
1375        // the `operand` contract (strided-view/src/raw.rs:212) rules out concurrent mutation from
1376        // outside.
1377        let operand = &unsafe { operand.try_as_ref_after_no_overlap() }?;
1378        // SAFETY: as for `operand` above: `validate_uninit_no_overlap` checked `update` against
1379        // `dest` at erased.rs:1365, and the same allocation contract and exclusive `dest` borrow
1380        // apply.
1381        let update = &unsafe { update.try_as_ref_after_no_overlap() }?;
1382        // SAFETY: as for `operand` above: `validate_uninit_no_overlap` checked `starts` against
1383        // `dest` at erased.rs:1366, and the same allocation contract and exclusive `dest` borrow
1384        // apply.
1385        let starts = &unsafe { starts.try_as_ref_after_no_overlap() }?;
1386        match self.dtype {
1387            KernelDType::F32 => execute_dynamic_update_uninit_dispatch::<f32>(
1388                &self.plan,
1389                self.index_dtype,
1390                dest,
1391                operand,
1392                update,
1393                starts,
1394                exec,
1395            ),
1396            KernelDType::F64 => execute_dynamic_update_uninit_dispatch::<f64>(
1397                &self.plan,
1398                self.index_dtype,
1399                dest,
1400                operand,
1401                update,
1402                starts,
1403                exec,
1404            ),
1405            KernelDType::I32 => execute_dynamic_update_uninit_dispatch::<i32>(
1406                &self.plan,
1407                self.index_dtype,
1408                dest,
1409                operand,
1410                update,
1411                starts,
1412                exec,
1413            ),
1414            KernelDType::I64 => execute_dynamic_update_uninit_dispatch::<i64>(
1415                &self.plan,
1416                self.index_dtype,
1417                dest,
1418                operand,
1419                update,
1420                starts,
1421                exec,
1422            ),
1423            KernelDType::Bool => execute_dynamic_update_uninit_dispatch::<bool>(
1424                &self.plan,
1425                self.index_dtype,
1426                dest,
1427                operand,
1428                update,
1429                starts,
1430                exec,
1431            ),
1432            KernelDType::C32 => execute_dynamic_update_uninit_dispatch::<Complex32>(
1433                &self.plan,
1434                self.index_dtype,
1435                dest,
1436                operand,
1437                update,
1438                starts,
1439                exec,
1440            ),
1441            KernelDType::C64 => execute_dynamic_update_uninit_dispatch::<Complex64>(
1442                &self.plan,
1443                self.index_dtype,
1444                dest,
1445                operand,
1446                update,
1447                starts,
1448                exec,
1449            ),
1450            _ => Err(StridedError::UnsupportedDType {
1451                dtype: self.dtype.label(),
1452            }),
1453        }
1454    }
1455}
1456
1457impl ErasedScatterPlan {
1458    /// Validate and store an additive scatter plan for one value dtype, index dtype, and layout set.
1459    ///
1460    /// # Errors
1461    ///
1462    /// Returns [`StridedError::UnsupportedDType`] when `index_dtype` is not
1463    /// `i32`/`i64`, or `dtype` is `bool`,
1464    /// [`StridedError::StrideLengthMismatch`] when a stride list does not
1465    /// match its dimension list, [`StridedError::OffsetOverflow`] when an
1466    /// element count or a layout span does not fit `usize`/`isize`,
1467    /// [`StridedError::ShapeMismatch`] when `dest_dims` differs from
1468    /// `operand_dims` or an update batch extent differs from the index batch
1469    /// shape, [`StridedError::NonInjectiveOutputLayout`] when the destination
1470    /// layout cannot be proven injective, [`StridedError::InvalidAxis`] for a
1471    /// listed axis outside its rank, a repeating axis, an `index_vector_dim`
1472    /// beyond the index rank, or an update window extent exceeding its
1473    /// operand extent, and [`StridedError::RankMismatch`] for an index vector
1474    /// that does not match `spec.scatter_dims_to_operand_dims`, a
1475    /// wrong-length `spec.update_window_dims`, or an update batch rank that
1476    /// disagrees with the index batch shape.
1477    // Dtype pair plus the operand, index, update and destination layouts and the
1478    // scatter spec: the plan key.
1479    #[allow(clippy::too_many_arguments)]
1480    pub fn compile(
1481        dtype: KernelDType,
1482        index_dtype: KernelDType,
1483        operand_dims: &[usize],
1484        operand_strides: &[isize],
1485        index_dims: &[usize],
1486        index_strides: &[isize],
1487        update_dims: &[usize],
1488        update_strides: &[isize],
1489        dest_dims: &[usize],
1490        dest_strides: &[isize],
1491        spec: ScatterSpec,
1492    ) -> Result<Self> {
1493        check_index_dtype(index_dtype)?;
1494        check_scatter_value_dtype(dtype)?;
1495        Ok(Self {
1496            dtype,
1497            index_dtype,
1498            plan: ScatterPlan::compile(
1499                operand_dims,
1500                operand_strides,
1501                index_dims,
1502                index_strides,
1503                update_dims,
1504                update_strides,
1505                dest_dims,
1506                dest_strides,
1507                spec,
1508            )?,
1509        })
1510    }
1511
1512    #[inline]
1513    pub fn dtype(&self) -> KernelDType {
1514        self.dtype
1515    }
1516
1517    #[inline]
1518    pub fn index_dtype(&self) -> KernelDType {
1519        self.index_dtype
1520    }
1521
1522    #[inline]
1523    pub fn plan(&self) -> &ScatterPlan {
1524        &self.plan
1525    }
1526
1527    /// Execute additive scatter into an erased output descriptor.
1528    ///
1529    /// # Errors
1530    ///
1531    /// Returns [`StridedError::DTypeMismatch`] when `dest`, `operand`,
1532    /// `scatter_indices`, or `updates` does not carry its compiled dtype,
1533    /// [`StridedError::PlanLayoutMismatch`] when a view does not carry its
1534    /// compiled extents and strides. Scatter indices are clamped into the
1535    /// operand window, so an out-of-range index is not an error, and the
1536    /// operand copy rejects everything above before it runs.
1537    pub fn execute(
1538        &self,
1539        dest: &mut ErasedRawStridedMut<'_>,
1540        operand: &ErasedRawStridedRef<'_>,
1541        scatter_indices: &ErasedRawStridedRef<'_>,
1542        updates: &ErasedRawStridedRef<'_>,
1543        exec: Exec<'_>,
1544    ) -> Result<()> {
1545        check_dtype(self.dtype, dest.dtype())?;
1546        check_dtype(self.dtype, operand.dtype())?;
1547        check_dtype(self.dtype, updates.dtype())?;
1548        check_dtype(self.index_dtype, scatter_indices.dtype())?;
1549
1550        match self.dtype {
1551            KernelDType::F32 => dispatch_scatter_index::<f32>(
1552                &self.plan,
1553                self.index_dtype,
1554                dest,
1555                operand,
1556                scatter_indices,
1557                updates,
1558                exec,
1559            ),
1560            KernelDType::F64 => dispatch_scatter_index::<f64>(
1561                &self.plan,
1562                self.index_dtype,
1563                dest,
1564                operand,
1565                scatter_indices,
1566                updates,
1567                exec,
1568            ),
1569            KernelDType::I32 => dispatch_scatter_index::<i32>(
1570                &self.plan,
1571                self.index_dtype,
1572                dest,
1573                operand,
1574                scatter_indices,
1575                updates,
1576                exec,
1577            ),
1578            KernelDType::I64 => dispatch_scatter_index::<i64>(
1579                &self.plan,
1580                self.index_dtype,
1581                dest,
1582                operand,
1583                scatter_indices,
1584                updates,
1585                exec,
1586            ),
1587            KernelDType::C32 => dispatch_scatter_index::<Complex32>(
1588                &self.plan,
1589                self.index_dtype,
1590                dest,
1591                operand,
1592                scatter_indices,
1593                updates,
1594                exec,
1595            ),
1596            KernelDType::C64 => dispatch_scatter_index::<Complex64>(
1597                &self.plan,
1598                self.index_dtype,
1599                dest,
1600                operand,
1601                scatter_indices,
1602                updates,
1603                exec,
1604            ),
1605            _ => Err(StridedError::UnsupportedDType {
1606                dtype: self.dtype.label(),
1607            }),
1608        }
1609    }
1610
1611    /// On success, the copy phase initializes every reachable destination
1612    /// slot before the read-modify-write phase. Unreachable holes are neither
1613    /// read nor initialized. Validation errors before the copy leave the
1614    /// destination untouched; an error or panic after the copy may leave a
1615    /// mixture of old and new reachable values, all initialized and safely
1616    /// droppable.
1617    ///
1618    /// # Errors
1619    ///
1620    /// Returns [`StridedError::DTypeMismatch`] when `dest`, `operand`,
1621    /// `scatter_indices`, or `updates` does not carry its compiled dtype,
1622    /// [`StridedError::OverlappingInputOutput`] when an input allocation
1623    /// overlaps the destination, and [`StridedError::PlanLayoutMismatch`]
1624    /// when a view does not carry its compiled extents and strides. Every
1625    /// rejection above is returned before the operand copy runs.
1626    pub fn execute_uninit(
1627        &self,
1628        dest: &mut ErasedRawStridedUninitMut<'_>,
1629        operand: &ErasedRawStridedPtr<'_>,
1630        scatter_indices: &ErasedRawStridedPtr<'_>,
1631        updates: &ErasedRawStridedPtr<'_>,
1632        exec: Exec<'_>,
1633    ) -> Result<()> {
1634        check_dtype(self.dtype, dest.dtype())?;
1635        check_dtype(self.dtype, operand.dtype())?;
1636        check_dtype(self.dtype, updates.dtype())?;
1637        check_dtype(self.index_dtype, scatter_indices.dtype())?;
1638        validate_uninit_no_overlap(dest, operand, 0)?;
1639        validate_uninit_no_overlap(dest, scatter_indices, 1)?;
1640        validate_uninit_no_overlap(dest, updates, 2)?;
1641        // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things.
1642        // No mutable allocation may overlap `operand`'s byte extent: `dest` is the only one in
1643        // this call, and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18)
1644        // checked `operand` against it at erased.rs:1638 by comparing whole byte ranges
1645        // (`overlaps_uninit_mut`, strided-view/src/raw.rs:355). The allocation contract
1646        // `operand` was built under (strided-view/src/raw.rs:204) must still hold; that is the
1647        // obligation of whoever built `operand`. No conflicting access may happen while the
1648        // result is used: within this call the only writer is `dest`, which does not overlap, and
1649        // the `operand` contract (strided-view/src/raw.rs:212) rules out concurrent mutation from
1650        // outside.
1651        let operand = &unsafe { operand.try_as_ref_after_no_overlap() }?;
1652        // SAFETY: as for `operand` above: `validate_uninit_no_overlap` checked `scatter_indices`
1653        // against `dest` at erased.rs:1639, and the same allocation contract and exclusive `dest`
1654        // borrow apply.
1655        let scatter_indices = &unsafe { scatter_indices.try_as_ref_after_no_overlap() }?;
1656        // SAFETY: as for `operand` above: `validate_uninit_no_overlap` checked `updates` against
1657        // `dest` at erased.rs:1640, and the same allocation contract and exclusive `dest` borrow
1658        // apply.
1659        let updates = &unsafe { updates.try_as_ref_after_no_overlap() }?;
1660        match self.dtype {
1661            KernelDType::F32 => execute_scatter_uninit_dispatch::<f32>(
1662                &self.plan,
1663                self.index_dtype,
1664                dest,
1665                operand,
1666                scatter_indices,
1667                updates,
1668                exec,
1669            ),
1670            KernelDType::F64 => execute_scatter_uninit_dispatch::<f64>(
1671                &self.plan,
1672                self.index_dtype,
1673                dest,
1674                operand,
1675                scatter_indices,
1676                updates,
1677                exec,
1678            ),
1679            KernelDType::I32 => execute_scatter_uninit_dispatch::<i32>(
1680                &self.plan,
1681                self.index_dtype,
1682                dest,
1683                operand,
1684                scatter_indices,
1685                updates,
1686                exec,
1687            ),
1688            KernelDType::I64 => execute_scatter_uninit_dispatch::<i64>(
1689                &self.plan,
1690                self.index_dtype,
1691                dest,
1692                operand,
1693                scatter_indices,
1694                updates,
1695                exec,
1696            ),
1697            KernelDType::C32 => execute_scatter_uninit_dispatch::<Complex32>(
1698                &self.plan,
1699                self.index_dtype,
1700                dest,
1701                operand,
1702                scatter_indices,
1703                updates,
1704                exec,
1705            ),
1706            KernelDType::C64 => execute_scatter_uninit_dispatch::<Complex64>(
1707                &self.plan,
1708                self.index_dtype,
1709                dest,
1710                operand,
1711                scatter_indices,
1712                updates,
1713                exec,
1714            ),
1715            _ => Err(StridedError::UnsupportedDType {
1716                dtype: self.dtype.label(),
1717            }),
1718        }
1719    }
1720}
1721
1722fn execute_one_shot_map<T: OneShotScalar>(
1723    op: ErasedMapOp,
1724    dest: &mut ErasedRawStridedMut<'_>,
1725    input: &ErasedRawStridedRef<'_>,
1726    exec: Exec<'_>,
1727) -> Result<()> {
1728    if !T::supports_map(op) {
1729        return Err(StridedError::UnsupportedOp {
1730            op: op.label(),
1731            dtype: T::one_shot_dtype_label(),
1732        });
1733    }
1734    let validated = strided_basic::execution::validate_destination_layout_without_alloc(
1735        dest.dims(),
1736        dest.strides(),
1737    )?;
1738    strided_basic::execution::ensure_same_shape(dest.dims(), input.dims())?;
1739    if dest.dims().contains(&0) {
1740        return Ok(());
1741    }
1742
1743    let dest_dims = dest.dims();
1744    let dest_strides = dest.strides();
1745    let dest_offset = dest.offset();
1746    let dest_data = dest.data_as_mut::<T>()?;
1747    // SAFETY: `RawStridedMut::new_unchecked` (strided-view/src/raw.rs:1115) needs every index
1748    // reachable from `dest_offset` through `dest_dims`/`dest_strides` inside `dest_data`, and no
1749    // alias that breaks mutable access. When `dest` was built (`from_slice_mut`,
1750    // strided-view/src/raw.rs:591, or `from_raw_parts`, strided-view/src/raw.rs:646),
1751    // `validate_bounds` (strided-view/src/view.rs:187) checked exactly these dims, strides and
1752    // offset against its element count, `byte_len / size_of::<T>()`, which is the length
1753    // `data_as_mut` (strided-view/src/raw.rs:710) returns after checking the dtype. `data_as_mut`
1754    // reborrows the descriptor through `&mut self`, so `dest_data` is the only access to that
1755    // storage while `dest` lives.
1756    let mut dest =
1757        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
1758    let input = erased_raw_ref::<T>(input)?;
1759
1760    // The op is matched once here so each arm replays a loop whose closure
1761    // names a constant op. After inlining, `T::map` folds to one arithmetic
1762    // expression and the contiguous and threaded leaf loops can vectorize.
1763    macro_rules! replay {
1764        ($op:ident) => {
1765            // SAFETY: `map_raw_into_validated` (strided-basic/src/execution.rs:365) requires
1766            // three things. Every input shape matches the destination: `ensure_same_shape`
1767            // checked it at erased.rs:1738. `validated` belongs to this destination's geometry:
1768            // `validate_destination_layout_without_alloc` produced it at erased.rs:1734 from the
1769            // same `dest.dims()` and `dest.strides()` that `dest` was rebuilt with. Bounds and
1770            // aliasing hold throughout the replay: each descriptor is bounded as argued where it
1771            // is built above, `dest` is an exclusive reborrow, and the public entry rejected
1772            // input/output overlap before converting the inputs (erased.rs:89).
1773            unsafe {
1774                strided_basic::execution::map_raw_into_validated::<T, T, Identity>(
1775                    &mut dest,
1776                    &input,
1777                    |value| T::map(ErasedMapOp::$op, value),
1778                    validated,
1779                    exec,
1780                )
1781            }
1782        };
1783    }
1784    match op {
1785        ErasedMapOp::Negate => replay!(Negate),
1786        ErasedMapOp::Conj => replay!(Conj),
1787        ErasedMapOp::Abs => replay!(Abs),
1788        ErasedMapOp::Sign => replay!(Sign),
1789    }
1790}
1791
1792fn execute_one_shot_map_with<D, A>(
1793    dest: &mut ErasedRawStridedMut<'_>,
1794    input: &ErasedRawStridedRef<'_>,
1795    map: impl Fn(A) -> D + Sync,
1796    exec: Exec<'_>,
1797) -> Result<()>
1798where
1799    D: Copy + Send + Sync + KernelStorageElement,
1800    A: Copy + Send + Sync + KernelStorageElement,
1801{
1802    let validated = strided_basic::execution::validate_destination_layout_without_alloc(
1803        dest.dims(),
1804        dest.strides(),
1805    )?;
1806    strided_basic::execution::ensure_same_shape(dest.dims(), input.dims())?;
1807    if dest.dims().contains(&0) {
1808        return Ok(());
1809    }
1810    let dest_dims = dest.dims();
1811    let dest_strides = dest.strides();
1812    let dest_offset = dest.offset();
1813    let dest_data = dest.data_as_mut::<D>()?;
1814    // SAFETY: as for `dest` in `execute_one_shot_map` (erased.rs:1747): `dest`'s construction ran
1815    // `validate_bounds` over these dims, strides and offset, and `data_as_mut` hands out the only
1816    // access to its storage.
1817    let mut dest =
1818        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
1819    let input = erased_raw_ref::<A>(input)?;
1820    // SAFETY: `map_raw_into_validated` (strided-basic/src/execution.rs:365) requires three
1821    // things. Every input shape matches the destination: `ensure_same_shape` checked it at
1822    // erased.rs:1806. `validated` belongs to this destination's geometry:
1823    // `validate_destination_layout_without_alloc` produced it at erased.rs:1802 from the same
1824    // `dest.dims()` and `dest.strides()` that `dest` was rebuilt with. Bounds and aliasing hold
1825    // throughout the replay: each descriptor is bounded as argued where it is built above, `dest`
1826    // is an exclusive reborrow, and the public entry rejected input/output overlap before
1827    // converting the inputs (erased.rs:89).
1828    unsafe {
1829        strided_basic::execution::map_raw_into_validated::<D, A, Identity>(
1830            &mut dest, &input, map, validated, exec,
1831        )
1832    }
1833}
1834
1835fn execute_one_shot_zip<T: OneShotScalar>(
1836    op: ErasedZipOp,
1837    dest: &mut ErasedRawStridedMut<'_>,
1838    lhs: &ErasedRawStridedRef<'_>,
1839    rhs: &ErasedRawStridedRef<'_>,
1840    exec: Exec<'_>,
1841) -> Result<()> {
1842    if !T::supports_zip(op) {
1843        return Err(StridedError::UnsupportedOp {
1844            op: op.label(),
1845            dtype: T::one_shot_dtype_label(),
1846        });
1847    }
1848    let validated = strided_basic::execution::validate_destination_layout_without_alloc(
1849        dest.dims(),
1850        dest.strides(),
1851    )?;
1852    strided_basic::execution::ensure_same_shape(dest.dims(), lhs.dims())?;
1853    strided_basic::execution::ensure_same_shape(dest.dims(), rhs.dims())?;
1854    if dest.dims().contains(&0) {
1855        return Ok(());
1856    }
1857
1858    let lhs = erased_raw_ref::<T>(lhs)?;
1859    let rhs = erased_raw_ref::<T>(rhs)?;
1860    if matches!(op, ErasedZipOp::Divide | ErasedZipOp::Remainder)
1861        && T::INTEGER
1862        && raw_any(&rhs, T::is_zero)?
1863    {
1864        return Err(StridedError::IntegerDivisionByZero { op: op.label() });
1865    }
1866    let dest_dims = dest.dims();
1867    let dest_strides = dest.strides();
1868    let dest_offset = dest.offset();
1869    let dest_data = dest.data_as_mut::<T>()?;
1870    // SAFETY: as for `dest` in `execute_one_shot_map` (erased.rs:1747): `dest`'s construction ran
1871    // `validate_bounds` over these dims, strides and offset, and `data_as_mut` hands out the only
1872    // access to its storage.
1873    let mut dest =
1874        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
1875    // The op is matched once here so each arm replays a loop whose closure
1876    // names a constant op; see `execute_one_shot_map`.
1877    macro_rules! replay {
1878        ($op:ident) => {
1879            // SAFETY: `zip_map2_raw_into_validated` (strided-basic/src/execution.rs:413) requires
1880            // three things. Every input shape matches the destination: `ensure_same_shape`
1881            // checked it at erased.rs:1852 and erased.rs:1853. `validated` belongs to this
1882            // destination's geometry: `validate_destination_layout_without_alloc` produced it at
1883            // erased.rs:1848 from the same `dest.dims()` and `dest.strides()` that `dest` was
1884            // rebuilt with. Bounds and aliasing hold throughout the replay: each descriptor is
1885            // bounded as argued where it is built above, `dest` is an exclusive reborrow, and the
1886            // public entry rejected input/output overlap before converting the inputs
1887            // (erased.rs:152, erased.rs:153).
1888            unsafe {
1889                strided_basic::execution::zip_map2_raw_into_validated::<
1890                    T,
1891                    T,
1892                    T,
1893                    Identity,
1894                    Identity,
1895                >(
1896                    &mut dest,
1897                    &lhs,
1898                    &rhs,
1899                    |lhs, rhs| T::zip(ErasedZipOp::$op, lhs, rhs),
1900                    validated, exec,
1901)
1902            }
1903        };
1904    }
1905    match op {
1906        ErasedZipOp::Add => replay!(Add),
1907        ErasedZipOp::Subtract => replay!(Subtract),
1908        ErasedZipOp::Multiply => replay!(Multiply),
1909        ErasedZipOp::Divide => replay!(Divide),
1910        ErasedZipOp::Remainder => replay!(Remainder),
1911        ErasedZipOp::Maximum => replay!(Maximum),
1912        ErasedZipOp::Minimum => replay!(Minimum),
1913    }
1914}
1915
1916fn validate_no_overlap(
1917    dest: &ErasedRawStridedMut<'_>,
1918    input: &ErasedRawStridedPtr<'_>,
1919    input_index: usize,
1920) -> Result<()> {
1921    if input.overlaps_mut(dest)? {
1922        Err(StridedError::OverlappingInputOutput { input: input_index })
1923    } else {
1924        Ok(())
1925    }
1926}
1927
1928trait OneShotScalar: Copy + Send + Sync + KernelStorageElement + 'static {
1929    const INTEGER: bool = false;
1930    fn is_zero(_value: Self) -> bool {
1931        false
1932    }
1933    fn one_shot_dtype_label() -> &'static str;
1934    fn supports_map(op: ErasedMapOp) -> bool;
1935    fn supports_zip(op: ErasedZipOp) -> bool;
1936    fn map(op: ErasedMapOp, value: Self) -> Self;
1937    fn zip(op: ErasedZipOp, lhs: Self, rhs: Self) -> Self;
1938    /// `minimum(hi, maximum(lo, x))`, the composition clamp promises.
1939    #[inline(always)]
1940    fn clamp(x: Self, lo: Self, hi: Self) -> Self {
1941        let raised = Self::zip(ErasedZipOp::Maximum, lo, x);
1942        Self::zip(ErasedZipOp::Minimum, hi, raised)
1943    }
1944}
1945
1946macro_rules! impl_real_one_shot_scalar {
1947    ($ty:ty, $label:literal) => {
1948        impl OneShotScalar for $ty {
1949            fn one_shot_dtype_label() -> &'static str {
1950                $label
1951            }
1952
1953            fn supports_map(_op: ErasedMapOp) -> bool {
1954                true
1955            }
1956
1957            fn supports_zip(_op: ErasedZipOp) -> bool {
1958                true
1959            }
1960
1961            #[inline(always)]
1962            fn map(op: ErasedMapOp, value: Self) -> Self {
1963                match op {
1964                    ErasedMapOp::Negate => -value,
1965                    ErasedMapOp::Conj => value,
1966                    ErasedMapOp::Abs => value.abs(),
1967                    ErasedMapOp::Sign => {
1968                        if value == 0.0 {
1969                            0.0
1970                        } else {
1971                            value.signum()
1972                        }
1973                    }
1974                }
1975            }
1976
1977            #[inline(always)]
1978            fn zip(op: ErasedZipOp, lhs: Self, rhs: Self) -> Self {
1979                match op {
1980                    ErasedZipOp::Add => lhs + rhs,
1981                    ErasedZipOp::Subtract => lhs - rhs,
1982                    ErasedZipOp::Multiply => lhs * rhs,
1983                    ErasedZipOp::Divide => lhs / rhs,
1984                    ErasedZipOp::Remainder => lhs % rhs,
1985                    // Shared NaN-propagating selects, so the fused path
1986                    // cannot drift from the ordinary binary kernel.
1987                    ErasedZipOp::Maximum => strided_basic::nan_propagating_maximum(lhs, rhs),
1988                    ErasedZipOp::Minimum => strided_basic::nan_propagating_minimum(lhs, rhs),
1989                }
1990            }
1991
1992            // Same result as the default composition: any NaN operand gives
1993            // the canonical NaN and ties return the bound. Testing NaN once
1994            // over the three operands, instead of once per step, keeps the
1995            // loop at memory bandwidth.
1996            #[inline(always)]
1997            fn clamp(x: Self, lo: Self, hi: Self) -> Self {
1998                let raised = if lo >= x { lo } else { x };
1999                let lowered = if hi <= raised { hi } else { raised };
2000                if x.is_nan() | lo.is_nan() | hi.is_nan() {
2001                    <$ty>::NAN
2002                } else {
2003                    lowered
2004                }
2005            }
2006        }
2007    };
2008}
2009
2010macro_rules! impl_integer_one_shot_scalar {
2011    ($ty:ty, $label:literal) => {
2012        impl OneShotScalar for $ty {
2013            const INTEGER: bool = true;
2014
2015            fn is_zero(value: Self) -> bool {
2016                value == 0
2017            }
2018            fn one_shot_dtype_label() -> &'static str {
2019                $label
2020            }
2021
2022            fn supports_map(_op: ErasedMapOp) -> bool {
2023                true
2024            }
2025
2026            fn supports_zip(_op: ErasedZipOp) -> bool {
2027                true
2028            }
2029
2030            #[inline(always)]
2031            fn map(op: ErasedMapOp, value: Self) -> Self {
2032                match op {
2033                    ErasedMapOp::Negate => value.wrapping_neg(),
2034                    ErasedMapOp::Conj => value,
2035                    ErasedMapOp::Abs => value.wrapping_abs(),
2036                    ErasedMapOp::Sign => value.signum(),
2037                }
2038            }
2039
2040            #[inline(always)]
2041            fn zip(op: ErasedZipOp, lhs: Self, rhs: Self) -> Self {
2042                match op {
2043                    ErasedZipOp::Add => lhs.wrapping_add(rhs),
2044                    ErasedZipOp::Subtract => lhs.wrapping_sub(rhs),
2045                    ErasedZipOp::Multiply => lhs.wrapping_mul(rhs),
2046                    ErasedZipOp::Maximum => lhs.max(rhs),
2047                    ErasedZipOp::Minimum => lhs.min(rhs),
2048                    ErasedZipOp::Divide => lhs.wrapping_div(rhs),
2049                    ErasedZipOp::Remainder => lhs.wrapping_rem(rhs),
2050                }
2051            }
2052        }
2053    };
2054}
2055
2056macro_rules! impl_complex_one_shot_scalar {
2057    ($ty:ty, $label:literal, $div:path) => {
2058        impl OneShotScalar for $ty {
2059            fn one_shot_dtype_label() -> &'static str {
2060                $label
2061            }
2062
2063            fn supports_map(_op: ErasedMapOp) -> bool {
2064                true
2065            }
2066
2067            fn supports_zip(op: ErasedZipOp) -> bool {
2068                !matches!(
2069                    op,
2070                    ErasedZipOp::Remainder | ErasedZipOp::Maximum | ErasedZipOp::Minimum
2071                )
2072            }
2073
2074            #[inline(always)]
2075            fn map(op: ErasedMapOp, value: Self) -> Self {
2076                match op {
2077                    ErasedMapOp::Negate => -value,
2078                    ErasedMapOp::Conj => value.conj(),
2079                    ErasedMapOp::Abs => Self::new(value.norm(), 0.0),
2080                    ErasedMapOp::Sign => {
2081                        if value.re == 0.0 && value.im == 0.0 {
2082                            Self::new(0.0, 0.0)
2083                        } else {
2084                            // Divide the components by the real modulus: complex
2085                            // division squares the divisor's components, which
2086                            // underflows for tiny magnitudes such as 1e-200 in
2087                            // f64 and yields NaN instead of the unit phase.
2088                            let norm = value.norm();
2089                            Self::new(value.re / norm, value.im / norm)
2090                        }
2091                    }
2092                }
2093            }
2094
2095            #[inline(always)]
2096            fn zip(op: ErasedZipOp, lhs: Self, rhs: Self) -> Self {
2097                match op {
2098                    ErasedZipOp::Add => lhs + rhs,
2099                    ErasedZipOp::Subtract => lhs - rhs,
2100                    ErasedZipOp::Multiply => lhs * rhs,
2101                    ErasedZipOp::Divide => $div(lhs, rhs),
2102                    ErasedZipOp::Remainder | ErasedZipOp::Maximum | ErasedZipOp::Minimum => {
2103                        unreachable!("unsupported complex one-shot op")
2104                    }
2105                }
2106            }
2107        }
2108    };
2109}
2110
2111impl_real_one_shot_scalar!(f32, "f32");
2112
2113impl_real_one_shot_scalar!(f64, "f64");
2114
2115impl_integer_one_shot_scalar!(i32, "i32");
2116
2117impl_integer_one_shot_scalar!(i64, "i64");
2118
2119impl_complex_one_shot_scalar!(Complex32, "c32", strided_basic::robust_complex_divide_f32);
2120
2121impl_complex_one_shot_scalar!(Complex64, "c64", strided_basic::robust_complex_divide_f64);
2122
2123impl OneShotScalar for bool {
2124    fn one_shot_dtype_label() -> &'static str {
2125        "bool"
2126    }
2127
2128    fn supports_map(op: ErasedMapOp) -> bool {
2129        matches!(op, ErasedMapOp::Conj)
2130    }
2131
2132    fn supports_zip(_op: ErasedZipOp) -> bool {
2133        false
2134    }
2135
2136    fn map(op: ErasedMapOp, value: Self) -> Self {
2137        match op {
2138            ErasedMapOp::Conj => value,
2139            _ => unreachable!("unsupported bool one-shot op"),
2140        }
2141    }
2142
2143    fn zip(_op: ErasedZipOp, _lhs: Self, _rhs: Self) -> Self {
2144        unreachable!("unsupported bool one-shot op")
2145    }
2146}
2147
2148fn erased_raw_ref<'a, T: KernelStorageElement>(
2149    src: &'a ErasedRawStridedRef<'a>,
2150) -> Result<RawStridedRef<'a, T>> {
2151    let data = src.data_as::<T>()?;
2152    // SAFETY: `RawStridedRef::new_unchecked` (strided-view/src/raw.rs:996) needs every index
2153    // reachable from `src.offset()` through `src.dims()`/`src.strides()` inside `data`. When
2154    // `src` was built (`from_slice`, strided-view/src/raw.rs:420, or `from_raw_parts`,
2155    // strided-view/src/raw.rs:473, which `try_as_ref_after_no_overlap` also uses),
2156    // `validate_bounds` (strided-view/src/view.rs:187) checked exactly these dims, strides and
2157    // offset against its element count, `byte_len / size_of::<T>()`. `data_as::<T>`
2158    // (strided-view/src/raw.rs:503) checked that the descriptor's dtype is `T` and returns
2159    // exactly that many elements.
2160    Ok(unsafe { RawStridedRef::new_unchecked(data, src.dims(), src.strides(), src.offset()) })
2161}
2162
2163fn map_output_dtype(dtype: KernelDType, op: ErasedMapOp) -> Result<KernelDType> {
2164    match (dtype, op) {
2165        (KernelDType::C32, ErasedMapOp::Abs) => Ok(KernelDType::F32),
2166        (KernelDType::C64, ErasedMapOp::Abs) => Ok(KernelDType::F64),
2167        (KernelDType::Bool, ErasedMapOp::Conj) => Ok(KernelDType::Bool),
2168        (KernelDType::Bool, _) => Err(StridedError::UnsupportedOp {
2169            op: op.label(),
2170            dtype: dtype.label(),
2171        }),
2172        _ => Ok(dtype),
2173    }
2174}
2175
2176fn raw_any<T: Copy>(
2177    src: &RawStridedRef<'_, T>,
2178    predicate: impl Fn(T) -> bool + Copy,
2179) -> Result<bool> {
2180    let total = src
2181        .dims()
2182        .iter()
2183        .try_fold(1usize, |total, &dim| total.checked_mul(dim))
2184        .ok_or(StridedError::OffsetOverflow)?;
2185    if total == 0 {
2186        return Ok(false);
2187    }
2188
2189    let rank = src.dims().len();
2190    if rank <= RAW_FUSED_RANK_LIMIT {
2191        let mut coordinates = [0usize; RAW_FUSED_RANK_LIMIT];
2192        let mut resets = [0isize; RAW_FUSED_RANK_LIMIT];
2193        raw_any_odometer(
2194            src,
2195            predicate,
2196            &mut coordinates[..rank],
2197            &mut resets[..rank],
2198        )
2199    } else {
2200        // Ranks above the fused limit keep the same incremental-offset
2201        // odometer; only the cursor storage moves to the heap.
2202        let mut coordinates = vec![0usize; rank];
2203        let mut resets = vec![0isize; rank];
2204        raw_any_odometer(src, predicate, &mut coordinates, &mut resets)
2205    }
2206}
2207
2208fn raw_any_odometer<T: Copy>(
2209    src: &RawStridedRef<'_, T>,
2210    predicate: impl Fn(T) -> bool + Copy,
2211    coordinates: &mut [usize],
2212    resets: &mut [isize],
2213) -> Result<bool> {
2214    let dims = src.dims();
2215    let strides = src.strides();
2216    // INVARIANT: the caller rejected empty extents, so every `dim - 1` is valid.
2217    // (`raw_any` returns early for a zero element count at erased.rs:2185.)
2218    for axis in 0..dims.len() {
2219        let last = isize::try_from(dims[axis] - 1).map_err(|_| StridedError::OffsetOverflow)?;
2220        resets[axis] = strides[axis]
2221            .checked_mul(last)
2222            .and_then(isize::checked_neg)
2223            .ok_or(StridedError::OffsetOverflow)?;
2224    }
2225
2226    let mut offset = src.offset();
2227    loop {
2228        // SAFETY: every `RawStridedRef` keeps its reachable offsets inside `data`:
2229        // `RawStridedRef::new` checks them and `new_unchecked` (strided-view/src/raw.rs:996)
2230        // makes them the caller's contract. Here `src` comes from `erased_raw_ref` (the only
2231        // caller, `raw_any`, runs at erased.rs:1862), whose proof is at erased.rs:2148. The
2232        // odometer keeps `coordinates[axis] < dims[axis]` and moves `offset` by whole strides, so
2233        // `offset` is always `src.offset()` plus the offset of a reachable index.
2234        if predicate(unsafe { *src.data().as_ptr().offset(offset) }) {
2235            return Ok(true);
2236        }
2237
2238        let mut axis = 0;
2239        while axis < dims.len() && coordinates[axis] == dims[axis] - 1 {
2240            axis += 1;
2241        }
2242        if axis == dims.len() {
2243            return Ok(false);
2244        }
2245        for reset_axis in 0..axis {
2246            coordinates[reset_axis] = 0;
2247            offset = offset
2248                .checked_add(resets[reset_axis])
2249                .ok_or(StridedError::OffsetOverflow)?;
2250        }
2251        coordinates[axis] = coordinates[axis]
2252            .checked_add(1)
2253            .ok_or(StridedError::OffsetOverflow)?;
2254        offset = offset
2255            .checked_add(strides[axis])
2256            .ok_or(StridedError::OffsetOverflow)?;
2257    }
2258}
2259
2260fn check_index_dtype(dtype: KernelDType) -> Result<()> {
2261    match dtype {
2262        KernelDType::I32 | KernelDType::I64 => Ok(()),
2263        _ => Err(StridedError::UnsupportedDType {
2264            dtype: dtype.label(),
2265        }),
2266    }
2267}
2268
2269fn check_gather_value_dtype(dtype: KernelDType) -> Result<()> {
2270    match dtype {
2271        KernelDType::F32
2272        | KernelDType::F64
2273        | KernelDType::I32
2274        | KernelDType::I64
2275        | KernelDType::Bool
2276        | KernelDType::C32
2277        | KernelDType::C64 => Ok(()),
2278        _ => Err(StridedError::UnsupportedDType {
2279            dtype: dtype.label(),
2280        }),
2281    }
2282}
2283
2284fn check_scatter_value_dtype(dtype: KernelDType) -> Result<()> {
2285    match dtype {
2286        KernelDType::F32
2287        | KernelDType::F64
2288        | KernelDType::I32
2289        | KernelDType::I64
2290        | KernelDType::C32
2291        | KernelDType::C64 => Ok(()),
2292        _ => Err(StridedError::UnsupportedDType {
2293            dtype: dtype.label(),
2294        }),
2295    }
2296}
2297
2298fn validate_scalar_bytes(dtype: KernelDType, bytes: &[u8]) -> Result<()> {
2299    let element_size = dtype.size_of();
2300    if bytes.len() != element_size {
2301        return Err(StridedError::ByteLengthMismatch {
2302            dtype: dtype.label(),
2303            byte_len: bytes.len(),
2304            element_size,
2305        });
2306    }
2307    if dtype.requires_valid_byte_values() {
2308        if let Some(&value) = bytes.iter().find(|&&value| value > 1) {
2309            return Err(StridedError::InvalidBoolByte { value });
2310        }
2311    }
2312    Ok(())
2313}
2314
2315fn execute_slice<T>(
2316    plan: &SlicePlan,
2317    dest: &mut ErasedRawStridedMut<'_>,
2318    operand: &ErasedRawStridedRef<'_>,
2319    exec: Exec<'_>,
2320) -> Result<()>
2321where
2322    T: Copy + Send + Sync + KernelStorageElement,
2323{
2324    let operand_data = operand.data_as::<T>()?;
2325    let dest_dims = dest.dims();
2326    let dest_strides = dest.strides();
2327    let dest_offset = dest.offset();
2328    let dest_data = dest.data_as_mut::<T>()?;
2329    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
2330    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2331    // count.
2332    let operand_ref = unsafe {
2333        RawStridedRef::new_unchecked(
2334            operand_data,
2335            operand.dims(),
2336            operand.strides(),
2337            operand.offset(),
2338        )
2339    };
2340    // SAFETY: as for `dest` in `execute_one_shot_map` (erased.rs:1747): `dest`'s construction ran
2341    // `validate_bounds` over these dims, strides and offset, and `data_as_mut` hands out the only
2342    // access to its storage.
2343    let mut dest_ref =
2344        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
2345    plan.execute(&mut dest_ref, &operand_ref, exec)
2346}
2347
2348fn execute_gather_uninit_dispatch<T>(
2349    plan: &GatherPlan,
2350    index_dtype: KernelDType,
2351    dest: &mut ErasedRawStridedUninitMut<'_>,
2352    operand: &ErasedRawStridedRef<'_>,
2353    start_indices: &ErasedRawStridedRef<'_>,
2354    exec: Exec<'_>,
2355) -> Result<()>
2356where
2357    T: Copy + Send + Sync + KernelStorageElement,
2358{
2359    match index_dtype {
2360        KernelDType::I32 => {
2361            execute_gather_uninit::<T, i32>(plan, index_dtype, dest, operand, start_indices, exec)
2362        }
2363        KernelDType::I64 => {
2364            execute_gather_uninit::<T, i64>(plan, index_dtype, dest, operand, start_indices, exec)
2365        }
2366        _ => Err(StridedError::UnsupportedDType {
2367            dtype: index_dtype.label(),
2368        }),
2369    }
2370}
2371
2372fn execute_gather_uninit<T, I>(
2373    plan: &GatherPlan,
2374    _index_dtype: KernelDType,
2375    dest: &mut ErasedRawStridedUninitMut<'_>,
2376    operand: &ErasedRawStridedRef<'_>,
2377    start_indices: &ErasedRawStridedRef<'_>,
2378    exec: Exec<'_>,
2379) -> Result<()>
2380where
2381    T: Copy + Send + Sync + KernelStorageElement,
2382    I: GatherIndex + KernelStorageElement,
2383{
2384    let operand_data = operand.data_as::<T>()?;
2385    let index_data = start_indices.data_as::<I>()?;
2386    let dest_dims = dest.dims();
2387    let dest_strides = dest.strides();
2388    let dest_offset = dest.offset();
2389    let dest_data = dest.data_as_uninit_mut::<T>()?;
2390    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
2391    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2392    // count.
2393    let operand_ref = unsafe {
2394        RawStridedRef::new_unchecked(
2395            operand_data,
2396            operand.dims(),
2397            operand.strides(),
2398            operand.offset(),
2399        )
2400    };
2401    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `start_indices` checked these dims,
2402    // strides and offset with `validate_bounds` when it was built, and `data_as` returned its
2403    // whole element count.
2404    let index_ref = unsafe {
2405        RawStridedRef::new_unchecked(
2406            index_data,
2407            start_indices.dims(),
2408            start_indices.strides(),
2409            start_indices.offset(),
2410        )
2411    };
2412    // SAFETY: `RawStridedMut::new_unchecked` (strided-view/src/raw.rs:1115) needs every index
2413    // reachable from `dest_offset` through `dest_dims`/`dest_strides` inside `dest_data`, and no
2414    // alias that breaks mutable access. When `dest` was built (`from_uninit_slice`,
2415    // strided-view/src/raw.rs:794, or `from_raw_parts`, strided-view/src/raw.rs:850),
2416    // `validate_bounds` (strided-view/src/view.rs:187) checked exactly these dims, strides and
2417    // offset against its slot count, `byte_len / size_of::<T>()`, which is the length
2418    // `data_as_uninit_mut` (strided-view/src/raw.rs:882) returns after checking the dtype.
2419    // `data_as_uninit_mut` reborrows the descriptor through `&mut self`, so `dest_data` is the
2420    // only access to those `MaybeUninit<T>` slots while `dest` lives.
2421    let mut dest_ref =
2422        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
2423    // SAFETY: `gather_into_uninit` (strided-basic/src/execution.rs:553) requires overlap rejected
2424    // before the input references existed, live descriptor contracts, and no initialized
2425    // reference to the output. This function is reached only from
2426    // `ErasedGatherPlan::execute_uninit` (through its dispatch helper), which rejected every
2427    // input/output overlap before converting the inputs (last check at erased.rs:845). The
2428    // descriptors stay borrowed for the call, and `dest_data` is `&mut [MaybeUninit<T>]`, so no
2429    // initialized reference to the output is formed.
2430    unsafe {
2431        strided_basic::execution::gather_into_uninit(
2432            plan,
2433            &mut dest_ref,
2434            &operand_ref,
2435            &index_ref,
2436            exec,
2437        )
2438    }
2439}
2440
2441fn execute_dynamic_slice_uninit_dispatch<T>(
2442    plan: &DynamicSlicePlan,
2443    index_dtype: KernelDType,
2444    dest: &mut ErasedRawStridedUninitMut<'_>,
2445    operand: &ErasedRawStridedRef<'_>,
2446    starts: &ErasedRawStridedRef<'_>,
2447    exec: Exec<'_>,
2448) -> Result<()>
2449where
2450    T: Copy + Send + Sync + KernelStorageElement,
2451{
2452    match index_dtype {
2453        KernelDType::I32 => {
2454            execute_dynamic_slice_uninit::<T, i32>(plan, dest, operand, starts, exec)
2455        }
2456        KernelDType::I64 => {
2457            execute_dynamic_slice_uninit::<T, i64>(plan, dest, operand, starts, exec)
2458        }
2459        _ => Err(StridedError::UnsupportedDType {
2460            dtype: index_dtype.label(),
2461        }),
2462    }
2463}
2464
2465fn execute_dynamic_slice_uninit<T, I>(
2466    plan: &DynamicSlicePlan,
2467    dest: &mut ErasedRawStridedUninitMut<'_>,
2468    operand: &ErasedRawStridedRef<'_>,
2469    starts: &ErasedRawStridedRef<'_>,
2470    exec: Exec<'_>,
2471) -> Result<()>
2472where
2473    T: Copy + Send + Sync + KernelStorageElement,
2474    I: GatherIndex + KernelStorageElement,
2475{
2476    let operand_data = operand.data_as::<T>()?;
2477    let starts_data = starts.data_as::<I>()?;
2478    let dest_dims = dest.dims();
2479    let dest_strides = dest.strides();
2480    let dest_offset = dest.offset();
2481    let dest_data = dest.data_as_uninit_mut::<T>()?;
2482    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
2483    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2484    // count.
2485    let operand_ref = unsafe {
2486        RawStridedRef::new_unchecked(
2487            operand_data,
2488            operand.dims(),
2489            operand.strides(),
2490            operand.offset(),
2491        )
2492    };
2493    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `starts` checked these dims, strides and
2494    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2495    // count.
2496    let starts_ref = unsafe {
2497        RawStridedRef::new_unchecked(
2498            starts_data,
2499            starts.dims(),
2500            starts.strides(),
2501            starts.offset(),
2502        )
2503    };
2504    // SAFETY: as for `dest` in `execute_gather_uninit` (erased.rs:2412): `dest`'s construction
2505    // ran `validate_bounds` over these dims, strides and offset, and `data_as_uninit_mut` hands
2506    // out the only access to its slots.
2507    let mut dest_ref =
2508        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
2509    // SAFETY: `dynamic_slice_into_uninit` (strided-basic/src/execution.rs:603) requires overlap
2510    // rejected before the input references existed, live descriptor contracts, and no initialized
2511    // reference to the output. This function is reached only from
2512    // `ErasedDynamicSlicePlan::execute_uninit` (through its dispatch helper), which rejected
2513    // every input/output overlap before converting the inputs (last check at erased.rs:1099). The
2514    // descriptors stay borrowed for the call, and `dest_data` is `&mut [MaybeUninit<T>]`, so no
2515    // initialized reference to the output is formed.
2516    unsafe {
2517        strided_basic::execution::dynamic_slice_into_uninit(
2518            plan,
2519            &mut dest_ref,
2520            &operand_ref,
2521            &starts_ref,
2522            exec,
2523        )
2524    }
2525}
2526
2527fn execute_dynamic_update_uninit_dispatch<T>(
2528    plan: &DynamicUpdateSlicePlan,
2529    index_dtype: KernelDType,
2530    dest: &mut ErasedRawStridedUninitMut<'_>,
2531    operand: &ErasedRawStridedRef<'_>,
2532    update: &ErasedRawStridedRef<'_>,
2533    starts: &ErasedRawStridedRef<'_>,
2534    exec: Exec<'_>,
2535) -> Result<()>
2536where
2537    T: Copy + Send + Sync + KernelStorageElement,
2538{
2539    match index_dtype {
2540        KernelDType::I32 => {
2541            execute_dynamic_update_uninit::<T, i32>(plan, dest, operand, update, starts, exec)
2542        }
2543        KernelDType::I64 => {
2544            execute_dynamic_update_uninit::<T, i64>(plan, dest, operand, update, starts, exec)
2545        }
2546        _ => Err(StridedError::UnsupportedDType {
2547            dtype: index_dtype.label(),
2548        }),
2549    }
2550}
2551
2552fn execute_dynamic_update_uninit<T, I>(
2553    plan: &DynamicUpdateSlicePlan,
2554    dest: &mut ErasedRawStridedUninitMut<'_>,
2555    operand: &ErasedRawStridedRef<'_>,
2556    update: &ErasedRawStridedRef<'_>,
2557    starts: &ErasedRawStridedRef<'_>,
2558    exec: Exec<'_>,
2559) -> Result<()>
2560where
2561    T: Copy + Send + Sync + KernelStorageElement,
2562    I: GatherIndex + KernelStorageElement,
2563{
2564    let operand_data = operand.data_as::<T>()?;
2565    let update_data = update.data_as::<T>()?;
2566    let starts_data = starts.data_as::<I>()?;
2567    let dest_dims = dest.dims();
2568    let dest_strides = dest.strides();
2569    let dest_offset = dest.offset();
2570    let dest_data = dest.data_as_uninit_mut::<T>()?;
2571    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
2572    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2573    // count.
2574    let operand_ref = unsafe {
2575        RawStridedRef::new_unchecked(
2576            operand_data,
2577            operand.dims(),
2578            operand.strides(),
2579            operand.offset(),
2580        )
2581    };
2582    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `update` checked these dims, strides and
2583    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2584    // count.
2585    let update_ref = unsafe {
2586        RawStridedRef::new_unchecked(
2587            update_data,
2588            update.dims(),
2589            update.strides(),
2590            update.offset(),
2591        )
2592    };
2593    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `starts` checked these dims, strides and
2594    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2595    // count.
2596    let starts_ref = unsafe {
2597        RawStridedRef::new_unchecked(
2598            starts_data,
2599            starts.dims(),
2600            starts.strides(),
2601            starts.offset(),
2602        )
2603    };
2604    // SAFETY: as for `dest` in `execute_gather_uninit` (erased.rs:2412): `dest`'s construction
2605    // ran `validate_bounds` over these dims, strides and offset, and `data_as_uninit_mut` hands
2606    // out the only access to its slots.
2607    let mut dest_ref =
2608        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
2609    // SAFETY: `dynamic_update_into_uninit` (strided-basic/src/execution.rs:651) requires overlap
2610    // rejected before the input references existed, live descriptor contracts, and no initialized
2611    // reference to the output. This function is reached only from
2612    // `ErasedDynamicUpdateSlicePlan::execute_uninit` (through its dispatch helper), which
2613    // rejected every input/output overlap before converting the inputs (last check at
2614    // erased.rs:1366). The descriptors stay borrowed for the call, and `dest_data` is `&mut
2615    // [MaybeUninit<T>]`, so no initialized reference to the output is formed.
2616    unsafe {
2617        strided_basic::execution::dynamic_update_into_uninit(
2618            plan,
2619            &mut dest_ref,
2620            &operand_ref,
2621            &update_ref,
2622            &starts_ref,
2623            exec,
2624        )
2625    }
2626}
2627
2628// Dtype plus the operand, index, update and destination layouts: the dispatch key. The
2629// combine is `ScatterScalar::wrapping_add`, the one `ScatterPlan::execute` uses.
2630#[allow(clippy::too_many_arguments)]
2631fn execute_scatter_uninit_dispatch<T>(
2632    plan: &ScatterPlan,
2633    index_dtype: KernelDType,
2634    dest: &mut ErasedRawStridedUninitMut<'_>,
2635    operand: &ErasedRawStridedRef<'_>,
2636    scatter_indices: &ErasedRawStridedRef<'_>,
2637    updates: &ErasedRawStridedRef<'_>,
2638    exec: Exec<'_>,
2639) -> Result<()>
2640where
2641    T: ScatterScalar + KernelStorageElement,
2642{
2643    match index_dtype {
2644        KernelDType::I32 => {
2645            execute_scatter_uninit::<T, i32>(plan, dest, operand, scatter_indices, updates, exec)
2646        }
2647        KernelDType::I64 => {
2648            execute_scatter_uninit::<T, i64>(plan, dest, operand, scatter_indices, updates, exec)
2649        }
2650        _ => Err(StridedError::UnsupportedDType {
2651            dtype: index_dtype.label(),
2652        }),
2653    }
2654}
2655
2656fn execute_scatter_uninit<T, I>(
2657    plan: &ScatterPlan,
2658    dest: &mut ErasedRawStridedUninitMut<'_>,
2659    operand: &ErasedRawStridedRef<'_>,
2660    scatter_indices: &ErasedRawStridedRef<'_>,
2661    updates: &ErasedRawStridedRef<'_>,
2662    exec: Exec<'_>,
2663) -> Result<()>
2664where
2665    T: ScatterScalar + KernelStorageElement,
2666    I: GatherIndex + KernelStorageElement,
2667{
2668    let indices = scatter_indices;
2669    let operand_data = operand.data_as::<T>()?;
2670    let index_data = indices.data_as::<I>()?;
2671    let update_data = updates.data_as::<T>()?;
2672    let dest_dims = dest.dims();
2673    let dest_strides = dest.strides();
2674    let dest_offset = dest.offset();
2675    let dest_data = dest.data_as_uninit_mut::<T>()?;
2676    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
2677    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2678    // count.
2679    let operand_ref = unsafe {
2680        RawStridedRef::new_unchecked(
2681            operand_data,
2682            operand.dims(),
2683            operand.strides(),
2684            operand.offset(),
2685        )
2686    };
2687    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `scatter_indices` checked these dims,
2688    // strides and offset with `validate_bounds` when it was built, and `data_as` returned its
2689    // whole element count.
2690    let index_ref = unsafe {
2691        RawStridedRef::new_unchecked(
2692            index_data,
2693            indices.dims(),
2694            indices.strides(),
2695            indices.offset(),
2696        )
2697    };
2698    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `updates` checked these dims, strides and
2699    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2700    // count.
2701    let update_ref = unsafe {
2702        RawStridedRef::new_unchecked(
2703            update_data,
2704            updates.dims(),
2705            updates.strides(),
2706            updates.offset(),
2707        )
2708    };
2709    // SAFETY: as for `dest` in `execute_gather_uninit` (erased.rs:2412): `dest`'s construction
2710    // ran `validate_bounds` over these dims, strides and offset, and `data_as_uninit_mut` hands
2711    // out the only access to its slots.
2712    let mut dest_ref =
2713        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
2714    // SAFETY: `scatter_into_uninit` (strided-basic/src/execution.rs:705) requires overlap
2715    // rejected before the input references existed, live descriptor contracts, and no initialized
2716    // reference to the output. This function is reached only from
2717    // `ErasedScatterPlan::execute_uninit` (through its dispatch helper), which rejected every
2718    // input/output overlap before converting the inputs (last check at erased.rs:1640). The
2719    // descriptors stay borrowed for the call, and `dest_data` is `&mut [MaybeUninit<T>]`, so no
2720    // initialized reference to the output is formed.
2721    unsafe {
2722        strided_basic::execution::scatter_into_uninit(
2723            plan,
2724            &mut dest_ref,
2725            &operand_ref,
2726            &index_ref,
2727            &update_ref,
2728            <T as ScatterScalar>::wrapping_add,
2729            exec,
2730        )
2731    }
2732}
2733
2734fn execute_slice_uninit<T>(
2735    plan: &SlicePlan,
2736    dest: &mut ErasedRawStridedUninitMut<'_>,
2737    operand: &ErasedRawStridedRef<'_>,
2738    exec: Exec<'_>,
2739) -> Result<()>
2740where
2741    T: Copy + Send + Sync + KernelStorageElement,
2742{
2743    let operand_data = operand.data_as::<T>()?;
2744    let dest_dims = dest.dims();
2745    let dest_strides = dest.strides();
2746    let dest_offset = dest.offset();
2747    let dest_data = dest.data_as_uninit_mut::<T>()?;
2748    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
2749    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2750    // count.
2751    let operand_ref = unsafe {
2752        RawStridedRef::new_unchecked(
2753            operand_data,
2754            operand.dims(),
2755            operand.strides(),
2756            operand.offset(),
2757        )
2758    };
2759    // SAFETY: as for `dest` in `execute_gather_uninit` (erased.rs:2412): `dest`'s construction
2760    // ran `validate_bounds` over these dims, strides and offset, and `data_as_uninit_mut` hands
2761    // out the only access to its slots.
2762    let mut dest_ref =
2763        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
2764    plan.execute_uninit(&mut dest_ref, &operand_ref, exec)
2765}
2766
2767fn execute_reverse<T>(
2768    plan: &ReversePlan,
2769    dest: &mut ErasedRawStridedMut<'_>,
2770    operand: &ErasedRawStridedRef<'_>,
2771    exec: Exec<'_>,
2772) -> Result<()>
2773where
2774    T: Copy + Send + Sync + KernelStorageElement,
2775{
2776    let operand_data = operand.data_as::<T>()?;
2777    let dest_dims = dest.dims();
2778    let dest_strides = dest.strides();
2779    let dest_offset = dest.offset();
2780    let dest_data = dest.data_as_mut::<T>()?;
2781    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
2782    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2783    // count.
2784    let operand_ref = unsafe {
2785        RawStridedRef::new_unchecked(
2786            operand_data,
2787            operand.dims(),
2788            operand.strides(),
2789            operand.offset(),
2790        )
2791    };
2792    // SAFETY: as for `dest` in `execute_one_shot_map` (erased.rs:1747): `dest`'s construction ran
2793    // `validate_bounds` over these dims, strides and offset, and `data_as_mut` hands out the only
2794    // access to its storage.
2795    let mut dest_ref =
2796        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
2797    plan.execute(&mut dest_ref, &operand_ref, exec)
2798}
2799
2800fn execute_reverse_uninit<T>(
2801    plan: &ReversePlan,
2802    dest: &mut ErasedRawStridedUninitMut<'_>,
2803    operand: &ErasedRawStridedRef<'_>,
2804    exec: Exec<'_>,
2805) -> Result<()>
2806where
2807    T: Copy + Send + Sync + KernelStorageElement,
2808{
2809    let operand_data = operand.data_as::<T>()?;
2810    let dest_dims = dest.dims();
2811    let dest_strides = dest.strides();
2812    let dest_offset = dest.offset();
2813    let dest_data = dest.data_as_uninit_mut::<T>()?;
2814    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
2815    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2816    // count.
2817    let operand_ref = unsafe {
2818        RawStridedRef::new_unchecked(
2819            operand_data,
2820            operand.dims(),
2821            operand.strides(),
2822            operand.offset(),
2823        )
2824    };
2825    // SAFETY: as for `dest` in `execute_gather_uninit` (erased.rs:2412): `dest`'s construction
2826    // ran `validate_bounds` over these dims, strides and offset, and `data_as_uninit_mut` hands
2827    // out the only access to its slots.
2828    let mut dest_ref =
2829        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
2830    plan.execute_uninit(&mut dest_ref, &operand_ref, exec)
2831}
2832
2833fn execute_pad<T>(
2834    plan: &PadPlan,
2835    dest: &mut ErasedRawStridedMut<'_>,
2836    operand: &ErasedRawStridedRef<'_>,
2837    fill: &[u8],
2838    exec: Exec<'_>,
2839) -> Result<()>
2840where
2841    T: Copy + Send + Sync + KernelStorageElement,
2842{
2843    let fill = read_unaligned_scalar::<T>(fill);
2844    let operand_data = operand.data_as::<T>()?;
2845    let dest_dims = dest.dims();
2846    let dest_strides = dest.strides();
2847    let dest_offset = dest.offset();
2848    let dest_data = dest.data_as_mut::<T>()?;
2849    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
2850    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2851    // count.
2852    let operand_ref = unsafe {
2853        RawStridedRef::new_unchecked(
2854            operand_data,
2855            operand.dims(),
2856            operand.strides(),
2857            operand.offset(),
2858        )
2859    };
2860    // SAFETY: as for `dest` in `execute_one_shot_map` (erased.rs:1747): `dest`'s construction ran
2861    // `validate_bounds` over these dims, strides and offset, and `data_as_mut` hands out the only
2862    // access to its storage.
2863    let mut dest_ref =
2864        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
2865    plan.execute(&mut dest_ref, &operand_ref, fill, exec)
2866}
2867
2868fn execute_pad_uninit<T>(
2869    plan: &PadPlan,
2870    dest: &mut ErasedRawStridedUninitMut<'_>,
2871    operand: &ErasedRawStridedRef<'_>,
2872    fill: &[u8],
2873    exec: Exec<'_>,
2874) -> Result<()>
2875where
2876    T: Copy + Send + Sync + KernelStorageElement,
2877{
2878    let fill = read_unaligned_scalar::<T>(fill);
2879    let operand_data = operand.data_as::<T>()?;
2880    let dest_dims = dest.dims();
2881    let dest_strides = dest.strides();
2882    let dest_offset = dest.offset();
2883    let dest_data = dest.data_as_uninit_mut::<T>()?;
2884    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
2885    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2886    // count.
2887    let operand_ref = unsafe {
2888        RawStridedRef::new_unchecked(
2889            operand_data,
2890            operand.dims(),
2891            operand.strides(),
2892            operand.offset(),
2893        )
2894    };
2895    // SAFETY: as for `dest` in `execute_gather_uninit` (erased.rs:2412): `dest`'s construction
2896    // ran `validate_bounds` over these dims, strides and offset, and `data_as_uninit_mut` hands
2897    // out the only access to its slots.
2898    let mut dest_ref =
2899        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
2900    plan.execute_uninit(&mut dest_ref, &operand_ref, fill, exec)
2901}
2902
2903fn dispatch_gather_index<T>(
2904    plan: &GatherPlan,
2905    index_dtype: KernelDType,
2906    dest: &mut ErasedRawStridedMut<'_>,
2907    operand: &ErasedRawStridedRef<'_>,
2908    start_indices: &ErasedRawStridedRef<'_>,
2909    exec: Exec<'_>,
2910) -> Result<()>
2911where
2912    T: Copy + Send + Sync + KernelStorageElement,
2913{
2914    match index_dtype {
2915        KernelDType::I32 => execute_gather::<T, i32>(plan, dest, operand, start_indices, exec),
2916        KernelDType::I64 => execute_gather::<T, i64>(plan, dest, operand, start_indices, exec),
2917        _ => Err(StridedError::UnsupportedDType {
2918            dtype: index_dtype.label(),
2919        }),
2920    }
2921}
2922
2923fn execute_gather<T, I>(
2924    plan: &GatherPlan,
2925    dest: &mut ErasedRawStridedMut<'_>,
2926    operand: &ErasedRawStridedRef<'_>,
2927    start_indices: &ErasedRawStridedRef<'_>,
2928    exec: Exec<'_>,
2929) -> Result<()>
2930where
2931    T: Copy + Send + Sync + KernelStorageElement,
2932    I: GatherIndex + KernelStorageElement,
2933{
2934    let operand_data = operand.data_as::<T>()?;
2935    let index_data = start_indices.data_as::<I>()?;
2936    let dest_dims = dest.dims();
2937    let dest_strides = dest.strides();
2938    let dest_offset = dest.offset();
2939    let dest_data = dest.data_as_mut::<T>()?;
2940    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
2941    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
2942    // count.
2943    let operand_ref = unsafe {
2944        RawStridedRef::new_unchecked(
2945            operand_data,
2946            operand.dims(),
2947            operand.strides(),
2948            operand.offset(),
2949        )
2950    };
2951    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `start_indices` checked these dims,
2952    // strides and offset with `validate_bounds` when it was built, and `data_as` returned its
2953    // whole element count.
2954    let index_ref = unsafe {
2955        RawStridedRef::new_unchecked(
2956            index_data,
2957            start_indices.dims(),
2958            start_indices.strides(),
2959            start_indices.offset(),
2960        )
2961    };
2962    // SAFETY: as for `dest` in `execute_one_shot_map` (erased.rs:1747): `dest`'s construction ran
2963    // `validate_bounds` over these dims, strides and offset, and `data_as_mut` hands out the only
2964    // access to its storage.
2965    let mut dest_ref =
2966        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
2967    plan.execute(&mut dest_ref, &operand_ref, &index_ref, exec)
2968}
2969
2970fn dispatch_dynamic_slice_index<T>(
2971    plan: &DynamicSlicePlan,
2972    index_dtype: KernelDType,
2973    dest: &mut ErasedRawStridedMut<'_>,
2974    operand: &ErasedRawStridedRef<'_>,
2975    starts: &ErasedRawStridedRef<'_>,
2976    exec: Exec<'_>,
2977) -> Result<()>
2978where
2979    T: Copy + Send + Sync + KernelStorageElement,
2980{
2981    match index_dtype {
2982        KernelDType::I32 => execute_dynamic_slice::<T, i32>(plan, dest, operand, starts, exec),
2983        KernelDType::I64 => execute_dynamic_slice::<T, i64>(plan, dest, operand, starts, exec),
2984        _ => Err(StridedError::UnsupportedDType {
2985            dtype: index_dtype.label(),
2986        }),
2987    }
2988}
2989
2990fn execute_dynamic_slice<T, I>(
2991    plan: &DynamicSlicePlan,
2992    dest: &mut ErasedRawStridedMut<'_>,
2993    operand: &ErasedRawStridedRef<'_>,
2994    starts: &ErasedRawStridedRef<'_>,
2995    exec: Exec<'_>,
2996) -> Result<()>
2997where
2998    T: Copy + Send + Sync + KernelStorageElement,
2999    I: GatherIndex + KernelStorageElement,
3000{
3001    let operand_data = operand.data_as::<T>()?;
3002    let start_data = starts.data_as::<I>()?;
3003    let dest_dims = dest.dims();
3004    let dest_strides = dest.strides();
3005    let dest_offset = dest.offset();
3006    let dest_data = dest.data_as_mut::<T>()?;
3007    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
3008    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
3009    // count.
3010    let operand_ref = unsafe {
3011        RawStridedRef::new_unchecked(
3012            operand_data,
3013            operand.dims(),
3014            operand.strides(),
3015            operand.offset(),
3016        )
3017    };
3018    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `starts` checked these dims, strides and
3019    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
3020    // count.
3021    let start_ref = unsafe {
3022        RawStridedRef::new_unchecked(start_data, starts.dims(), starts.strides(), starts.offset())
3023    };
3024    // SAFETY: as for `dest` in `execute_one_shot_map` (erased.rs:1747): `dest`'s construction ran
3025    // `validate_bounds` over these dims, strides and offset, and `data_as_mut` hands out the only
3026    // access to its storage.
3027    let mut dest_ref =
3028        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
3029    plan.execute(&mut dest_ref, &operand_ref, &start_ref, exec)
3030}
3031
3032fn dispatch_dynamic_update_slice_index<T>(
3033    plan: &DynamicUpdateSlicePlan,
3034    index_dtype: KernelDType,
3035    dest: &mut ErasedRawStridedMut<'_>,
3036    operand: &ErasedRawStridedRef<'_>,
3037    update: &ErasedRawStridedRef<'_>,
3038    starts: &ErasedRawStridedRef<'_>,
3039    exec: Exec<'_>,
3040) -> Result<()>
3041where
3042    T: Copy + Send + Sync + KernelStorageElement,
3043{
3044    match index_dtype {
3045        KernelDType::I32 => {
3046            execute_dynamic_update_slice::<T, i32>(plan, dest, operand, update, starts, exec)
3047        }
3048        KernelDType::I64 => {
3049            execute_dynamic_update_slice::<T, i64>(plan, dest, operand, update, starts, exec)
3050        }
3051        _ => Err(StridedError::UnsupportedDType {
3052            dtype: index_dtype.label(),
3053        }),
3054    }
3055}
3056
3057fn execute_dynamic_update_slice<T, I>(
3058    plan: &DynamicUpdateSlicePlan,
3059    dest: &mut ErasedRawStridedMut<'_>,
3060    operand: &ErasedRawStridedRef<'_>,
3061    update: &ErasedRawStridedRef<'_>,
3062    starts: &ErasedRawStridedRef<'_>,
3063    exec: Exec<'_>,
3064) -> Result<()>
3065where
3066    T: Copy + Send + Sync + KernelStorageElement,
3067    I: GatherIndex + KernelStorageElement,
3068{
3069    let operand_data = operand.data_as::<T>()?;
3070    let update_data = update.data_as::<T>()?;
3071    let start_data = starts.data_as::<I>()?;
3072    let dest_dims = dest.dims();
3073    let dest_strides = dest.strides();
3074    let dest_offset = dest.offset();
3075    let dest_data = dest.data_as_mut::<T>()?;
3076    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
3077    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
3078    // count.
3079    let operand_ref = unsafe {
3080        RawStridedRef::new_unchecked(
3081            operand_data,
3082            operand.dims(),
3083            operand.strides(),
3084            operand.offset(),
3085        )
3086    };
3087    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `update` checked these dims, strides and
3088    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
3089    // count.
3090    let update_ref = unsafe {
3091        RawStridedRef::new_unchecked(
3092            update_data,
3093            update.dims(),
3094            update.strides(),
3095            update.offset(),
3096        )
3097    };
3098    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `starts` checked these dims, strides and
3099    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
3100    // count.
3101    let start_ref = unsafe {
3102        RawStridedRef::new_unchecked(start_data, starts.dims(), starts.strides(), starts.offset())
3103    };
3104    // SAFETY: as for `dest` in `execute_one_shot_map` (erased.rs:1747): `dest`'s construction ran
3105    // `validate_bounds` over these dims, strides and offset, and `data_as_mut` hands out the only
3106    // access to its storage.
3107    let mut dest_ref =
3108        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
3109    plan.execute(&mut dest_ref, &operand_ref, &update_ref, &start_ref, exec)
3110}
3111
3112#[allow(clippy::too_many_arguments)]
3113fn dispatch_scatter_index<T>(
3114    plan: &ScatterPlan,
3115    index_dtype: KernelDType,
3116    dest: &mut ErasedRawStridedMut<'_>,
3117    operand: &ErasedRawStridedRef<'_>,
3118    scatter_indices: &ErasedRawStridedRef<'_>,
3119    updates: &ErasedRawStridedRef<'_>,
3120    exec: Exec<'_>,
3121) -> Result<()>
3122where
3123    T: ScatterScalar + KernelStorageElement,
3124{
3125    match index_dtype {
3126        KernelDType::I32 => {
3127            execute_scatter::<T, i32>(plan, dest, operand, scatter_indices, updates, exec)
3128        }
3129        KernelDType::I64 => {
3130            execute_scatter::<T, i64>(plan, dest, operand, scatter_indices, updates, exec)
3131        }
3132        _ => Err(StridedError::UnsupportedDType {
3133            dtype: index_dtype.label(),
3134        }),
3135    }
3136}
3137
3138fn execute_scatter<T, I>(
3139    plan: &ScatterPlan,
3140    dest: &mut ErasedRawStridedMut<'_>,
3141    operand: &ErasedRawStridedRef<'_>,
3142    scatter_indices: &ErasedRawStridedRef<'_>,
3143    updates: &ErasedRawStridedRef<'_>,
3144    exec: Exec<'_>,
3145) -> Result<()>
3146where
3147    T: ScatterScalar + KernelStorageElement,
3148    I: GatherIndex + KernelStorageElement,
3149{
3150    let operand_data = operand.data_as::<T>()?;
3151    let index_data = scatter_indices.data_as::<I>()?;
3152    let update_data = updates.data_as::<T>()?;
3153    let dest_dims = dest.dims();
3154    let dest_strides = dest.strides();
3155    let dest_offset = dest.offset();
3156    let dest_data = dest.data_as_mut::<T>()?;
3157    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `operand` checked these dims, strides and
3158    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
3159    // count.
3160    let operand_ref = unsafe {
3161        RawStridedRef::new_unchecked(
3162            operand_data,
3163            operand.dims(),
3164            operand.strides(),
3165            operand.offset(),
3166        )
3167    };
3168    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `scatter_indices` checked these dims,
3169    // strides and offset with `validate_bounds` when it was built, and `data_as` returned its
3170    // whole element count.
3171    let index_ref = unsafe {
3172        RawStridedRef::new_unchecked(
3173            index_data,
3174            scatter_indices.dims(),
3175            scatter_indices.strides(),
3176            scatter_indices.offset(),
3177        )
3178    };
3179    // SAFETY: as in `erased_raw_ref` (erased.rs:2148): `updates` checked these dims, strides and
3180    // offset with `validate_bounds` when it was built, and `data_as` returned its whole element
3181    // count.
3182    let update_ref = unsafe {
3183        RawStridedRef::new_unchecked(
3184            update_data,
3185            updates.dims(),
3186            updates.strides(),
3187            updates.offset(),
3188        )
3189    };
3190    // SAFETY: as for `dest` in `execute_one_shot_map` (erased.rs:1747): `dest`'s construction ran
3191    // `validate_bounds` over these dims, strides and offset, and `data_as_mut` hands out the only
3192    // access to its storage.
3193    let mut dest_ref =
3194        unsafe { RawStridedMut::new_unchecked(dest_data, dest_dims, dest_strides, dest_offset) };
3195    // The typed entry itself, so the erased and typed initialized scatter share one combine
3196    // (`ScatterScalar::wrapping_add`).
3197    plan.execute(&mut dest_ref, &operand_ref, &index_ref, &update_ref, exec)
3198}
3199
3200fn read_unaligned_scalar<T>(bytes: &[u8]) -> T
3201where
3202    T: Copy,
3203{
3204    // SAFETY: `read_unaligned` needs `size_of::<T>()` readable bytes and, for the value, a valid
3205    // bit pattern of `T`; it accepts any alignment. Both callers, `execute_pad` and
3206    // `execute_pad_uninit`, run only after `ErasedPadPlan::execute`/`execute_uninit` called
3207    // `validate_scalar_bytes` (erased.rs:2298) at erased.rs:549 and erased.rs:594. It checks
3208    // that `fill.len()` is the dtype's size, which is `size_of::<T>()` for the `T` each match arm
3209    // picks, and rejects bool bytes other than 0 or 1; the other dtypes accept any bit pattern.
3210    // This safe helper depends on that validation: a shorter slice would be read out of bounds.
3211    unsafe { core::ptr::read_unaligned(bytes.as_ptr().cast::<T>()) }
3212}