strided_kernel/erased/uninit.rs
1//! Dtype-erased elementwise entry points that fully overwrite uninitialized
2//! output storage.
3//!
4//! Every entry point validates dtype, shape, destination injectivity, and
5//! input/output overlap before the first write. `Ok(())` means every reachable
6//! destination element was initialized. A panic during replay may leave the
7//! destination partially initialized, which remains safe to drop because the
8//! storage is `MaybeUninit`.
9
10use super::{erased_raw_ref, map_output_dtype, raw_any, OneShotScalar};
11use crate::*;
12use core::mem::MaybeUninit;
13use core::num::Wrapping;
14use num_complex::{Complex32, Complex64};
15use strided_basic::execution::{
16 check_dtype, ensure_same_shape, map_raw_into_validated,
17 validate_destination_layout_without_alloc, validate_uninit_no_overlap,
18 zip_map2_raw_into_validated, ValidatedDestinationLayout,
19};
20
21/// Apply one runtime-selected unary operation into uninitialized storage.
22///
23/// The dtype contract matches [`erased_map_into`](crate::erased_map_into):
24/// complex absolute value writes `c32 -> f32` and `c64 -> f64`, `bool`
25/// supports only [`ErasedMapOp::Conj`], and signed integers use wrapping
26/// negate/abs.
27///
28/// # Examples
29///
30/// ```
31/// use core::mem::MaybeUninit;
32/// use strided_kernel::{
33/// erased_map_into_uninit, ErasedMapOp, ErasedRawStridedPtr, ErasedRawStridedRef,
34/// ErasedRawStridedUninitMut, Exec, KernelDType,
35/// };
36///
37/// let input = [-1.5_f64, 2.0];
38/// let input = ErasedRawStridedRef::from_slice(&input, &[2], &[1], 0).unwrap();
39/// let mut out = [MaybeUninit::<f64>::uninit(); 2];
40/// let mut dest = ErasedRawStridedUninitMut::from_uninit_slice(&mut out, &[2], &[1], 0).unwrap();
41/// erased_map_into_uninit(
42/// KernelDType::F64,
43/// ErasedMapOp::Abs,
44/// &mut dest,
45/// &ErasedRawStridedPtr::from_ref(&input),
46/// Exec::serial(),
47/// )
48/// .unwrap();
49/// // SAFETY: a successful call initializes every reachable element.
50/// assert_eq!(unsafe { [out[0].assume_init(), out[1].assume_init()] }, [1.5, 2.0]);
51/// ```
52///
53/// # Errors
54///
55/// Returns [`StridedError::DTypeMismatch`] when `input` or `dest` does not
56/// carry the dtype that `input_dtype` and `op` imply,
57/// [`StridedError::UnsupportedOp`] for a `bool` input with any op other than
58/// [`ErasedMapOp::Conj`], [`StridedError::OverlappingInputOutput`] when the
59/// input allocation overlaps the destination,
60/// [`StridedError::InvalidBoolByte`] when a `bool` input holds a byte other
61/// than 0 or 1, [`StridedError::NonInjectiveOutputLayout`] when the
62/// destination layout cannot be proven to place logical elements on distinct
63/// offsets, and [`StridedError::RankMismatch`] or
64/// [`StridedError::ShapeMismatch`] when the destination dims differ from the
65/// input dims. Validation completes before any write.
66pub fn erased_map_into_uninit(
67 input_dtype: KernelDType,
68 op: ErasedMapOp,
69 dest: &mut ErasedRawStridedUninitMut<'_>,
70 input: &ErasedRawStridedPtr<'_>,
71 exec: Exec<'_>,
72) -> Result<()> {
73 check_dtype(input_dtype, input.dtype())?;
74 check_dtype(map_output_dtype(input_dtype, op)?, dest.dtype())?;
75 validate_uninit_no_overlap(dest, input, 0)?;
76 // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things. No
77 // mutable allocation may overlap `input`'s byte extent: `dest` is the only one in this call,
78 // and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18) checked `input`
79 // against it at erased/uninit.rs:75 by comparing whole byte ranges (`overlaps_uninit_mut`,
80 // strided-view/src/raw.rs:355). The allocation contract `input` was built under
81 // (strided-view/src/raw.rs:204) must still hold; that is the obligation of whoever built
82 // `input`. No conflicting access may happen while the result is used: within this call the
83 // only writer is `dest`, which does not overlap, and the `input` contract
84 // (strided-view/src/raw.rs:212) rules out concurrent mutation from outside.
85 let input = unsafe { input.try_as_ref_after_no_overlap() }?;
86
87 match (input_dtype, op) {
88 (KernelDType::C32, ErasedMapOp::Abs) => {
89 uninit_map_with::<f32, Complex32>(dest, &input, |value| value.norm(), exec)
90 }
91 (KernelDType::C64, ErasedMapOp::Abs) => {
92 uninit_map_with::<f64, Complex64>(dest, &input, |value| value.norm(), exec)
93 }
94 (KernelDType::F32, _) => uninit_map::<f32>(op, dest, &input, exec),
95 (KernelDType::F64, _) => uninit_map::<f64>(op, dest, &input, exec),
96 (KernelDType::I32, _) => uninit_map::<i32>(op, dest, &input, exec),
97 (KernelDType::I64, _) => uninit_map::<i64>(op, dest, &input, exec),
98 (KernelDType::Bool, _) => uninit_map::<bool>(op, dest, &input, exec),
99 (KernelDType::C32, _) => uninit_map::<Complex32>(op, dest, &input, exec),
100 (KernelDType::C64, _) => uninit_map::<Complex64>(op, dest, &input, exec),
101 _ => Err(StridedError::UnsupportedDType {
102 dtype: input_dtype.label(),
103 }),
104 }
105}
106
107/// Apply one runtime-selected binary operation into uninitialized storage.
108///
109/// The dtype contract matches [`erased_zip_into`](crate::erased_zip_into).
110/// Signed-integer divide and remainder scan the divisor before any write and
111/// return [`StridedError::IntegerDivisionByZero`] when it contains zero; all
112/// other integer arithmetic wraps. Real maximum/minimum propagate NaN.
113///
114/// # Examples
115///
116/// ```
117/// use core::mem::MaybeUninit;
118/// use strided_kernel::{
119/// erased_zip_into_uninit, ErasedRawStridedPtr, ErasedRawStridedRef,
120/// ErasedRawStridedUninitMut, ErasedZipOp, Exec, KernelDType,
121/// };
122///
123/// let lhs = [i32::MAX, 7];
124/// let rhs = [1_i32, 2];
125/// let lhs = ErasedRawStridedRef::from_slice(&lhs, &[2], &[1], 0).unwrap();
126/// let rhs = ErasedRawStridedRef::from_slice(&rhs, &[2], &[1], 0).unwrap();
127/// let mut out = [MaybeUninit::<i32>::uninit(); 2];
128/// let mut dest = ErasedRawStridedUninitMut::from_uninit_slice(&mut out, &[2], &[1], 0).unwrap();
129/// erased_zip_into_uninit(
130/// KernelDType::I32,
131/// ErasedZipOp::Add,
132/// &mut dest,
133/// &ErasedRawStridedPtr::from_ref(&lhs),
134/// &ErasedRawStridedPtr::from_ref(&rhs),
135/// Exec::serial(),
136/// )
137/// .unwrap();
138/// // SAFETY: a successful call initializes every reachable element.
139/// assert_eq!(unsafe { [out[0].assume_init(), out[1].assume_init()] }, [i32::MIN, 9]);
140/// ```
141///
142/// # Errors
143///
144/// Returns [`StridedError::DTypeMismatch`] when `dest`, `lhs`, or `rhs` does
145/// not carry `dtype`, [`StridedError::UnsupportedOp`] for `bool` operands or
146/// for a complex remainder/maximum/minimum,
147/// [`StridedError::OverlappingInputOutput`] when either input allocation
148/// overlaps the destination, [`StridedError::InvalidBoolByte`] when an input
149/// holds a `bool` byte other than 0 or 1,
150/// [`StridedError::IntegerDivisionByZero`] when an integer divide or
151/// remainder finds a zero divisor,
152/// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
153/// cannot be proven to place logical elements on distinct offsets, and
154/// [`StridedError::RankMismatch`] or [`StridedError::ShapeMismatch`] when the
155/// destination dims differ from either input's dims. Validation completes
156/// before any write.
157pub fn erased_zip_into_uninit(
158 dtype: KernelDType,
159 op: ErasedZipOp,
160 dest: &mut ErasedRawStridedUninitMut<'_>,
161 lhs: &ErasedRawStridedPtr<'_>,
162 rhs: &ErasedRawStridedPtr<'_>,
163 exec: Exec<'_>,
164) -> Result<()> {
165 check_dtype(dtype, dest.dtype())?;
166 check_dtype(dtype, lhs.dtype())?;
167 check_dtype(dtype, rhs.dtype())?;
168 validate_uninit_no_overlap(dest, lhs, 0)?;
169 validate_uninit_no_overlap(dest, rhs, 1)?;
170 // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things. No
171 // mutable allocation may overlap `lhs`'s byte extent: `dest` is the only one in this call,
172 // and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18) checked `lhs`
173 // against it at erased/uninit.rs:168 by comparing whole byte ranges (`overlaps_uninit_mut`,
174 // strided-view/src/raw.rs:355). The allocation contract `lhs` was built under
175 // (strided-view/src/raw.rs:204) must still hold; that is the obligation of whoever built
176 // `lhs`. No conflicting access may happen while the result is used: within this call the only
177 // writer is `dest`, which does not overlap, and the `lhs` contract
178 // (strided-view/src/raw.rs:212) rules out concurrent mutation from outside.
179 let lhs = unsafe { lhs.try_as_ref_after_no_overlap() }?;
180 // SAFETY: as for `lhs` above: `validate_uninit_no_overlap` checked `rhs` against `dest` at
181 // erased/uninit.rs:169, and the same allocation contract and exclusive `dest` borrow apply.
182 let rhs = unsafe { rhs.try_as_ref_after_no_overlap() }?;
183
184 match dtype {
185 KernelDType::F32 => uninit_zip::<f32>(op, dest, &lhs, &rhs, exec),
186 KernelDType::F64 => uninit_zip::<f64>(op, dest, &lhs, &rhs, exec),
187 KernelDType::I32 => uninit_zip::<i32>(op, dest, &lhs, &rhs, exec),
188 KernelDType::I64 => uninit_zip::<i64>(op, dest, &lhs, &rhs, exec),
189 KernelDType::Bool => uninit_zip::<bool>(op, dest, &lhs, &rhs, exec),
190 KernelDType::C32 => uninit_zip::<Complex32>(op, dest, &lhs, &rhs, exec),
191 KernelDType::C64 => uninit_zip::<Complex64>(op, dest, &lhs, &rhs, exec),
192 _ => Err(StridedError::UnsupportedDType {
193 dtype: dtype.label(),
194 }),
195 }
196}
197
198/// Compare two same-dtype operands elementwise into uninitialized `bool`
199/// storage.
200///
201/// Real, signed-integer, and `bool` operands support every [`CompareOp`] with
202/// `PartialOrd` semantics, so any comparison involving NaN is `false`.
203/// Complex operands support only [`CompareOp::Eq`]; ordered comparisons return
204/// [`StridedError::UnsupportedOp`]. The destination dtype must be `bool`.
205///
206/// # Examples
207///
208/// ```
209/// use core::mem::MaybeUninit;
210/// use strided_kernel::{
211/// erased_compare_into_uninit, CompareOp, ErasedRawStridedPtr, ErasedRawStridedRef,
212/// ErasedRawStridedUninitMut, Exec, KernelDType,
213/// };
214///
215/// let lhs = [1.0_f64, f64::NAN];
216/// let rhs = [2.0_f64, 0.0];
217/// let lhs = ErasedRawStridedRef::from_slice(&lhs, &[2], &[1], 0).unwrap();
218/// let rhs = ErasedRawStridedRef::from_slice(&rhs, &[2], &[1], 0).unwrap();
219/// let mut out = [MaybeUninit::<bool>::uninit(); 2];
220/// let mut dest = ErasedRawStridedUninitMut::from_uninit_slice(&mut out, &[2], &[1], 0).unwrap();
221/// erased_compare_into_uninit(
222/// KernelDType::F64,
223/// CompareOp::Lt,
224/// &mut dest,
225/// &ErasedRawStridedPtr::from_ref(&lhs),
226/// &ErasedRawStridedPtr::from_ref(&rhs),
227/// Exec::serial(),
228/// )
229/// .unwrap();
230/// // SAFETY: a successful call initializes every reachable element.
231/// assert_eq!(unsafe { [out[0].assume_init(), out[1].assume_init()] }, [true, false]);
232/// ```
233///
234/// # Errors
235///
236/// Returns [`StridedError::DTypeMismatch`] when `dest` is not `bool` or when
237/// `lhs` or `rhs` does not carry `dtype`,
238/// [`StridedError::UnsupportedOp`] for an ordered comparison of complex
239/// operands, [`StridedError::OverlappingInputOutput`] when either input
240/// allocation overlaps the destination,
241/// [`StridedError::InvalidBoolByte`] when an input holds a `bool` byte other
242/// than 0 or 1, [`StridedError::NonInjectiveOutputLayout`] when the
243/// destination layout cannot be proven to place logical elements on distinct
244/// offsets, and [`StridedError::RankMismatch`] or
245/// [`StridedError::ShapeMismatch`] when the destination dims differ from
246/// either input's dims. Validation completes before any write.
247pub fn erased_compare_into_uninit(
248 dtype: KernelDType,
249 op: CompareOp,
250 dest: &mut ErasedRawStridedUninitMut<'_>,
251 lhs: &ErasedRawStridedPtr<'_>,
252 rhs: &ErasedRawStridedPtr<'_>,
253 exec: Exec<'_>,
254) -> Result<()> {
255 check_dtype(KernelDType::Bool, dest.dtype())?;
256 check_dtype(dtype, lhs.dtype())?;
257 check_dtype(dtype, rhs.dtype())?;
258 validate_uninit_no_overlap(dest, lhs, 0)?;
259 validate_uninit_no_overlap(dest, rhs, 1)?;
260 // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things. No
261 // mutable allocation may overlap `lhs`'s byte extent: `dest` is the only one in this call,
262 // and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18) checked `lhs`
263 // against it at erased/uninit.rs:258 by comparing whole byte ranges (`overlaps_uninit_mut`,
264 // strided-view/src/raw.rs:355). The allocation contract `lhs` was built under
265 // (strided-view/src/raw.rs:204) must still hold; that is the obligation of whoever built
266 // `lhs`. No conflicting access may happen while the result is used: within this call the only
267 // writer is `dest`, which does not overlap, and the `lhs` contract
268 // (strided-view/src/raw.rs:212) rules out concurrent mutation from outside.
269 let lhs = unsafe { lhs.try_as_ref_after_no_overlap() }?;
270 // SAFETY: as for `lhs` above: `validate_uninit_no_overlap` checked `rhs` against `dest` at
271 // erased/uninit.rs:259, and the same allocation contract and exclusive `dest` borrow apply.
272 let rhs = unsafe { rhs.try_as_ref_after_no_overlap() }?;
273
274 match dtype {
275 KernelDType::F32 => uninit_compare_ordered::<f32>(op, dest, &lhs, &rhs, exec),
276 KernelDType::F64 => uninit_compare_ordered::<f64>(op, dest, &lhs, &rhs, exec),
277 KernelDType::I32 => uninit_compare_ordered::<i32>(op, dest, &lhs, &rhs, exec),
278 KernelDType::I64 => uninit_compare_ordered::<i64>(op, dest, &lhs, &rhs, exec),
279 KernelDType::Bool => uninit_compare_ordered::<bool>(op, dest, &lhs, &rhs, exec),
280 KernelDType::C32 => uninit_compare_eq::<Complex32>(op, dest, &lhs, &rhs, exec),
281 KernelDType::C64 => uninit_compare_eq::<Complex64>(op, dest, &lhs, &rhs, exec),
282 _ => Err(StridedError::UnsupportedDType {
283 dtype: dtype.label(),
284 }),
285 }
286}
287
288/// Select elementwise between two same-dtype operands by a `bool` predicate,
289/// writing uninitialized storage: `dest[i] = if pred[i] { on_true[i] } else
290/// { on_false[i] }`.
291///
292/// Every dtype is supported. The predicate dtype must be `bool`.
293///
294/// # Examples
295///
296/// ```
297/// use core::mem::MaybeUninit;
298/// use strided_kernel::{
299/// erased_select_into_uninit, ErasedRawStridedPtr, ErasedRawStridedRef,
300/// ErasedRawStridedUninitMut, Exec, KernelDType,
301/// };
302///
303/// let pred = [true, false];
304/// let on_true = [1_i64, 2];
305/// let on_false = [10_i64, 20];
306/// let pred = ErasedRawStridedRef::from_slice(&pred, &[2], &[1], 0).unwrap();
307/// let on_true = ErasedRawStridedRef::from_slice(&on_true, &[2], &[1], 0).unwrap();
308/// let on_false = ErasedRawStridedRef::from_slice(&on_false, &[2], &[1], 0).unwrap();
309/// let mut out = [MaybeUninit::<i64>::uninit(); 2];
310/// let mut dest = ErasedRawStridedUninitMut::from_uninit_slice(&mut out, &[2], &[1], 0).unwrap();
311/// erased_select_into_uninit(
312/// KernelDType::I64,
313/// &mut dest,
314/// &ErasedRawStridedPtr::from_ref(&pred),
315/// &ErasedRawStridedPtr::from_ref(&on_true),
316/// &ErasedRawStridedPtr::from_ref(&on_false),
317/// Exec::serial(),
318/// )
319/// .unwrap();
320/// // SAFETY: a successful call initializes every reachable element.
321/// assert_eq!(unsafe { [out[0].assume_init(), out[1].assume_init()] }, [1, 20]);
322/// ```
323///
324/// # Errors
325///
326/// Returns [`StridedError::DTypeMismatch`] when `pred` is not `bool` or when
327/// `dest`, `on_true`, or `on_false` does not carry `dtype`,
328/// [`StridedError::OverlappingInputOutput`] when any input allocation
329/// overlaps the destination, [`StridedError::InvalidBoolByte`] when `pred` or
330/// a `bool` operand holds a byte other than 0 or 1,
331/// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
332/// cannot be proven to place logical elements on distinct offsets, and
333/// [`StridedError::RankMismatch`] or [`StridedError::ShapeMismatch`] when the
334/// destination dims differ from an input's dims. Validation completes before
335/// any write.
336pub fn erased_select_into_uninit(
337 dtype: KernelDType,
338 dest: &mut ErasedRawStridedUninitMut<'_>,
339 pred: &ErasedRawStridedPtr<'_>,
340 on_true: &ErasedRawStridedPtr<'_>,
341 on_false: &ErasedRawStridedPtr<'_>,
342 exec: Exec<'_>,
343) -> Result<()> {
344 check_dtype(dtype, dest.dtype())?;
345 check_dtype(KernelDType::Bool, pred.dtype())?;
346 check_dtype(dtype, on_true.dtype())?;
347 check_dtype(dtype, on_false.dtype())?;
348 validate_uninit_no_overlap(dest, pred, 0)?;
349 validate_uninit_no_overlap(dest, on_true, 1)?;
350 validate_uninit_no_overlap(dest, on_false, 2)?;
351 // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things. No
352 // mutable allocation may overlap `pred`'s byte extent: `dest` is the only one in this call,
353 // and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18) checked `pred`
354 // against it at erased/uninit.rs:348 by comparing whole byte ranges (`overlaps_uninit_mut`,
355 // strided-view/src/raw.rs:355). The allocation contract `pred` was built under
356 // (strided-view/src/raw.rs:204) must still hold; that is the obligation of whoever built
357 // `pred`. No conflicting access may happen while the result is used: within this call the
358 // only writer is `dest`, which does not overlap, and the `pred` contract
359 // (strided-view/src/raw.rs:212) rules out concurrent mutation from outside.
360 let pred = unsafe { pred.try_as_ref_after_no_overlap() }?;
361 // SAFETY: as for `pred` above: `validate_uninit_no_overlap` checked `on_true` against `dest`
362 // at erased/uninit.rs:349, and the same allocation contract and exclusive `dest` borrow
363 // apply.
364 let on_true = unsafe { on_true.try_as_ref_after_no_overlap() }?;
365 // SAFETY: as for `pred` above: `validate_uninit_no_overlap` checked `on_false` against `dest`
366 // at erased/uninit.rs:350, and the same allocation contract and exclusive `dest` borrow
367 // apply.
368 let on_false = unsafe { on_false.try_as_ref_after_no_overlap() }?;
369
370 match dtype {
371 KernelDType::F32 => uninit_select::<f32>(dest, &pred, &on_true, &on_false, exec),
372 KernelDType::F64 => uninit_select::<f64>(dest, &pred, &on_true, &on_false, exec),
373 KernelDType::I32 => uninit_select::<i32>(dest, &pred, &on_true, &on_false, exec),
374 KernelDType::I64 => uninit_select::<i64>(dest, &pred, &on_true, &on_false, exec),
375 KernelDType::Bool => uninit_select::<bool>(dest, &pred, &on_true, &on_false, exec),
376 KernelDType::C32 => uninit_select::<Complex32>(dest, &pred, &on_true, &on_false, exec),
377 KernelDType::C64 => uninit_select::<Complex64>(dest, &pred, &on_true, &on_false, exec),
378 _ => Err(StridedError::UnsupportedDType {
379 dtype: dtype.label(),
380 }),
381 }
382}
383
384/// Clamp elementwise into uninitialized storage:
385/// `dest[i] = minimum(hi[i], maximum(lo[i], x[i]))`.
386///
387/// `maximum` and `minimum` are [`ErasedZipOp::Maximum`] and
388/// [`ErasedZipOp::Minimum`], so a NaN in any real operand yields NaN and
389/// `lo > hi` yields `hi`. Supported dtypes are `f32`, `f64`, `i32`, and `i64`.
390///
391/// # Examples
392///
393/// ```
394/// use core::mem::MaybeUninit;
395/// use strided_kernel::{
396/// erased_clamp_into_uninit, ErasedRawStridedPtr, ErasedRawStridedRef,
397/// ErasedRawStridedUninitMut, Exec, KernelDType,
398/// };
399///
400/// let x = [-3.0_f32, 0.5, 9.0];
401/// let lo = [0.0_f32; 1];
402/// let hi = [1.0_f32; 1];
403/// let x = ErasedRawStridedRef::from_slice(&x, &[3], &[1], 0).unwrap();
404/// // Stride-0 descriptors broadcast one bound over the output.
405/// let lo = ErasedRawStridedRef::from_slice(&lo, &[3], &[0], 0).unwrap();
406/// let hi = ErasedRawStridedRef::from_slice(&hi, &[3], &[0], 0).unwrap();
407/// let mut out = [MaybeUninit::<f32>::uninit(); 3];
408/// let mut dest = ErasedRawStridedUninitMut::from_uninit_slice(&mut out, &[3], &[1], 0).unwrap();
409/// erased_clamp_into_uninit(
410/// KernelDType::F32,
411/// &mut dest,
412/// &ErasedRawStridedPtr::from_ref(&x),
413/// &ErasedRawStridedPtr::from_ref(&lo),
414/// &ErasedRawStridedPtr::from_ref(&hi),
415/// Exec::serial(),
416/// )
417/// .unwrap();
418/// // SAFETY: a successful call initializes every reachable element.
419/// let out = unsafe { out.map(|value| value.assume_init()) };
420/// assert_eq!(out, [0.0, 0.5, 1.0]);
421/// ```
422///
423/// # Errors
424///
425/// Returns [`StridedError::DTypeMismatch`] when `dest`, `x`, `lo`, or `hi`
426/// does not carry `dtype`, [`StridedError::OverlappingInputOutput`] when any
427/// input allocation overlaps the destination,
428/// [`StridedError::InvalidBoolByte`] when an input holds a `bool` byte other
429/// than 0 or 1, [`StridedError::NonInjectiveOutputLayout`] when the
430/// destination layout cannot be proven to place logical elements on distinct
431/// offsets, [`StridedError::RankMismatch`] or
432/// [`StridedError::ShapeMismatch`] when the destination dims differ from an
433/// input's dims, and
434/// [`StridedError::UnsupportedDType`] for a dtype other than `f32`, `f64`,
435/// `i32`, or `i64`. Validation completes before any write.
436pub fn erased_clamp_into_uninit(
437 dtype: KernelDType,
438 dest: &mut ErasedRawStridedUninitMut<'_>,
439 x: &ErasedRawStridedPtr<'_>,
440 lo: &ErasedRawStridedPtr<'_>,
441 hi: &ErasedRawStridedPtr<'_>,
442 exec: Exec<'_>,
443) -> Result<()> {
444 check_dtype(dtype, dest.dtype())?;
445 check_dtype(dtype, x.dtype())?;
446 check_dtype(dtype, lo.dtype())?;
447 check_dtype(dtype, hi.dtype())?;
448 validate_uninit_no_overlap(dest, x, 0)?;
449 validate_uninit_no_overlap(dest, lo, 1)?;
450 validate_uninit_no_overlap(dest, hi, 2)?;
451 // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things. No
452 // mutable allocation may overlap `x`'s byte extent: `dest` is the only one in this call, and
453 // `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18) checked `x` against it
454 // at erased/uninit.rs:448 by comparing whole byte ranges (`overlaps_uninit_mut`,
455 // strided-view/src/raw.rs:355). The allocation contract `x` was built under
456 // (strided-view/src/raw.rs:204) must still hold; that is the obligation of whoever built `x`.
457 // No conflicting access may happen while the result is used: within this call the only writer
458 // is `dest`, which does not overlap, and the `x` contract (strided-view/src/raw.rs:212) rules
459 // out concurrent mutation from outside.
460 let x = unsafe { x.try_as_ref_after_no_overlap() }?;
461 // SAFETY: as for `x` above: `validate_uninit_no_overlap` checked `lo` against `dest` at
462 // erased/uninit.rs:449, and the same allocation contract and exclusive `dest` borrow apply.
463 let lo = unsafe { lo.try_as_ref_after_no_overlap() }?;
464 // SAFETY: as for `x` above: `validate_uninit_no_overlap` checked `hi` against `dest` at
465 // erased/uninit.rs:450, and the same allocation contract and exclusive `dest` borrow apply.
466 let hi = unsafe { hi.try_as_ref_after_no_overlap() }?;
467
468 match dtype {
469 KernelDType::F32 => uninit_clamp::<f32>(dest, &x, &lo, &hi, exec),
470 KernelDType::F64 => uninit_clamp::<f64>(dest, &x, &lo, &hi, exec),
471 KernelDType::I32 => uninit_clamp::<i32>(dest, &x, &lo, &hi, exec),
472 KernelDType::I64 => uninit_clamp::<i64>(dest, &x, &lo, &hi, exec),
473 _ => Err(StridedError::UnsupportedDType {
474 dtype: dtype.label(),
475 }),
476 }
477}
478
479/// Broadcast two same-dtype operands onto the destination axes and multiply
480/// them into uninitialized storage.
481///
482/// `lhs_axes[k]` names the destination axis that `lhs` axis `k` maps to; each
483/// mapped extent must equal the destination extent or be one, and unmapped
484/// destination axes broadcast. Supported dtypes are `f32`, `f64`, `c32`,
485/// `c64`, and the signed integers, whose products wrap on overflow.
486///
487/// # Examples
488///
489/// ```
490/// use core::mem::MaybeUninit;
491/// use strided_kernel::{
492/// erased_broadcast_mul_into_uninit, ErasedRawStridedPtr, ErasedRawStridedRef,
493/// ErasedRawStridedUninitMut, Exec, KernelDType,
494/// };
495///
496/// // Outer product: out[i, j] = a[i] * b[j], column-major 2 x 3 output.
497/// let a = [1.0_f64, 2.0];
498/// let b = [10.0_f64, 20.0, 30.0];
499/// let a = ErasedRawStridedRef::from_slice(&a, &[2], &[1], 0).unwrap();
500/// let b = ErasedRawStridedRef::from_slice(&b, &[3], &[1], 0).unwrap();
501/// let mut out = [MaybeUninit::<f64>::uninit(); 6];
502/// let mut dest =
503/// ErasedRawStridedUninitMut::from_uninit_slice(&mut out, &[2, 3], &[1, 2], 0).unwrap();
504/// erased_broadcast_mul_into_uninit(
505/// KernelDType::F64,
506/// &mut dest,
507/// &ErasedRawStridedPtr::from_ref(&a),
508/// &[0],
509/// &ErasedRawStridedPtr::from_ref(&b),
510/// &[1],
511/// Exec::serial(),
512/// )
513/// .unwrap();
514/// // SAFETY: a successful call initializes every reachable element.
515/// let out = unsafe { out.map(|value| value.assume_init()) };
516/// assert_eq!(out, [10.0, 20.0, 20.0, 40.0, 30.0, 60.0]);
517/// ```
518///
519/// # Errors
520///
521/// Returns [`StridedError::DTypeMismatch`] when `dest`, `lhs`, or `rhs` does
522/// not carry `dtype`, [`StridedError::OverlappingInputOutput`] when either
523/// input allocation overlaps the destination,
524/// [`StridedError::InvalidBoolByte`] when an input holds a `bool` byte other
525/// than 0 or 1, [`StridedError::RankMismatch`] when `lhs_axes` or `rhs_axes`
526/// is not one axis per input dim, [`StridedError::InvalidAxis`] for a mapped
527/// axis that is out of range or named twice,
528/// [`StridedError::ShapeMismatch`] when a mapped input extent is neither the
529/// destination extent nor one,
530/// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
531/// cannot be proven to place logical elements on distinct offsets, and
532/// [`StridedError::UnsupportedDType`] for `bool`. Validation completes before
533/// any write.
534pub fn erased_broadcast_mul_into_uninit(
535 dtype: KernelDType,
536 dest: &mut ErasedRawStridedUninitMut<'_>,
537 lhs: &ErasedRawStridedPtr<'_>,
538 lhs_axes: &[usize],
539 rhs: &ErasedRawStridedPtr<'_>,
540 rhs_axes: &[usize],
541 exec: Exec<'_>,
542) -> Result<()> {
543 check_dtype(dtype, dest.dtype())?;
544 check_dtype(dtype, lhs.dtype())?;
545 check_dtype(dtype, rhs.dtype())?;
546 validate_uninit_no_overlap(dest, lhs, 0)?;
547 validate_uninit_no_overlap(dest, rhs, 1)?;
548 // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs three things. No
549 // mutable allocation may overlap `lhs`'s byte extent: `dest` is the only one in this call,
550 // and `validate_uninit_no_overlap` (strided-basic/src/erased_common.rs:18) checked `lhs`
551 // against it at erased/uninit.rs:546 by comparing whole byte ranges (`overlaps_uninit_mut`,
552 // strided-view/src/raw.rs:355). The allocation contract `lhs` was built under
553 // (strided-view/src/raw.rs:204) must still hold; that is the obligation of whoever built
554 // `lhs`. No conflicting access may happen while the result is used: within this call the only
555 // writer is `dest`, which does not overlap, and the `lhs` contract
556 // (strided-view/src/raw.rs:212) rules out concurrent mutation from outside.
557 let lhs = unsafe { lhs.try_as_ref_after_no_overlap() }?;
558 // SAFETY: as for `lhs` above: `validate_uninit_no_overlap` checked `rhs` against `dest` at
559 // erased/uninit.rs:547, and the same allocation contract and exclusive `dest` borrow apply.
560 let rhs = unsafe { rhs.try_as_ref_after_no_overlap() }?;
561
562 match dtype {
563 KernelDType::F32 => uninit_broadcast_mul::<f32>(dest, &lhs, lhs_axes, &rhs, rhs_axes, exec),
564 KernelDType::F64 => uninit_broadcast_mul::<f64>(dest, &lhs, lhs_axes, &rhs, rhs_axes, exec),
565 KernelDType::C32 => {
566 uninit_broadcast_mul::<Complex32>(dest, &lhs, lhs_axes, &rhs, rhs_axes, exec)
567 }
568 KernelDType::C64 => {
569 uninit_broadcast_mul::<Complex64>(dest, &lhs, lhs_axes, &rhs, rhs_axes, exec)
570 }
571 KernelDType::I32 => {
572 uninit_broadcast_mul_wrapping::<i32>(dest, &lhs, lhs_axes, &rhs, rhs_axes, exec)
573 }
574 KernelDType::I64 => {
575 uninit_broadcast_mul_wrapping::<i64>(dest, &lhs, lhs_axes, &rhs, rhs_axes, exec)
576 }
577 _ => Err(StridedError::UnsupportedDType {
578 dtype: dtype.label(),
579 }),
580 }
581}
582
583/// Validate the destination layout and the input shapes.
584///
585/// Returns `None` for an empty destination, which needs no writes.
586fn prepare_destination(
587 dest: &ErasedRawStridedUninitMut<'_>,
588 inputs: &[&[usize]],
589) -> Result<Option<ValidatedDestinationLayout>> {
590 let validated = validate_destination_layout_without_alloc(dest.dims(), dest.strides())?;
591 for input_dims in inputs {
592 ensure_same_shape(dest.dims(), input_dims)?;
593 }
594 if dest.dims().contains(&0) {
595 Ok(None)
596 } else {
597 Ok(Some(validated))
598 }
599}
600
601fn uninit_raw_mut<'a, T: KernelStorageElement>(
602 dest: &'a mut ErasedRawStridedUninitMut<'_>,
603) -> Result<RawStridedMut<'a, MaybeUninit<T>>> {
604 let dims = dest.dims();
605 let strides = dest.strides();
606 let offset = dest.offset();
607 let data = dest.data_as_uninit_mut::<T>()?;
608 // SAFETY: `RawStridedMut::new_unchecked` (strided-view/src/raw.rs:1115) needs every index
609 // reachable from `offset` through `dims`/`strides` inside `data`, and no alias that breaks
610 // mutable access. When `dest` was built (`from_uninit_slice`, strided-view/src/raw.rs:794, or
611 // `from_raw_parts`, strided-view/src/raw.rs:850), `validate_bounds`
612 // (strided-view/src/view.rs:187) checked exactly these dims, strides and offset against its
613 // slot count, `byte_len / size_of::<T>()`, which is the length `data_as_uninit_mut`
614 // (strided-view/src/raw.rs:882) returns after checking the dtype. `data_as_uninit_mut`
615 // reborrows `dest` through `&mut`, and the result keeps that borrow (`'a`), so `data` is the
616 // only access to those `MaybeUninit<T>` slots.
617 Ok(unsafe { RawStridedMut::new_unchecked(data, dims, strides, offset) })
618}
619
620fn uninit_view_mut<'a, T: KernelStorageElement>(
621 dest: &'a mut ErasedRawStridedUninitMut<'_>,
622) -> Result<StridedViewMut<'a, MaybeUninit<T>>> {
623 let dims = dest.dims();
624 let strides = dest.strides();
625 let offset = dest.offset();
626 let data = dest.data_as_uninit_mut::<T>()?;
627 // SAFETY: `StridedViewMut::new_unchecked` (strided-view/src/view.rs:957) needs every index
628 // combination in bounds: the same `validate_bounds` argument as in `uninit_raw_mut`
629 // (erased/uninit.rs:601) covers these dims, strides and offset over `data`; the `&mut` slice
630 // type carries the exclusivity.
631 Ok(unsafe { StridedViewMut::new_unchecked(data, dims, strides, offset) })
632}
633
634fn erased_view<'a, T: KernelStorageElement>(
635 src: &'a ErasedRawStridedRef<'a>,
636) -> Result<StridedView<'a, T>> {
637 let data = src.data_as::<T>()?;
638 // SAFETY: `StridedView::new_unchecked` (strided-view/src/view.rs:517) needs every index
639 // combination in bounds. When `src` was built (`from_slice`, strided-view/src/raw.rs:420, or
640 // `from_raw_parts`, strided-view/src/raw.rs:473, which `try_as_ref_after_no_overlap` also
641 // uses), `validate_bounds` (strided-view/src/view.rs:187) checked exactly these dims, strides
642 // and offset against its element count, `byte_len / size_of::<T>()`. `data_as::<T>`
643 // (strided-view/src/raw.rs:503) checked that the dtype is `T` and returns exactly that many
644 // elements.
645 Ok(unsafe { StridedView::new_unchecked(data, src.dims(), src.strides(), src.offset()) })
646}
647
648fn uninit_map<T: OneShotScalar>(
649 op: ErasedMapOp,
650 dest: &mut ErasedRawStridedUninitMut<'_>,
651 input: &ErasedRawStridedRef<'_>,
652 exec: Exec<'_>,
653) -> Result<()> {
654 if !T::supports_map(op) {
655 return Err(StridedError::UnsupportedOp {
656 op: op.label(),
657 dtype: T::one_shot_dtype_label(),
658 });
659 }
660 // Select the operation once, outside the element loop, so each replay
661 // closure is monomorphic and the inner loop can vectorize.
662 match op {
663 ErasedMapOp::Negate => uninit_map_with::<T, T>(
664 dest,
665 input,
666 |value| T::map(ErasedMapOp::Negate, value),
667 exec,
668 ),
669 ErasedMapOp::Conj => {
670 uninit_map_with::<T, T>(dest, input, |value| T::map(ErasedMapOp::Conj, value), exec)
671 }
672 ErasedMapOp::Abs => {
673 uninit_map_with::<T, T>(dest, input, |value| T::map(ErasedMapOp::Abs, value), exec)
674 }
675 ErasedMapOp::Sign => {
676 uninit_map_with::<T, T>(dest, input, |value| T::map(ErasedMapOp::Sign, value), exec)
677 }
678 }
679}
680
681fn uninit_map_with<D, A>(
682 dest: &mut ErasedRawStridedUninitMut<'_>,
683 input: &ErasedRawStridedRef<'_>,
684 map: impl Fn(A) -> D + Sync,
685 exec: Exec<'_>,
686) -> Result<()>
687where
688 D: Copy + Send + Sync + KernelStorageElement,
689 A: Copy + Send + Sync + KernelStorageElement,
690{
691 let Some(validated) = prepare_destination(dest, &[input.dims()])? else {
692 return Ok(());
693 };
694 let input = erased_raw_ref::<A>(input)?;
695 let mut dest = uninit_raw_mut::<D>(dest)?;
696 // SAFETY: `map_raw_into_validated` (strided-basic/src/execution.rs:365) requires three
697 // things. Every input shape matches the destination, and `validated` belongs to this
698 // destination's geometry: `prepare_destination` (erased/uninit.rs:586) ran
699 // `ensure_same_shape` on `input.dims()` and produced `validated` from
700 // `dest.dims()`/`dest.strides()`, the geometry `uninit_raw_mut` rebuilds `dest` with. Bounds
701 // and aliasing hold throughout the replay: the inputs come from `erased_raw_ref`, bounded by
702 // their descriptors' `validate_bounds` (strided-view/src/view.rs:187), `dest` is bounded as
703 // argued in `uninit_raw_mut` (erased/uninit.rs:601), and the public entry rejected
704 // input/output overlap before converting the inputs (erased/uninit.rs:75). The closure only
705 // writes `MaybeUninit::new(..)`, so no uninitialized slot is read.
706 unsafe {
707 map_raw_into_validated::<MaybeUninit<D>, A, Identity>(
708 &mut dest,
709 &input,
710 |value| MaybeUninit::new(map(value)),
711 validated,
712 exec,
713 )
714 }
715}
716
717fn uninit_zip<T: OneShotScalar>(
718 op: ErasedZipOp,
719 dest: &mut ErasedRawStridedUninitMut<'_>,
720 lhs: &ErasedRawStridedRef<'_>,
721 rhs: &ErasedRawStridedRef<'_>,
722 exec: Exec<'_>,
723) -> Result<()> {
724 if !T::supports_zip(op) {
725 return Err(StridedError::UnsupportedOp {
726 op: op.label(),
727 dtype: T::one_shot_dtype_label(),
728 });
729 }
730 let Some(validated) = prepare_destination(dest, &[lhs.dims(), rhs.dims()])? else {
731 return Ok(());
732 };
733 let lhs = erased_raw_ref::<T>(lhs)?;
734 let rhs = erased_raw_ref::<T>(rhs)?;
735 if matches!(op, ErasedZipOp::Divide | ErasedZipOp::Remainder)
736 && T::INTEGER
737 && raw_any(&rhs, T::is_zero)?
738 {
739 return Err(StridedError::IntegerDivisionByZero { op: op.label() });
740 }
741 let mut dest = uninit_raw_mut::<T>(dest)?;
742 // Select the operation once, outside the element loop, so each replay
743 // closure is monomorphic and the inner loop can vectorize.
744 macro_rules! replay {
745 ($op:ident) => {
746 // SAFETY: `zip_map2_raw_into_validated` (strided-basic/src/execution.rs:413) requires
747 // three things. Every input shape matches the destination, and `validated` belongs to
748 // this destination's geometry: `prepare_destination` (erased/uninit.rs:586) ran
749 // `ensure_same_shape` on both input shapes and produced `validated` from
750 // `dest.dims()`/`dest.strides()`, the geometry `uninit_raw_mut` rebuilds `dest` with.
751 // Bounds and aliasing hold throughout the replay: the inputs come from
752 // `erased_raw_ref`, bounded by their descriptors' `validate_bounds`
753 // (strided-view/src/view.rs:187), `dest` is bounded as argued in `uninit_raw_mut`
754 // (erased/uninit.rs:601), and the public entry rejected input/output overlap before
755 // converting the inputs (erased/uninit.rs:168 and erased/uninit.rs:169). The closure
756 // only writes `MaybeUninit::new(..)`, so no uninitialized slot is read.
757 unsafe {
758 zip_map2_raw_into_validated::<MaybeUninit<T>, T, T, Identity, Identity>(
759 &mut dest,
760 &lhs,
761 &rhs,
762 |lhs, rhs| MaybeUninit::new(T::zip(ErasedZipOp::$op, lhs, rhs)),
763 validated,
764 exec,
765 )
766 }
767 };
768 }
769 match op {
770 ErasedZipOp::Add => replay!(Add),
771 ErasedZipOp::Subtract => replay!(Subtract),
772 ErasedZipOp::Multiply => replay!(Multiply),
773 ErasedZipOp::Divide => replay!(Divide),
774 ErasedZipOp::Remainder => replay!(Remainder),
775 ErasedZipOp::Maximum => replay!(Maximum),
776 ErasedZipOp::Minimum => replay!(Minimum),
777 }
778}
779
780fn uninit_compare_with<T>(
781 dest: &mut ErasedRawStridedUninitMut<'_>,
782 lhs: &ErasedRawStridedRef<'_>,
783 rhs: &ErasedRawStridedRef<'_>,
784 compare: impl Fn(T, T) -> bool + Sync,
785 exec: Exec<'_>,
786) -> Result<()>
787where
788 T: Copy + Send + Sync + KernelStorageElement,
789{
790 let Some(validated) = prepare_destination(dest, &[lhs.dims(), rhs.dims()])? else {
791 return Ok(());
792 };
793 let lhs = erased_raw_ref::<T>(lhs)?;
794 let rhs = erased_raw_ref::<T>(rhs)?;
795 let mut dest = uninit_raw_mut::<bool>(dest)?;
796 // SAFETY: `zip_map2_raw_into_validated` (strided-basic/src/execution.rs:413) requires three
797 // things. Every input shape matches the destination, and `validated` belongs to this
798 // destination's geometry: `prepare_destination` (erased/uninit.rs:586) ran
799 // `ensure_same_shape` on both input shapes and produced `validated` from
800 // `dest.dims()`/`dest.strides()`, the geometry `uninit_raw_mut` rebuilds `dest` with. Bounds
801 // and aliasing hold throughout the replay: the inputs come from `erased_raw_ref`, bounded by
802 // their descriptors' `validate_bounds` (strided-view/src/view.rs:187), `dest` is bounded as
803 // argued in `uninit_raw_mut` (erased/uninit.rs:601), and the public entry rejected
804 // input/output overlap before converting the inputs (erased/uninit.rs:258 and
805 // erased/uninit.rs:259). The closure only writes `MaybeUninit::new(..)`, so no uninitialized
806 // slot is read.
807 unsafe {
808 zip_map2_raw_into_validated::<MaybeUninit<bool>, T, T, Identity, Identity>(
809 &mut dest,
810 &lhs,
811 &rhs,
812 |lhs, rhs| MaybeUninit::new(compare(lhs, rhs)),
813 validated,
814 exec,
815 )
816 }
817}
818
819fn uninit_compare_ordered<T>(
820 op: CompareOp,
821 dest: &mut ErasedRawStridedUninitMut<'_>,
822 lhs: &ErasedRawStridedRef<'_>,
823 rhs: &ErasedRawStridedRef<'_>,
824 exec: Exec<'_>,
825) -> Result<()>
826where
827 T: Copy + Send + Sync + KernelStorageElement + PartialOrd,
828{
829 // The comparison is selected once, outside the element loop.
830 match op {
831 CompareOp::Eq => uninit_compare_with::<T>(dest, lhs, rhs, |a, b| a == b, exec),
832 CompareOp::Lt => uninit_compare_with::<T>(dest, lhs, rhs, |a, b| a < b, exec),
833 CompareOp::Le => uninit_compare_with::<T>(dest, lhs, rhs, |a, b| a <= b, exec),
834 CompareOp::Gt => uninit_compare_with::<T>(dest, lhs, rhs, |a, b| a > b, exec),
835 CompareOp::Ge => uninit_compare_with::<T>(dest, lhs, rhs, |a, b| a >= b, exec),
836 _ => Err(StridedError::UnsupportedOp {
837 op: compare_label(op),
838 dtype: T::DTYPE.label(),
839 }),
840 }
841}
842
843fn uninit_compare_eq<T>(
844 op: CompareOp,
845 dest: &mut ErasedRawStridedUninitMut<'_>,
846 lhs: &ErasedRawStridedRef<'_>,
847 rhs: &ErasedRawStridedRef<'_>,
848 exec: Exec<'_>,
849) -> Result<()>
850where
851 T: Copy + Send + Sync + KernelStorageElement + PartialEq,
852{
853 match op {
854 CompareOp::Eq => uninit_compare_with::<T>(dest, lhs, rhs, |a, b| a == b, exec),
855 _ => Err(StridedError::UnsupportedOp {
856 op: compare_label(op),
857 dtype: T::DTYPE.label(),
858 }),
859 }
860}
861
862fn compare_label(op: CompareOp) -> &'static str {
863 match op {
864 CompareOp::Eq => "eq",
865 CompareOp::Lt => "lt",
866 CompareOp::Le => "le",
867 CompareOp::Gt => "gt",
868 CompareOp::Ge => "ge",
869 _ => "compare",
870 }
871}
872
873fn uninit_select<T>(
874 dest: &mut ErasedRawStridedUninitMut<'_>,
875 pred: &ErasedRawStridedRef<'_>,
876 on_true: &ErasedRawStridedRef<'_>,
877 on_false: &ErasedRawStridedRef<'_>,
878 exec: Exec<'_>,
879) -> Result<()>
880where
881 T: Copy + Send + Sync + KernelStorageElement,
882{
883 let dims: [&[usize]; 3] = [pred.dims(), on_true.dims(), on_false.dims()];
884 if prepare_destination(dest, &dims)?.is_none() {
885 return Ok(());
886 }
887 let pred = erased_view::<bool>(pred)?;
888 let on_true = erased_view::<T>(on_true)?;
889 let on_false = erased_view::<T>(on_false)?;
890 let mut dest = uninit_view_mut::<T>(dest)?;
891 zip_map3_into(
892 &mut dest,
893 &pred,
894 &on_true,
895 &on_false,
896 |pred, a, b| MaybeUninit::new(if pred { a } else { b }),
897 exec,
898 )
899}
900
901fn uninit_clamp<T: OneShotScalar>(
902 dest: &mut ErasedRawStridedUninitMut<'_>,
903 x: &ErasedRawStridedRef<'_>,
904 lo: &ErasedRawStridedRef<'_>,
905 hi: &ErasedRawStridedRef<'_>,
906 exec: Exec<'_>,
907) -> Result<()> {
908 let dims: [&[usize]; 3] = [x.dims(), lo.dims(), hi.dims()];
909 if prepare_destination(dest, &dims)?.is_none() {
910 return Ok(());
911 }
912 let x = erased_view::<T>(x)?;
913 let lo = erased_view::<T>(lo)?;
914 let hi = erased_view::<T>(hi)?;
915 let mut dest = uninit_view_mut::<T>(dest)?;
916 zip_map3_into(
917 &mut dest,
918 &x,
919 &lo,
920 &hi,
921 |x, lo, hi| MaybeUninit::new(T::clamp(x, lo, hi)),
922 exec,
923 )
924}
925
926fn uninit_broadcast_mul<T>(
927 dest: &mut ErasedRawStridedUninitMut<'_>,
928 lhs: &ErasedRawStridedRef<'_>,
929 lhs_axes: &[usize],
930 rhs: &ErasedRawStridedRef<'_>,
931 rhs_axes: &[usize],
932 exec: Exec<'_>,
933) -> Result<()>
934where
935 T: Copy + Send + Sync + KernelStorageElement + core::ops::Mul<Output = T>,
936{
937 let lhs = erased_view::<T>(lhs)?;
938 let rhs = erased_view::<T>(rhs)?;
939 let mut dest = uninit_view_mut::<T>(dest)?;
940 broadcast_mul_into_uninit(&mut dest, &lhs, lhs_axes, &rhs, rhs_axes, exec)
941}
942
943fn uninit_broadcast_mul_wrapping<T>(
944 dest: &mut ErasedRawStridedUninitMut<'_>,
945 lhs: &ErasedRawStridedRef<'_>,
946 lhs_axes: &[usize],
947 rhs: &ErasedRawStridedRef<'_>,
948 rhs_axes: &[usize],
949 exec: Exec<'_>,
950) -> Result<()>
951where
952 T: Copy + Send + Sync + KernelStorageElement,
953 Wrapping<T>: core::ops::Mul<Output = Wrapping<T>> + Send + Sync,
954{
955 let lhs_data = wrapping_slice(lhs.data_as::<T>()?);
956 let rhs_data = wrapping_slice(rhs.data_as::<T>()?);
957 // SAFETY: `StridedView::new_unchecked` (strided-view/src/view.rs:517) needs every index
958 // combination in bounds. `lhs` validated these dims, strides and offset against its element
959 // count when it was built (`validate_bounds`, strided-view/src/view.rs:187); `data_as::<T>`
960 // (strided-view/src/raw.rs:503) returned exactly that many elements, and `wrapping_slice`
961 // (erased/uninit.rs:1003) keeps the count.
962 let lhs = unsafe {
963 StridedView::<Wrapping<T>, Identity>::new_unchecked(
964 lhs_data,
965 lhs.dims(),
966 lhs.strides(),
967 lhs.offset(),
968 )
969 };
970 // SAFETY: as for `lhs` above, with `rhs`'s own construction-time `validate_bounds`.
971 let rhs = unsafe {
972 StridedView::<Wrapping<T>, Identity>::new_unchecked(
973 rhs_data,
974 rhs.dims(),
975 rhs.strides(),
976 rhs.offset(),
977 )
978 };
979 let dims = dest.dims();
980 let strides = dest.strides();
981 let offset = dest.offset();
982 let data = dest.data_as_uninit_mut::<T>()?;
983 // SAFETY: `slice::from_raw_parts_mut` needs a pointer valid for `data.len()` elements of the
984 // new type, properly aligned, with no other access for the slice's lifetime. `Wrapping<T>` is
985 // documented `#[repr(transparent)]` over `T`, so `MaybeUninit<Wrapping<T>>` has the size and
986 // alignment of `MaybeUninit<T>`, and every bit pattern stays valid. The pointer and length
987 // come from the exclusive slice `data_as_uninit_mut` returned, which is shadowed here and not
988 // used again.
989 let data = unsafe {
990 core::slice::from_raw_parts_mut(
991 data.as_mut_ptr().cast::<MaybeUninit<Wrapping<T>>>(),
992 data.len(),
993 )
994 };
995 // SAFETY: `StridedViewMut::new_unchecked` (strided-view/src/view.rs:957) needs every index
996 // combination in bounds: `dest` validated these dims, strides and offset against its slot
997 // count when it was built (`validate_bounds`, strided-view/src/view.rs:187), and the
998 // reinterpreted slice above keeps that count.
999 let mut dest = unsafe { StridedViewMut::new_unchecked(data, dims, strides, offset) };
1000 broadcast_mul_into_uninit(&mut dest, &lhs, lhs_axes, &rhs, rhs_axes, exec)
1001}
1002
1003fn wrapping_slice<T>(data: &[T]) -> &[Wrapping<T>] {
1004 // SAFETY: `slice::from_raw_parts` needs a pointer valid for `data.len()` elements of the new
1005 // type, properly aligned, for the borrow's lifetime. `Wrapping<T>` is documented
1006 // `#[repr(transparent)]` over `T`, so it has `T`'s size, alignment and valid bit patterns;
1007 // the result reborrows `data` with the same lifetime and count.
1008 unsafe { core::slice::from_raw_parts(data.as_ptr().cast::<Wrapping<T>>(), data.len()) }
1009}