Skip to main content

strided_basic/
ops_view.rs

1//! High-level operations on dynamic-rank strided views.
2
3use crate::kernel::{
4    ensure_same_shape, for_each_inner_block_preordered, for_each_pointwise_block_preordered,
5    pointwise_plan, same_contiguous_layout, sequential_contiguous_layout, total_len,
6};
7use crate::map_view::{copy_map_into, map_into, validate_destination_layout, zip_map2_into};
8use crate::reduce_view::reduce;
9use crate::simd;
10use crate::view::{StridedView, StridedViewMut};
11use crate::{Exec, Result, StridedError};
12use num_traits::{One, Zero};
13use std::mem::MaybeUninit;
14use std::ops::{Add, Mul};
15use strided_view::{ElementOp, ElementOpApply};
16
17use crate::cost::KernelClass;
18use crate::fuse::compute_costs;
19use crate::threading::{is_parallel, mapreduce_threaded, SendPtr};
20// ============================================================================
21// Stride-specialized inner loop helpers for ops_view
22//
23// When all inner strides are 1 (contiguous in the innermost dimension),
24// we use slice-based iteration so LLVM can auto-vectorize effectively.
25// This mirrors the inner_loop_map* helpers in map_view.rs.
26// ============================================================================
27
28// INVARIANT: validated layouts keep all dereferences in bounds. Wrapping
29// advances permit an unused final cursor outside a reversed/gapped allocation.
30/// Inner loop for `add_acc`: `dst[i] += Op::apply(src[i])`.
31#[inline(always)]
32unsafe fn inner_loop_add<D: Copy + Add<S, Output = D>, S: Copy, Op: ElementOp<S>>(
33    dp: *mut D,
34    ds: isize,
35    sp: *const S,
36    ss: isize,
37    len: usize,
38) {
39    if ds == 1 && ss == 1 {
40        let dst = std::slice::from_raw_parts_mut(dp, len);
41        let src = std::slice::from_raw_parts(sp, len);
42        simd::dispatch_if_large(len, || {
43            for i in 0..len {
44                dst[i] = dst[i] + Op::apply(src[i]);
45            }
46        });
47    } else {
48        let mut dp = dp;
49        let mut sp = sp;
50        for _ in 0..len {
51            *dp = *dp + Op::apply(*sp);
52            dp = dp.wrapping_offset(ds);
53            sp = sp.wrapping_offset(ss);
54        }
55    }
56}
57
58/// Inner loop for `mul_acc`: `dst[i] *= Op::apply(src[i])`.
59#[inline(always)]
60unsafe fn inner_loop_mul<D: Copy + Mul<S, Output = D>, S: Copy, Op: ElementOp<S>>(
61    dp: *mut D,
62    ds: isize,
63    sp: *const S,
64    ss: isize,
65    len: usize,
66) {
67    if ds == 1 && ss == 1 {
68        let dst = std::slice::from_raw_parts_mut(dp, len);
69        let src = std::slice::from_raw_parts(sp, len);
70        simd::dispatch_if_large(len, || {
71            for i in 0..len {
72                dst[i] = dst[i] * Op::apply(src[i]);
73            }
74        });
75    } else {
76        let mut dp = dp;
77        let mut sp = sp;
78        for _ in 0..len {
79            *dp = *dp * Op::apply(*sp);
80            dp = dp.wrapping_offset(ds);
81            sp = sp.wrapping_offset(ss);
82        }
83    }
84}
85
86/// Inner loop for `axpy_acc`: `dst[i] = alpha * Op::apply(src[i]) + dst[i]`.
87#[inline(always)]
88unsafe fn inner_loop_axpy<
89    D: Copy + Add<D, Output = D>,
90    S: Copy,
91    A: Copy + Mul<S, Output = D>,
92    Op: ElementOp<S>,
93>(
94    dp: *mut D,
95    ds: isize,
96    sp: *const S,
97    ss: isize,
98    len: usize,
99    alpha: A,
100) {
101    if ds == 1 && ss == 1 {
102        let dst = std::slice::from_raw_parts_mut(dp, len);
103        let src = std::slice::from_raw_parts(sp, len);
104        simd::dispatch_if_large(len, || {
105            for i in 0..len {
106                dst[i] = alpha * Op::apply(src[i]) + dst[i];
107            }
108        });
109    } else {
110        let mut dp = dp;
111        let mut sp = sp;
112        for _ in 0..len {
113            *dp = alpha * Op::apply(*sp) + *dp;
114            dp = dp.wrapping_offset(ds);
115            sp = sp.wrapping_offset(ss);
116        }
117    }
118}
119
120/// Inner loop for `fma_acc`: `dst[i] += OpA::apply(a[i]) * OpB::apply(b[i])`.
121#[inline(always)]
122unsafe fn inner_loop_fma<
123    D: Copy + Add<D, Output = D>,
124    A: Copy + Mul<B, Output = D>,
125    B: Copy,
126    OpA: ElementOp<A>,
127    OpB: ElementOp<B>,
128>(
129    dp: *mut D,
130    ds: isize,
131    ap: *const A,
132    a_s: isize,
133    bp: *const B,
134    b_s: isize,
135    len: usize,
136) {
137    if ds == 1 && a_s == 1 && b_s == 1 {
138        let dst = std::slice::from_raw_parts_mut(dp, len);
139        let sa = std::slice::from_raw_parts(ap, len);
140        let sb = std::slice::from_raw_parts(bp, len);
141        simd::dispatch_if_large(len, || {
142            for i in 0..len {
143                dst[i] = dst[i] + OpA::apply(sa[i]) * OpB::apply(sb[i]);
144            }
145        });
146    } else {
147        let mut dp = dp;
148        let mut ap = ap;
149        let mut bp = bp;
150        for _ in 0..len {
151            *dp = *dp + OpA::apply(*ap) * OpB::apply(*bp);
152            dp = dp.wrapping_offset(ds);
153            ap = ap.wrapping_offset(a_s);
154            bp = bp.wrapping_offset(b_s);
155        }
156    }
157}
158
159/// Inner loop for dot: `acc += OpA::apply(a[i]) * OpB::apply(b[i])`.
160#[inline(always)]
161unsafe fn inner_loop_dot<
162    A: Copy + Mul<B, Output = R>,
163    B: Copy,
164    R: Copy + Add<R, Output = R>,
165    OpA: ElementOp<A>,
166    OpB: ElementOp<B>,
167>(
168    ap: *const A,
169    a_s: isize,
170    bp: *const B,
171    b_s: isize,
172    len: usize,
173    mut acc: R,
174) -> R {
175    if a_s == 1 && b_s == 1 {
176        let sa = std::slice::from_raw_parts(ap, len);
177        let sb = std::slice::from_raw_parts(bp, len);
178        simd::dispatch_if_large(len, || {
179            for i in 0..len {
180                acc = acc + OpA::apply(sa[i]) * OpB::apply(sb[i]);
181            }
182        });
183    } else {
184        let mut ap = ap;
185        let mut bp = bp;
186        for _ in 0..len {
187            acc = acc + OpA::apply(*ap) * OpB::apply(*bp);
188            ap = ap.wrapping_offset(a_s);
189            bp = bp.wrapping_offset(b_s);
190        }
191    }
192    acc
193}
194
195/// Copy elements from source to destination: `dest[i] = src[i]`.
196///
197/// # Errors
198///
199/// Returns [`StridedError::RankMismatch`] or
200/// [`StridedError::ShapeMismatch`] when the views describe different
201/// extents, and [`StridedError::OffsetOverflow`] when the element count of
202/// the shape does not fit in `usize`. The generic element path also returns
203/// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
204/// cannot be proven representable and injective: two logical indices name
205/// one offset, or the address span is too large to represent. Nothing is
206/// written unless validation succeeds.
207pub fn copy_into<T: Copy + Send + Sync, Op: ElementOp<T>>(
208    dest: &mut StridedViewMut<T>,
209    src: &StridedView<T, Op>,
210    exec: Exec<'_>,
211) -> Result<()> {
212    ensure_same_shape(dest.dims(), src.dims())?;
213
214    let dst_ptr = dest.as_mut_ptr();
215    let src_ptr = src.ptr();
216    let dst_dims = dest.dims();
217    let dst_strides = dest.strides();
218    let src_strides = src.strides();
219
220    if sequential_contiguous_layout(
221        KernelClass::Copy,
222        dst_dims,
223        &[dst_strides, src_strides],
224        &exec,
225    )?
226    .is_some()
227    {
228        let len = total_len(dst_dims)?;
229        if Op::IS_IDENTITY {
230            debug_assert!(
231                {
232                    let nbytes = len
233                        .checked_mul(std::mem::size_of::<T>())
234                        .expect("copy size must not overflow");
235                    let dst_start = dst_ptr as usize;
236                    let src_start = src_ptr as usize;
237                    let dst_end = dst_start.saturating_add(nbytes);
238                    let src_end = src_start.saturating_add(nbytes);
239                    dst_end <= src_start || src_end <= dst_start
240                },
241                "overlapping src/dest is not supported"
242            );
243            unsafe { std::ptr::copy_nonoverlapping(src_ptr, dst_ptr, len) };
244        } else {
245            let dst = unsafe { std::slice::from_raw_parts_mut(dst_ptr, len) };
246            let src = unsafe { std::slice::from_raw_parts(src_ptr, len) };
247            simd::dispatch_if_large(len, || {
248                for i in 0..len {
249                    dst[i] = Op::apply(src[i]);
250                }
251            });
252        }
253        return Ok(());
254    }
255
256    copy_map_into(dest, src, |x| x, exec)
257}
258
259/// Copy initialized values into a potentially uninitialized destination.
260///
261/// On success every logical destination element is initialized; holes are
262/// untouched. Accepts identity views; use `map_into` for element operations
263/// such as conjugation. Equal contiguous f32/f64 layouts and every other type
264/// keep the element map; a non-contiguous f32/f64 copy uses the permutation
265/// engine, split within the budget of `exec`.
266///
267/// # Errors
268/// Returns a shape/rank error for mismatched views, `NonInjectiveOutputLayout`
269/// for overlapping destination elements, or `OffsetOverflow` for size overflow.
270///
271/// # Examples
272/// ```
273/// use std::mem::MaybeUninit;
274/// use strided_basic::{copy_into_uninit, Exec, StridedView, StridedViewMut};
275/// let src = [1.0_f64, 2.0];
276/// let mut dst = [MaybeUninit::uninit(); 2];
277/// copy_into_uninit(
278///     &mut StridedViewMut::new(&mut dst, &[2], &[1], 0).unwrap(),
279///     &StridedView::new(&src, &[2], &[1], 0).unwrap(),
280///     Exec::serial(),
281/// ).unwrap();
282/// // SAFETY: the successful copy initialized both destination elements.
283/// assert_eq!(unsafe { dst[1].assume_init() }, 2.0);
284/// ```
285pub fn copy_into_uninit<T: Copy + Send + Sync + 'static>(
286    dest: &mut StridedViewMut<MaybeUninit<T>>,
287    src: &StridedView<T>,
288    exec: Exec<'_>,
289) -> Result<()> {
290    ensure_same_shape(dest.dims(), src.dims())?;
291    if !crate::layout_check::is_injective_layout(dest.dims(), dest.strides()) {
292        return Err(StridedError::NonInjectiveOutputLayout);
293    }
294    if src.is_empty() {
295        return Ok(());
296    }
297    let _len = src
298        .dims()
299        .iter()
300        .try_fold(1usize, |n, &dim| n.checked_mul(dim))
301        .ok_or(StridedError::OffsetOverflow)?;
302    // The permutation engine's 4/8-byte paths reinterpret storage as native
303    // floats. Restrict that path to those exact types: arbitrary Copy types can
304    // contain uninitialized padding or have weaker alignment (e.g. Complex32).
305    let native_float = std::any::TypeId::of::<T>() == std::any::TypeId::of::<f32>()
306        || std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>();
307    // Equal contiguous layouts go to the element map, whose contiguous path
308    // parallelizes a large copy; the permutation engine has only a serial
309    // contiguous shortcut. Non-contiguous native-float copies use the
310    // permutation engine, serial or parallel.
311    if !native_float
312        || same_contiguous_layout(dest.dims(), &[dest.strides(), src.strides()]).is_some()
313    {
314        return copy_map_into(dest, src, MaybeUninit::new, exec);
315    }
316    // INVARIANT: the permutation engine selects its float paths by the
317    // source element type and only stores into the destination, so an
318    // uninitialized destination with an initialized source is valid.
319    crate::threading::copy_permuted_uninit(dest, src, exec)
320}
321
322/// Copy elements from `src` to `dst`, optimized for col-major destination.
323///
324/// Delegates to the centralized permutation-copy dispatch for the actual work,
325/// inside the budget of `exec`: the same explicit-token contract as
326/// [`copy_into`], so a large copy splits across the token's slots instead of
327/// always staying on the calling thread (strided-rs#212).
328///
329/// # Errors
330///
331/// The rejection set of that dispatch: [`StridedError::RankMismatch`] or
332/// [`StridedError::ShapeMismatch`] when the views describe different
333/// extents, [`StridedError::OffsetOverflow`] when the layout cannot be
334/// expressed in `isize` stride arithmetic or a fused extent overflows, and
335/// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
336/// cannot be proven representable and injective. Nothing is written unless
337/// validation succeeds.
338pub fn copy_into_col_major<T: Copy + Send + Sync + 'static>(
339    dst: &mut StridedViewMut<T>,
340    src: &StridedView<T>,
341    exec: Exec<'_>,
342) -> Result<()> {
343    strided_perm::copy_into_col_major(dst, src, exec)
344}
345
346/// Accumulating element-wise addition: `dest[i] += src[i]`.
347///
348/// Source may have a different element type from destination.
349///
350/// # Errors
351///
352/// Returns [`StridedError::RankMismatch`] or
353/// [`StridedError::ShapeMismatch`] when the views describe different
354/// extents, and [`StridedError::OffsetOverflow`] when the element count of
355/// the shape does not fit in `usize`. Every check runs before the first
356/// write, so a rejected call leaves `dest` untouched.
357///
358/// # Destination contract
359///
360/// [`StridedError::NonInjectiveOutputLayout`] when two logical indices of
361/// `dest` name the same element (for example a stride-0 broadcast axis of
362/// extent above one): the update reads and writes `dest`, so an aliased
363/// destination would be order-dependent, and a race under a threaded `exec`.
364pub fn add_acc<
365    D: Copy + Add<S, Output = D> + Send + Sync,
366    S: Copy + Send + Sync,
367    Op: ElementOp<S>,
368>(
369    dest: &mut StridedViewMut<D>,
370    src: &StridedView<S, Op>,
371    exec: Exec<'_>,
372) -> Result<()> {
373    ensure_same_shape(dest.dims(), src.dims())?;
374    validate_destination_layout(dest.dims(), dest.strides())?;
375
376    let dst_ptr = dest.as_mut_ptr();
377    let src_ptr = src.ptr();
378    let dst_dims = dest.dims();
379    let dst_strides = dest.strides();
380    let src_strides = src.strides();
381
382    if sequential_contiguous_layout(
383        KernelClass::Map,
384        dst_dims,
385        &[dst_strides, src_strides],
386        &exec,
387    )?
388    .is_some()
389    {
390        let len = total_len(dst_dims)?;
391        let dst = unsafe { std::slice::from_raw_parts_mut(dst_ptr, len) };
392        let src = unsafe { std::slice::from_raw_parts(src_ptr, len) };
393        simd::dispatch_if_large(len, || {
394            for i in 0..len {
395                dst[i] = dst[i] + Op::apply(src[i]);
396            }
397        });
398        return Ok(());
399    }
400
401    let strides_list: [&[isize]; 2] = [dst_strides, src_strides];
402    let total = total_len(dst_dims)?;
403    let (fused_dims, ordered_strides, plan) = pointwise_plan(
404        dst_dims,
405        &strides_list,
406        Some(0),
407        &[std::mem::size_of::<D>(), std::mem::size_of::<S>()],
408        total,
409    );
410
411    let total = total_len(&fused_dims)?;
412    if is_parallel(KernelClass::Map, total, &exec) {
413        let dst_send = SendPtr(dst_ptr);
414        let src_send = SendPtr(src_ptr as *mut S);
415
416        let costs = compute_costs(&ordered_strides);
417        let initial_offsets: crate::inline::OperandVec<isize> =
418            strides_list.iter().map(|_| 0isize).collect();
419        return mapreduce_threaded(
420            &fused_dims,
421            &plan.block,
422            &ordered_strides,
423            &initial_offsets,
424            &costs,
425            KernelClass::Map,
426            exec,
427            &|dims, blocks, strides_list, offsets| {
428                for_each_pointwise_block_preordered(
429                    dims,
430                    blocks,
431                    strides_list,
432                    offsets,
433                    |offsets, len, strides| {
434                        unsafe {
435                            inner_loop_add::<D, S, Op>(
436                                dst_send.as_ptr().offset(offsets[0]),
437                                strides[0],
438                                src_send.as_const().offset(offsets[1]),
439                                strides[1],
440                                len,
441                            )
442                        };
443                        Ok(())
444                    },
445                )
446            },
447        );
448    }
449
450    let initial_offsets: crate::inline::OperandVec<isize> =
451        ordered_strides.iter().map(|_| 0isize).collect();
452    for_each_pointwise_block_preordered(
453        &fused_dims,
454        &plan.block,
455        &ordered_strides,
456        &initial_offsets,
457        |offsets, len, strides| {
458            unsafe {
459                inner_loop_add::<D, S, Op>(
460                    dst_ptr.offset(offsets[0]),
461                    strides[0],
462                    src_ptr.offset(offsets[1]),
463                    strides[1],
464                    len,
465                )
466            };
467            Ok(())
468        },
469    )
470}
471
472/// Accumulating element-wise multiplication: `dest[i] *= src[i]`.
473///
474/// Source may have a different element type from destination.
475///
476/// # Errors
477///
478/// Returns [`StridedError::RankMismatch`] or
479/// [`StridedError::ShapeMismatch`] when the views describe different
480/// extents, and [`StridedError::OffsetOverflow`] when the element count of
481/// the shape does not fit in `usize`. Every check runs before the first
482/// write, so a rejected call leaves `dest` untouched.
483///
484/// # Destination contract
485///
486/// [`StridedError::NonInjectiveOutputLayout`] when two logical indices of
487/// `dest` name the same element (for example a stride-0 broadcast axis of
488/// extent above one): the update reads and writes `dest`, so an aliased
489/// destination would be order-dependent, and a race under a threaded `exec`.
490pub fn mul_acc<
491    D: Copy + Mul<S, Output = D> + Send + Sync,
492    S: Copy + Send + Sync,
493    Op: ElementOp<S>,
494>(
495    dest: &mut StridedViewMut<D>,
496    src: &StridedView<S, Op>,
497    exec: Exec<'_>,
498) -> Result<()> {
499    ensure_same_shape(dest.dims(), src.dims())?;
500    validate_destination_layout(dest.dims(), dest.strides())?;
501
502    let dst_ptr = dest.as_mut_ptr();
503    let src_ptr = src.ptr();
504    let dst_dims = dest.dims();
505    let dst_strides = dest.strides();
506    let src_strides = src.strides();
507
508    if sequential_contiguous_layout(
509        KernelClass::Map,
510        dst_dims,
511        &[dst_strides, src_strides],
512        &exec,
513    )?
514    .is_some()
515    {
516        let len = total_len(dst_dims)?;
517        let dst = unsafe { std::slice::from_raw_parts_mut(dst_ptr, len) };
518        let src = unsafe { std::slice::from_raw_parts(src_ptr, len) };
519        simd::dispatch_if_large(len, || {
520            for i in 0..len {
521                dst[i] = dst[i] * Op::apply(src[i]);
522            }
523        });
524        return Ok(());
525    }
526
527    let strides_list: [&[isize]; 2] = [dst_strides, src_strides];
528    let total = total_len(dst_dims)?;
529    let (fused_dims, ordered_strides, plan) = pointwise_plan(
530        dst_dims,
531        &strides_list,
532        Some(0),
533        &[std::mem::size_of::<D>(), std::mem::size_of::<S>()],
534        total,
535    );
536
537    let total = total_len(&fused_dims)?;
538    if is_parallel(KernelClass::Map, total, &exec) {
539        let dst_send = SendPtr(dst_ptr);
540        let src_send = SendPtr(src_ptr as *mut S);
541
542        let costs = compute_costs(&ordered_strides);
543        let initial_offsets: crate::inline::OperandVec<isize> =
544            strides_list.iter().map(|_| 0isize).collect();
545        return mapreduce_threaded(
546            &fused_dims,
547            &plan.block,
548            &ordered_strides,
549            &initial_offsets,
550            &costs,
551            KernelClass::Map,
552            exec,
553            &|dims, blocks, strides_list, offsets| {
554                for_each_pointwise_block_preordered(
555                    dims,
556                    blocks,
557                    strides_list,
558                    offsets,
559                    |offsets, len, strides| {
560                        unsafe {
561                            inner_loop_mul::<D, S, Op>(
562                                dst_send.as_ptr().offset(offsets[0]),
563                                strides[0],
564                                src_send.as_const().offset(offsets[1]),
565                                strides[1],
566                                len,
567                            )
568                        };
569                        Ok(())
570                    },
571                )
572            },
573        );
574    }
575
576    let initial_offsets: crate::inline::OperandVec<isize> =
577        ordered_strides.iter().map(|_| 0isize).collect();
578    for_each_pointwise_block_preordered(
579        &fused_dims,
580        &plan.block,
581        &ordered_strides,
582        &initial_offsets,
583        |offsets, len, strides| {
584            unsafe {
585                inner_loop_mul::<D, S, Op>(
586                    dst_ptr.offset(offsets[0]),
587                    strides[0],
588                    src_ptr.offset(offsets[1]),
589                    strides[1],
590                    len,
591                )
592            };
593            Ok(())
594        },
595    )
596}
597
598/// Accumulating AXPY: `dest[i] = alpha * src[i] + dest[i]`.
599///
600/// Alpha, source, and destination may have different element types.
601///
602/// # Errors
603///
604/// Returns [`StridedError::RankMismatch`] or
605/// [`StridedError::ShapeMismatch`] when the views describe different
606/// extents, and [`StridedError::OffsetOverflow`] when the element count of
607/// the shape does not fit in `usize`. Every check runs before the first
608/// write, so a rejected call leaves `dest` untouched.
609///
610/// # Destination contract
611///
612/// [`StridedError::NonInjectiveOutputLayout`] when two logical indices of
613/// `dest` name the same element (for example a stride-0 broadcast axis of
614/// extent above one): the update reads and writes `dest`, so an aliased
615/// destination would be order-dependent, and a race under a threaded `exec`.
616pub fn axpy_acc<D, S, A, Op>(
617    dest: &mut StridedViewMut<D>,
618    src: &StridedView<S, Op>,
619    alpha: A,
620    exec: Exec<'_>,
621) -> Result<()>
622where
623    A: Copy + Mul<S, Output = D> + Sync,
624    D: Copy + Add<D, Output = D> + Send + Sync,
625    S: Copy + Send + Sync,
626    Op: ElementOp<S>,
627{
628    ensure_same_shape(dest.dims(), src.dims())?;
629    validate_destination_layout(dest.dims(), dest.strides())?;
630
631    let dst_ptr = dest.as_mut_ptr();
632    let src_ptr = src.ptr();
633    let dst_dims = dest.dims();
634    let dst_strides = dest.strides();
635    let src_strides = src.strides();
636
637    if sequential_contiguous_layout(
638        KernelClass::Map,
639        dst_dims,
640        &[dst_strides, src_strides],
641        &exec,
642    )?
643    .is_some()
644    {
645        let len = total_len(dst_dims)?;
646        let dst = unsafe { std::slice::from_raw_parts_mut(dst_ptr, len) };
647        let src = unsafe { std::slice::from_raw_parts(src_ptr, len) };
648        simd::dispatch_if_large(len, || {
649            for i in 0..len {
650                dst[i] = alpha * Op::apply(src[i]) + dst[i];
651            }
652        });
653        return Ok(());
654    }
655
656    let strides_list: [&[isize]; 2] = [dst_strides, src_strides];
657    let total = total_len(dst_dims)?;
658    let (fused_dims, ordered_strides, plan) = pointwise_plan(
659        dst_dims,
660        &strides_list,
661        Some(0),
662        &[std::mem::size_of::<D>(), std::mem::size_of::<S>()],
663        total,
664    );
665
666    let total = total_len(&fused_dims)?;
667    if is_parallel(KernelClass::Map, total, &exec) {
668        let dst_send = SendPtr(dst_ptr);
669        let src_send = SendPtr(src_ptr as *mut S);
670
671        let costs = compute_costs(&ordered_strides);
672        let initial_offsets: crate::inline::OperandVec<isize> =
673            strides_list.iter().map(|_| 0isize).collect();
674        return mapreduce_threaded(
675            &fused_dims,
676            &plan.block,
677            &ordered_strides,
678            &initial_offsets,
679            &costs,
680            KernelClass::Map,
681            exec,
682            &|dims, blocks, strides_list, offsets| {
683                for_each_pointwise_block_preordered(
684                    dims,
685                    blocks,
686                    strides_list,
687                    offsets,
688                    |offsets, len, strides| {
689                        unsafe {
690                            inner_loop_axpy::<D, S, A, Op>(
691                                dst_send.as_ptr().offset(offsets[0]),
692                                strides[0],
693                                src_send.as_const().offset(offsets[1]),
694                                strides[1],
695                                len,
696                                alpha,
697                            )
698                        };
699                        Ok(())
700                    },
701                )
702            },
703        );
704    }
705
706    let initial_offsets: crate::inline::OperandVec<isize> =
707        ordered_strides.iter().map(|_| 0isize).collect();
708    for_each_pointwise_block_preordered(
709        &fused_dims,
710        &plan.block,
711        &ordered_strides,
712        &initial_offsets,
713        |offsets, len, strides| {
714            unsafe {
715                inner_loop_axpy::<D, S, A, Op>(
716                    dst_ptr.offset(offsets[0]),
717                    strides[0],
718                    src_ptr.offset(offsets[1]),
719                    strides[1],
720                    len,
721                    alpha,
722                )
723            };
724            Ok(())
725        },
726    )
727}
728
729/// Accumulating fused multiply-add: `dest[i] += OpA::apply(a[i]) * OpB::apply(b[i])`.
730///
731/// Operands may have different element types. Element operations are applied lazily.
732///
733/// # Errors
734///
735/// Returns [`StridedError::RankMismatch`] or
736/// [`StridedError::ShapeMismatch`] when `dest` and an operand describe
737/// different extents, and [`StridedError::OffsetOverflow`] when the element
738/// count of the shape does not fit in `usize`. Every check runs before the
739/// first write, so a rejected call leaves `dest` untouched.
740///
741/// # Destination contract
742///
743/// [`StridedError::NonInjectiveOutputLayout`] when two logical indices of
744/// `dest` name the same element (for example a stride-0 broadcast axis of
745/// extent above one): the update reads and writes `dest`, so an aliased
746/// destination would be order-dependent, and a race under a threaded `exec`.
747pub fn fma_acc<D, A, B, OpA, OpB>(
748    dest: &mut StridedViewMut<D>,
749    a: &StridedView<A, OpA>,
750    b: &StridedView<B, OpB>,
751    exec: Exec<'_>,
752) -> Result<()>
753where
754    A: Copy + Mul<B, Output = D> + Send + Sync,
755    B: Copy + Send + Sync,
756    D: Copy + Add<D, Output = D> + Send + Sync,
757    OpA: ElementOp<A>,
758    OpB: ElementOp<B>,
759{
760    ensure_same_shape(dest.dims(), a.dims())?;
761    ensure_same_shape(dest.dims(), b.dims())?;
762    validate_destination_layout(dest.dims(), dest.strides())?;
763
764    let dst_ptr = dest.as_mut_ptr();
765    let a_ptr = a.ptr();
766    let b_ptr = b.ptr();
767    let dst_dims = dest.dims();
768    let dst_strides = dest.strides();
769    let a_strides = a.strides();
770    let b_strides = b.strides();
771
772    if sequential_contiguous_layout(
773        KernelClass::Map,
774        dst_dims,
775        &[dst_strides, a_strides, b_strides],
776        &exec,
777    )?
778    .is_some()
779    {
780        let len = total_len(dst_dims)?;
781        let dst = unsafe { std::slice::from_raw_parts_mut(dst_ptr, len) };
782        let sa = unsafe { std::slice::from_raw_parts(a_ptr, len) };
783        let sb = unsafe { std::slice::from_raw_parts(b_ptr, len) };
784        simd::dispatch_if_large(len, || {
785            for i in 0..len {
786                dst[i] = dst[i] + OpA::apply(sa[i]) * OpB::apply(sb[i]);
787            }
788        });
789        return Ok(());
790    }
791
792    let strides_list: [&[isize]; 3] = [dst_strides, a_strides, b_strides];
793    let total = total_len(dst_dims)?;
794    let (fused_dims, ordered_strides, plan) = pointwise_plan(
795        dst_dims,
796        &strides_list,
797        Some(0),
798        &[
799            std::mem::size_of::<D>(),
800            std::mem::size_of::<A>(),
801            std::mem::size_of::<B>(),
802        ],
803        total,
804    );
805
806    let total = total_len(&fused_dims)?;
807    if is_parallel(KernelClass::Map, total, &exec) {
808        let dst_send = SendPtr(dst_ptr);
809        let a_send = SendPtr(a_ptr as *mut A);
810        let b_send = SendPtr(b_ptr as *mut B);
811
812        let costs = compute_costs(&ordered_strides);
813        let initial_offsets: crate::inline::OperandVec<isize> =
814            strides_list.iter().map(|_| 0isize).collect();
815        return mapreduce_threaded(
816            &fused_dims,
817            &plan.block,
818            &ordered_strides,
819            &initial_offsets,
820            &costs,
821            KernelClass::Map,
822            exec,
823            &|dims, blocks, strides_list, offsets| {
824                for_each_pointwise_block_preordered(
825                    dims,
826                    blocks,
827                    strides_list,
828                    offsets,
829                    |offsets, len, strides| {
830                        unsafe {
831                            inner_loop_fma::<D, A, B, OpA, OpB>(
832                                dst_send.as_ptr().offset(offsets[0]),
833                                strides[0],
834                                a_send.as_const().offset(offsets[1]),
835                                strides[1],
836                                b_send.as_const().offset(offsets[2]),
837                                strides[2],
838                                len,
839                            )
840                        };
841                        Ok(())
842                    },
843                )
844            },
845        );
846    }
847
848    let initial_offsets: crate::inline::OperandVec<isize> =
849        ordered_strides.iter().map(|_| 0isize).collect();
850    for_each_pointwise_block_preordered(
851        &fused_dims,
852        &plan.block,
853        &ordered_strides,
854        &initial_offsets,
855        |offsets, len, strides| {
856            unsafe {
857                inner_loop_fma::<D, A, B, OpA, OpB>(
858                    dst_ptr.offset(offsets[0]),
859                    strides[0],
860                    a_ptr.offset(offsets[1]),
861                    strides[1],
862                    b_ptr.offset(offsets[2]),
863                    strides[2],
864                    len,
865                )
866            };
867            Ok(())
868        },
869    )
870}
871
872/// Sum all elements: `sum(src)`.
873///
874/// # Evaluation order
875///
876/// The result is independent of the pool when the call runs with a serial
877/// token ([`Exec::serial`]) or a budget of one. With a larger budget a
878/// contiguous identity operand above the threading threshold is summed per
879/// task and the partial sums are combined in a tree, so the result is
880/// repeatable for a fixed budget but can differ between budgets.
881///
882/// Neither path is a strict left to right sum: a contiguous run is folded with
883/// independent SIMD or scalar lanes (see [`reduce`] for the lane scheme of the
884/// generic path). The last bits can therefore differ from a naive loop, and no
885/// bitwise equality across machines or target features is guaranteed.
886///
887/// For a deterministic accumulation of `f32` data in `f64`, use
888/// [`zip_reduce`](crate::zip_reduce) with an `f64` map and a `0.0f64` init.
889///
890/// # Allocation
891///
892/// At rank ≤ [`INLINE_RANK`](strided_view::INLINE_RANK) the view metadata and
893/// the traversal plan are stored inline, so a call performs no heap allocation.
894///
895/// # Errors
896///
897/// Returns [`StridedError::OffsetOverflow`] when the element count of the
898/// view's shape does not fit in `usize`, the only failure this entry can
899/// produce. That check runs first, before any planning or read.
900pub fn sum<
901    T: Copy + Zero + Add<Output = T> + Send + Sync + simd::MaybeSimdOps,
902    Op: ElementOp<T>,
903>(
904    src: &StridedView<T, Op>,
905    exec: Exec<'_>,
906) -> Result<T> {
907    // A zero-element sum is the additive identity. Return before any planning
908    // so an empty view with an enormous stride never reaches block sizing.
909    if total_len(src.dims())? == 0 {
910        return Ok(T::zero());
911    }
912    // SIMD fast path: contiguous Identity view with SIMD support
913    if Op::IS_IDENTITY && same_contiguous_layout(src.dims(), &[src.strides()]).is_some() {
914        let len = total_len(src.dims())?;
915        let src_slice = unsafe { std::slice::from_raw_parts(src.ptr(), len) };
916
917        // The partial sums of the halves are combined in a tree; a type
918        // without SIMD support takes the generic reduction below.
919        if T::try_simd_sum(&[]).is_some() && is_parallel(KernelClass::Reduce, len, &exec) {
920            return Ok(crate::threading::parallel_map_reduce(
921                0..len,
922                crate::cost::for_len_tree(exec, KernelClass::Reduce, len),
923                &|range| T::try_simd_sum(&src_slice[range]).unwrap(),
924                &|left, right| left + right,
925            ));
926        }
927
928        if let Some(result) = T::try_simd_sum(src_slice) {
929            return Ok(result);
930        }
931    }
932    reduce(src, |x| x, |a, b| a + b, T::zero(), exec)
933}
934
935/// Dot product: `sum(OpA::apply(a[i]) * OpB::apply(b[i]))`.
936///
937/// Operands may have different element types. Result type `R` must be `A * B`.
938/// SIMD fast path fires only when `A == B == R` (same type) and both Identity ops.
939///
940/// A widening dot — `f32` operands with an `f64` accumulator — is not
941/// expressible here because `R` is pinned to `A * B`; use
942/// [`zip_reduce`](crate::zip_reduce) with a
943/// `|x, y| x as f64 * y as f64` map instead.
944///
945/// # Evaluation order
946///
947/// This entry takes no parallel branch and no token, so its result does not
948/// depend on any pool: it is computed on the calling thread. The homogeneous contiguous fast path folds with the SIMD
949/// lane scheme of the element type; every other layout folds a single
950/// accumulator along the traversal order of the fused plan, which is left to
951/// right over each unit-stride run. Neither is guaranteed to be bitwise equal
952/// across machines or target features.
953///
954/// # Allocation
955///
956/// At rank ≤ [`INLINE_RANK`](strided_view::INLINE_RANK) the view metadata and
957/// the traversal plan are stored inline, so a call performs no heap allocation.
958///
959/// # Errors
960///
961/// Returns [`StridedError::RankMismatch`] or
962/// [`StridedError::ShapeMismatch`] when the two operands describe different
963/// extents, and [`StridedError::OffsetOverflow`] when the element count of
964/// their shape does not fit in `usize`.
965pub fn dot<A, B, R, OpA, OpB>(a: &StridedView<A, OpA>, b: &StridedView<B, OpB>) -> Result<R>
966where
967    A: Copy + Mul<B, Output = R> + Send + Sync + 'static,
968    B: Copy + Send + Sync + 'static,
969    R: Copy + Zero + Add<Output = R> + Send + Sync + simd::MaybeSimdOps + 'static,
970    OpA: ElementOp<A>,
971    OpB: ElementOp<B>,
972{
973    ensure_same_shape(a.dims(), b.dims())?;
974
975    let a_ptr = a.ptr();
976    let b_ptr = b.ptr();
977    let a_strides = a.strides();
978    let b_strides = b.strides();
979    let a_dims = a.dims();
980    let len = total_len(a_dims)?;
981
982    // A zero-element dot product is the additive identity. Return before any
983    // planning so an empty view with an enormous stride never reaches block
984    // sizing.
985    if len == 0 {
986        return Ok(R::zero());
987    }
988
989    if same_contiguous_layout(a_dims, &[a_strides, b_strides]).is_some() {
990        // SIMD fast path: both contiguous, both Identity ops, same type
991        if OpA::IS_IDENTITY
992            && OpB::IS_IDENTITY
993            && std::any::TypeId::of::<A>() == std::any::TypeId::of::<R>()
994            && std::any::TypeId::of::<B>() == std::any::TypeId::of::<R>()
995        {
996            let sa = unsafe { std::slice::from_raw_parts(a_ptr as *const R, len) };
997            let sb = unsafe { std::slice::from_raw_parts(b_ptr as *const R, len) };
998            if let Some(result) = R::try_simd_dot(sa, sb) {
999                return Ok(result);
1000            }
1001        }
1002
1003        // Generic contiguous fast path
1004        let sa = unsafe { std::slice::from_raw_parts(a_ptr, len) };
1005        let sb = unsafe { std::slice::from_raw_parts(b_ptr, len) };
1006        let mut acc = R::zero();
1007        simd::dispatch_if_large(len, || {
1008            for i in 0..len {
1009                acc = acc + OpA::apply(sa[i]) * OpB::apply(sb[i]);
1010            }
1011        });
1012        return Ok(acc);
1013    }
1014
1015    let strides_list: [&[isize]; 2] = [a_strides, b_strides];
1016    // The accumulator `R` is not a memory operand, so it has no element size.
1017    let total = total_len(a_dims)?;
1018    // A fold: its tiles order `acc`, so it keeps the model's (#287).
1019    let (fused_dims, ordered_strides, plan) = crate::kernel::fold_plan(
1020        a_dims,
1021        &strides_list,
1022        0,
1023        &[std::mem::size_of::<A>(), std::mem::size_of::<B>()],
1024        total,
1025    );
1026
1027    let mut acc = R::zero();
1028    let initial_offsets: crate::inline::OperandVec<isize> =
1029        ordered_strides.iter().map(|_| 0isize).collect();
1030    for_each_inner_block_preordered(
1031        &fused_dims,
1032        &plan.block,
1033        &ordered_strides,
1034        &initial_offsets,
1035        |offsets, len, strides| {
1036            acc = unsafe {
1037                inner_loop_dot::<A, B, R, OpA, OpB>(
1038                    a_ptr.offset(offsets[0]),
1039                    strides[0],
1040                    b_ptr.offset(offsets[1]),
1041                    strides[1],
1042                    len,
1043                    acc,
1044                )
1045            };
1046            Ok(())
1047        },
1048    )?;
1049
1050    Ok(acc)
1051}
1052
1053/// Symmetrize a square matrix: `dest = (src + src^T) / 2`.
1054///
1055/// # Errors
1056///
1057/// Returns [`StridedError::RankMismatch`] when `src` is not rank 2,
1058/// [`StridedError::NonSquare`] when its two extents differ, and
1059/// [`StridedError::ScalarConversion`] only when `T::from_f64(0.5)` returns
1060/// `None`. `num_traits::FromPrimitive::from_f64` truncates for the primitive
1061/// integer types (`i32::from_f64(0.5) == Some(0)`), so an integer `T` is not
1062/// rejected: it scales by zero, and the result is zero rather than a half.
1063/// Writing through [`zip_map2_into`](crate::zip_map2_into) adds
1064/// [`StridedError::RankMismatch`] or [`StridedError::ShapeMismatch`] when
1065/// `dest` and the transposed `src` describe different extents, and
1066/// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
1067/// cannot be proven representable and injective: two logical indices name
1068/// one offset, or the element count or address span is too large to
1069/// represent. Nothing is written unless validation succeeds.
1070pub fn symmetrize_into<T>(
1071    dest: &mut StridedViewMut<T>,
1072    src: &StridedView<T>,
1073    exec: Exec<'_>,
1074) -> Result<()>
1075where
1076    T: Copy
1077        + Add<Output = T>
1078        + Mul<Output = T>
1079        + num_traits::FromPrimitive
1080        + std::ops::Div<Output = T>
1081        + Send
1082        + Sync,
1083{
1084    if src.ndim() != 2 {
1085        return Err(StridedError::RankMismatch(src.ndim(), 2));
1086    }
1087    let rows = src.dims()[0];
1088    let cols = src.dims()[1];
1089    if rows != cols {
1090        return Err(StridedError::NonSquare { rows, cols });
1091    }
1092
1093    let src_t = src.permute(&[1, 0])?;
1094    let half = T::from_f64(0.5).ok_or(StridedError::ScalarConversion)?;
1095
1096    zip_map2_into(dest, src, &src_t, |a, b| (a + b) * half, exec)
1097}
1098
1099/// Conjugate-symmetrize a square matrix: `dest = (src + conj(src^T)) / 2`.
1100///
1101/// # Errors
1102///
1103/// Returns [`StridedError::RankMismatch`] when `src` is not rank 2,
1104/// [`StridedError::NonSquare`] when its two extents differ, and
1105/// [`StridedError::ScalarConversion`] only when `T::from_f64(0.5)` returns
1106/// `None`. `num_traits::FromPrimitive::from_f64` truncates for the primitive
1107/// integer types (`i32::from_f64(0.5) == Some(0)`), so an integer `T` is not
1108/// rejected: it scales by zero, and the result is zero rather than a half.
1109/// Writing through [`zip_map2_into`](crate::zip_map2_into) adds
1110/// [`StridedError::RankMismatch`] or [`StridedError::ShapeMismatch`] when
1111/// `dest` and the adjoint of `src` describe different extents, and
1112/// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
1113/// cannot be proven representable and injective: two logical indices name
1114/// one offset, or the element count or address span is too large to
1115/// represent. Nothing is written unless validation succeeds.
1116pub fn symmetrize_conj_into<T>(
1117    dest: &mut StridedViewMut<T>,
1118    src: &StridedView<T>,
1119    exec: Exec<'_>,
1120) -> Result<()>
1121where
1122    T: Copy
1123        + ElementOpApply
1124        + Add<Output = T>
1125        + Mul<Output = T>
1126        + num_traits::FromPrimitive
1127        + std::ops::Div<Output = T>
1128        + Send
1129        + Sync,
1130{
1131    if src.ndim() != 2 {
1132        return Err(StridedError::RankMismatch(src.ndim(), 2));
1133    }
1134    let rows = src.dims()[0];
1135    let cols = src.dims()[1];
1136    if rows != cols {
1137        return Err(StridedError::NonSquare { rows, cols });
1138    }
1139
1140    // adjoint = conj + transpose
1141    let src_adj = src.adjoint_2d()?;
1142    let half = T::from_f64(0.5).ok_or(StridedError::ScalarConversion)?;
1143
1144    zip_map2_into(dest, src, &src_adj, |a, b| (a + b) * half, exec)
1145}
1146
1147/// Overwriting copy with scaling: `dest[i] = scale * src[i]`.
1148///
1149/// Scale, source, and destination may have different element types.
1150///
1151/// # Errors
1152///
1153/// Returns [`StridedError::RankMismatch`] or
1154/// [`StridedError::ShapeMismatch`] when the views describe different
1155/// extents, and [`StridedError::NonInjectiveOutputLayout`] when the
1156/// destination layout cannot be proven representable and injective: two
1157/// logical indices name one offset, or the element count or address span is
1158/// too large to represent. Nothing is written unless validation succeeds.
1159pub fn copy_scale_into<D, S, A, Op>(
1160    dest: &mut StridedViewMut<D>,
1161    src: &StridedView<S, Op>,
1162    scale: A,
1163    exec: Exec<'_>,
1164) -> Result<()>
1165where
1166    A: Copy + Mul<S, Output = D> + Sync,
1167    D: Copy + Send + Sync,
1168    S: Copy + Send + Sync,
1169    Op: ElementOp<S>,
1170{
1171    map_into(dest, src, |x| scale * x, exec)
1172}
1173
1174/// Overwriting copy with complex conjugation: `dest[i] = conj(src[i])`.
1175///
1176/// A non-contiguous copy of a complex element type is handed to the permutation
1177/// engine's conjugating store ([`strided_perm::copy_conj_into`], HPTT's
1178/// `conjA`) when that engine is measured to beat the element map for the shape;
1179/// every other copy keeps the element map. The engine conjugates each element
1180/// as it stores it, so the operation costs no extra pass over memory. Which
1181/// route is taken is measured, not guessed: `benches/conj_route_467.rs`
1182/// reproduces the table and `docs/worklogs/2026-11-15-issue-467-conj-route.md`
1183/// records it, with the bound and the rows that fix it. A real element type's
1184/// `conj` is the identity, so it always keeps the element map; use
1185/// [`copy_into`] for those.
1186///
1187/// # Errors
1188///
1189/// The rejection set of [`copy_into`]: [`StridedError::RankMismatch`] or
1190/// [`StridedError::ShapeMismatch`] when the views describe different
1191/// extents, [`StridedError::OffsetOverflow`] when the element count of the
1192/// shape does not fit in `usize`, and
1193/// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
1194/// cannot be proven representable and injective. Nothing is written unless
1195/// validation succeeds.
1196///
1197/// The engine route reports one of those differently: it plans the permutation
1198/// before it checks the destination for injectivity, so an unrepresentable
1199/// destination keeps reporting [`StridedError::OffsetOverflow`] (issue #263)
1200/// where [`copy_into`] reports [`StridedError::NonInjectiveOutputLayout`] under
1201/// its "cannot be proven representable and injective" case. Nothing is written
1202/// on either route.
1203pub fn copy_conj_into<T: ElementOpApply + Send + Sync + 'static>(
1204    dest: &mut StridedViewMut<T>,
1205    src: &StridedView<T>,
1206    exec: Exec<'_>,
1207) -> Result<()> {
1208    if conj_perm_engine_route::<T>(dest.dims(), dest.strides(), src.strides()) {
1209        return crate::threading::copy_conj_permuted(dest, src, exec);
1210    }
1211    let src_conj = src.conj();
1212    copy_into(dest, &src_conj, exec)
1213}
1214
1215/// Bytes of one operand below which [`copy_conj_into`] leaves a non-contiguous
1216/// complex copy on the permutation engine ([#467]).
1217///
1218/// Measured crossing, `Complex<f64>`, `Exec::serial()`, ns per element, quoted as
1219/// element map over engine (`> 1` means the engine wins), across four passes:
1220/// 112^3 = 21.4 MiB is 1.51-1.67, 116^3 = 23.8 MiB is 0.93-0.96, 120^3 = 26.4
1221/// MiB is 0.90-0.93, 124^3 = 29.1 MiB is 0.86-0.89 and 128^3 = 32.0 MiB is
1222/// 0.84-0.97. The engine's tiles stop beating the map's blocked traversal once
1223/// one operand no longer fits in a 32 MiB last-level-cache domain, so the bound
1224/// sits inside that bracket at 24 MiB — above the last outright engine win
1225/// (112^3) and below every row the map wins or ties (120^3 and up), with 116^3
1226/// the one tie it leaves on the engine side. `Complex<f32>` is bounded the same
1227/// way in bytes but was not measured.
1228///
1229/// [#467]: https://github.com/tensor4all/strided-rs/issues/467
1230const CONJ_PERM_ENGINE_MAX_BYTES: usize = 24 * 1024 * 1024;
1231
1232/// Whether [`copy_conj_into`] hands this copy to the permutation engine: a
1233/// complex element type, a non-contiguous layout, and a packed footprint below
1234/// [`CONJ_PERM_ENGINE_MAX_BYTES`]. The footprint bound is measured and the other
1235/// two clauses are what the engine's conjugating store cannot do better than the
1236/// map; the table behind all three is `benches/conj_route_467.rs`, recorded in
1237/// `docs/worklogs/2026-11-15-issue-467-conj-route.md`.
1238fn conj_perm_engine_route<T: 'static>(
1239    dims: &[usize],
1240    dst_strides: &[isize],
1241    src_strides: &[isize],
1242) -> bool {
1243    if !element_conj_is_applied::<T>() {
1244        return false;
1245    }
1246    // A contiguous copy takes the map's SIMD store loop (or its splitting
1247    // contiguous path); the engine's conjugating store has no memcpy.
1248    if same_contiguous_layout(dims, &[dst_strides, src_strides]).is_some() {
1249        return false;
1250    }
1251    // An overflowing element count is the map path's `OffsetOverflow` to report.
1252    total_len(dims).is_ok_and(|len| {
1253        len.checked_mul(std::mem::size_of::<T>())
1254            .is_some_and(|bytes| bytes < CONJ_PERM_ENGINE_MAX_BYTES)
1255    })
1256}
1257
1258/// Whether `T`'s `conj` is not the identity, i.e. whether the engine's
1259/// conjugating store does anything.
1260#[inline]
1261fn element_conj_is_applied<T: 'static>() -> bool {
1262    use std::any::TypeId;
1263
1264    let id = TypeId::of::<T>();
1265    id == TypeId::of::<num_complex::Complex32>() || id == TypeId::of::<num_complex::Complex64>()
1266}
1267
1268#[inline]
1269fn element_transpose_is_identity<T: 'static>() -> bool {
1270    use std::any::TypeId;
1271
1272    macro_rules! matches_type {
1273        ($($ty:ty),* $(,)?) => {{
1274            let id = TypeId::of::<T>();
1275            false $(|| id == TypeId::of::<$ty>())*
1276        }};
1277    }
1278
1279    matches_type!(
1280        f32,
1281        f64,
1282        i8,
1283        i16,
1284        i32,
1285        i64,
1286        i128,
1287        isize,
1288        u8,
1289        u16,
1290        u32,
1291        u64,
1292        u128,
1293        usize,
1294        num_complex::Complex32,
1295        num_complex::Complex64,
1296    )
1297}
1298
1299#[inline]
1300fn element_zero_is_all_bits_zero<T: 'static>() -> bool {
1301    use std::any::TypeId;
1302
1303    macro_rules! matches_type {
1304        ($($ty:ty),* $(,)?) => {{
1305            let id = TypeId::of::<T>();
1306            false $(|| id == TypeId::of::<$ty>())*
1307        }};
1308    }
1309
1310    matches_type!(
1311        f32,
1312        f64,
1313        i8,
1314        i16,
1315        i32,
1316        i64,
1317        i128,
1318        isize,
1319        u8,
1320        u16,
1321        u32,
1322        u64,
1323        u128,
1324        usize,
1325        num_complex::Complex32,
1326        num_complex::Complex64,
1327    )
1328}
1329
1330#[inline]
1331unsafe fn fill_2d<T: Copy + Send + Sync>(
1332    dst: *mut T,
1333    dim0: usize,
1334    dim1: usize,
1335    dst_stride0: isize,
1336    dst_stride1: isize,
1337    value: T,
1338    exec: Exec<'_>,
1339) {
1340    let total = dim0.saturating_mul(dim1);
1341    let exec = crate::cost::for_len(exec, KernelClass::Copy, total);
1342    if !exec.is_serial() {
1343        let dst_send = SendPtr(dst);
1344        if dst_stride0.unsigned_abs() <= dst_stride1.unsigned_abs() {
1345            crate::threading::parallel_for_each(0..dim1, exec, &|columns| {
1346                for j in columns {
1347                    let dst = dst_send.as_ptr();
1348                    unsafe {
1349                        let base = j as isize * dst_stride1;
1350                        for i in 0..dim0 {
1351                            *dst.offset(base + i as isize * dst_stride0) = value;
1352                        }
1353                    }
1354                }
1355            });
1356        } else {
1357            crate::threading::parallel_for_each(0..dim0, exec, &|rows| {
1358                for i in rows {
1359                    let dst = dst_send.as_ptr();
1360                    unsafe {
1361                        let base = i as isize * dst_stride0;
1362                        for j in 0..dim1 {
1363                            *dst.offset(base + j as isize * dst_stride1) = value;
1364                        }
1365                    }
1366                }
1367            });
1368        }
1369        return;
1370    }
1371
1372    if dst_stride0.unsigned_abs() <= dst_stride1.unsigned_abs() {
1373        for j in 0..dim1 {
1374            let base = j as isize * dst_stride1;
1375            for i in 0..dim0 {
1376                *dst.offset(base + i as isize * dst_stride0) = value;
1377            }
1378        }
1379    } else {
1380        for i in 0..dim0 {
1381            let base = i as isize * dst_stride0;
1382            for j in 0..dim1 {
1383                *dst.offset(base + j as isize * dst_stride1) = value;
1384            }
1385        }
1386    }
1387}
1388
1389#[inline]
1390unsafe fn fill_contiguous<T>(dst: *mut T, len: usize, value: T)
1391where
1392    T: Copy + Zero + PartialEq + Send + Sync + 'static,
1393{
1394    if element_zero_is_all_bits_zero::<T>() && value == T::zero() {
1395        std::ptr::write_bytes(dst, 0, len);
1396        return;
1397    }
1398
1399    let dst = std::slice::from_raw_parts_mut(dst, len);
1400    dst.fill(value);
1401}
1402
1403// 4x4 transpose block: both base pointers with both strides, the block index and
1404// the scale.
1405#[allow(clippy::too_many_arguments)]
1406#[inline(always)]
1407unsafe fn transpose_scale_4x4_f64(
1408    dst: *mut f64,
1409    dst_stride0: isize,
1410    dst_stride1: isize,
1411    src: *const f64,
1412    src_stride0: isize,
1413    src_stride1: isize,
1414    i: usize,
1415    j: usize,
1416    scale: f64,
1417) {
1418    let src_base = src.offset(i as isize * src_stride0 + j as isize * src_stride1);
1419
1420    let s00 = *src_base;
1421    let s10 = *src_base.offset(src_stride0);
1422    let s20 = *src_base.offset(2 * src_stride0);
1423    let s30 = *src_base.offset(3 * src_stride0);
1424
1425    let src_col1 = src_base.offset(src_stride1);
1426    let s01 = *src_col1;
1427    let s11 = *src_col1.offset(src_stride0);
1428    let s21 = *src_col1.offset(2 * src_stride0);
1429    let s31 = *src_col1.offset(3 * src_stride0);
1430
1431    let src_col2 = src_base.offset(2 * src_stride1);
1432    let s02 = *src_col2;
1433    let s12 = *src_col2.offset(src_stride0);
1434    let s22 = *src_col2.offset(2 * src_stride0);
1435    let s32 = *src_col2.offset(3 * src_stride0);
1436
1437    let src_col3 = src_base.offset(3 * src_stride1);
1438    let s03 = *src_col3;
1439    let s13 = *src_col3.offset(src_stride0);
1440    let s23 = *src_col3.offset(2 * src_stride0);
1441    let s33 = *src_col3.offset(3 * src_stride0);
1442
1443    let dst_row0 = dst.offset(j as isize * dst_stride0 + i as isize * dst_stride1);
1444    *dst_row0 = scale * s00;
1445    *dst_row0.offset(dst_stride0) = scale * s01;
1446    *dst_row0.offset(2 * dst_stride0) = scale * s02;
1447    *dst_row0.offset(3 * dst_stride0) = scale * s03;
1448
1449    let dst_row1 = dst_row0.offset(dst_stride1);
1450    *dst_row1 = scale * s10;
1451    *dst_row1.offset(dst_stride0) = scale * s11;
1452    *dst_row1.offset(2 * dst_stride0) = scale * s12;
1453    *dst_row1.offset(3 * dst_stride0) = scale * s13;
1454
1455    let dst_row2 = dst_row0.offset(2 * dst_stride1);
1456    *dst_row2 = scale * s20;
1457    *dst_row2.offset(dst_stride0) = scale * s21;
1458    *dst_row2.offset(2 * dst_stride0) = scale * s22;
1459    *dst_row2.offset(3 * dst_stride0) = scale * s23;
1460
1461    let dst_row3 = dst_row0.offset(3 * dst_stride1);
1462    *dst_row3 = scale * s30;
1463    *dst_row3.offset(dst_stride0) = scale * s31;
1464    *dst_row3.offset(2 * dst_stride0) = scale * s32;
1465    *dst_row3.offset(3 * dst_stride0) = scale * s33;
1466}
1467
1468#[inline]
1469// Tile kernel for f64: both bases, both stride pairs, the tile bounds, the scale and
1470// the token.
1471#[allow(clippy::too_many_arguments)]
1472unsafe fn copy_transpose_scale_2d_f64_tiled_raw(
1473    dst: *mut f64,
1474    dst_stride0: isize,
1475    dst_stride1: isize,
1476    src: *const f64,
1477    src_stride0: isize,
1478    src_stride1: isize,
1479    src_rows: usize,
1480    src_cols: usize,
1481    scale: f64,
1482    exec: Exec<'_>,
1483) {
1484    const TILE: usize = 4;
1485    let row_full = src_rows / TILE * TILE;
1486    let col_full = src_cols / TILE * TILE;
1487
1488    let total = src_rows.saturating_mul(src_cols);
1489    let exec = crate::cost::for_len(exec, KernelClass::Map, total);
1490    if !exec.is_serial() {
1491        let dst_send = SendPtr(dst);
1492        let src_send = SendPtr(src as *mut f64);
1493        let row_tiles = row_full / TILE;
1494        crate::threading::parallel_for_each(0..row_tiles, exec, &|tiles| {
1495            for tile_i in tiles {
1496                let i = tile_i * TILE;
1497                let dst = dst_send.as_ptr();
1498                let src = src_send.as_const();
1499                unsafe {
1500                    let mut j = 0;
1501                    while j < col_full {
1502                        transpose_scale_4x4_f64(
1503                            dst,
1504                            dst_stride0,
1505                            dst_stride1,
1506                            src,
1507                            src_stride0,
1508                            src_stride1,
1509                            i,
1510                            j,
1511                            scale,
1512                        );
1513                        j += TILE;
1514                    }
1515                    for j in col_full..src_cols {
1516                        for ii in i..i + TILE {
1517                            *dst.offset(j as isize * dst_stride0 + ii as isize * dst_stride1) =
1518                                scale
1519                                    * *src.offset(
1520                                        ii as isize * src_stride0 + j as isize * src_stride1,
1521                                    );
1522                        }
1523                    }
1524                }
1525            }
1526        });
1527        for i in row_full..src_rows {
1528            for j in 0..src_cols {
1529                *dst.offset(j as isize * dst_stride0 + i as isize * dst_stride1) =
1530                    scale * *src.offset(i as isize * src_stride0 + j as isize * src_stride1);
1531            }
1532        }
1533        return;
1534    }
1535
1536    let mut i = 0;
1537    while i < row_full {
1538        let mut j = 0;
1539        while j < col_full {
1540            transpose_scale_4x4_f64(
1541                dst,
1542                dst_stride0,
1543                dst_stride1,
1544                src,
1545                src_stride0,
1546                src_stride1,
1547                i,
1548                j,
1549                scale,
1550            );
1551            j += TILE;
1552        }
1553        for j in col_full..src_cols {
1554            for ii in i..i + TILE {
1555                *dst.offset(j as isize * dst_stride0 + ii as isize * dst_stride1) =
1556                    scale * *src.offset(ii as isize * src_stride0 + j as isize * src_stride1);
1557            }
1558        }
1559        i += TILE;
1560    }
1561    for i in row_full..src_rows {
1562        for j in 0..src_cols {
1563            *dst.offset(j as isize * dst_stride0 + i as isize * dst_stride1) =
1564                scale * *src.offset(i as isize * src_stride0 + j as isize * src_stride1);
1565        }
1566    }
1567}
1568
1569#[inline]
1570#[cfg(test)]
1571unsafe fn try_copy_transpose_scale_2d_f64_tiled(
1572    dest: &mut StridedViewMut<f64>,
1573    src: &StridedView<f64>,
1574    scale: f64,
1575    exec: Exec<'_>,
1576) -> bool {
1577    if src.ndim() != 2 || dest.ndim() != 2 {
1578        return false;
1579    }
1580    let src_dims = src.dims();
1581    if dest.dims() != [src_dims[1], src_dims[0]] {
1582        return false;
1583    }
1584    if src.strides()[0] != 1 || dest.strides()[0] != 1 {
1585        return false;
1586    }
1587
1588    copy_transpose_scale_2d_f64_tiled_raw(
1589        dest.as_mut_ptr(),
1590        dest.strides()[0],
1591        dest.strides()[1],
1592        src.ptr(),
1593        src.strides()[0],
1594        src.strides()[1],
1595        src_dims[0],
1596        src_dims[1],
1597        scale,
1598        exec,
1599    );
1600    true
1601}
1602
1603#[inline]
1604unsafe fn try_copy_transpose_scale_2d_f64_tiled_typed<T>(
1605    dest: &mut StridedViewMut<T>,
1606    src: &StridedView<T>,
1607    scale: T,
1608    exec: Exec<'_>,
1609) -> bool
1610where
1611    T: Copy + 'static,
1612{
1613    if std::any::TypeId::of::<T>() != std::any::TypeId::of::<f64>() {
1614        return false;
1615    }
1616
1617    let scale = *(&scale as *const T).cast::<f64>();
1618    if src.ndim() != 2 || dest.ndim() != 2 {
1619        return false;
1620    }
1621    let src_dims = src.dims();
1622    if dest.dims() != [src_dims[1], src_dims[0]] {
1623        return false;
1624    }
1625    if src.strides()[0] != 1 || dest.strides()[0] != 1 {
1626        return false;
1627    }
1628
1629    copy_transpose_scale_2d_f64_tiled_raw(
1630        dest.as_mut_ptr().cast::<f64>(),
1631        dest.strides()[0],
1632        dest.strides()[1],
1633        src.ptr().cast::<f64>(),
1634        src.strides()[0],
1635        src.strides()[1],
1636        src_dims[0],
1637        src_dims[1],
1638        scale,
1639        exec,
1640    );
1641    true
1642}
1643
1644// Same 4x4 transpose block for the identity element op, which skips the op.
1645#[allow(clippy::too_many_arguments)]
1646#[inline(always)]
1647unsafe fn transpose_scale_4x4_identity<T>(
1648    dst: *mut T,
1649    dst_stride0: isize,
1650    dst_stride1: isize,
1651    src: *const T,
1652    src_stride0: isize,
1653    src_stride1: isize,
1654    i: usize,
1655    j: usize,
1656    scale: T,
1657) where
1658    T: Copy + Mul<Output = T>,
1659{
1660    let src_base = src.offset(i as isize * src_stride0 + j as isize * src_stride1);
1661
1662    let s00 = *src_base;
1663    let s10 = *src_base.offset(src_stride0);
1664    let s20 = *src_base.offset(2 * src_stride0);
1665    let s30 = *src_base.offset(3 * src_stride0);
1666
1667    let src_col1 = src_base.offset(src_stride1);
1668    let s01 = *src_col1;
1669    let s11 = *src_col1.offset(src_stride0);
1670    let s21 = *src_col1.offset(2 * src_stride0);
1671    let s31 = *src_col1.offset(3 * src_stride0);
1672
1673    let src_col2 = src_base.offset(2 * src_stride1);
1674    let s02 = *src_col2;
1675    let s12 = *src_col2.offset(src_stride0);
1676    let s22 = *src_col2.offset(2 * src_stride0);
1677    let s32 = *src_col2.offset(3 * src_stride0);
1678
1679    let src_col3 = src_base.offset(3 * src_stride1);
1680    let s03 = *src_col3;
1681    let s13 = *src_col3.offset(src_stride0);
1682    let s23 = *src_col3.offset(2 * src_stride0);
1683    let s33 = *src_col3.offset(3 * src_stride0);
1684
1685    let dst_row0 = dst.offset(j as isize * dst_stride0 + i as isize * dst_stride1);
1686    *dst_row0 = scale * s00;
1687    *dst_row0.offset(dst_stride0) = scale * s01;
1688    *dst_row0.offset(2 * dst_stride0) = scale * s02;
1689    *dst_row0.offset(3 * dst_stride0) = scale * s03;
1690
1691    let dst_row1 = dst_row0.offset(dst_stride1);
1692    *dst_row1 = scale * s10;
1693    *dst_row1.offset(dst_stride0) = scale * s11;
1694    *dst_row1.offset(2 * dst_stride0) = scale * s12;
1695    *dst_row1.offset(3 * dst_stride0) = scale * s13;
1696
1697    let dst_row2 = dst_row0.offset(2 * dst_stride1);
1698    *dst_row2 = scale * s20;
1699    *dst_row2.offset(dst_stride0) = scale * s21;
1700    *dst_row2.offset(2 * dst_stride0) = scale * s22;
1701    *dst_row2.offset(3 * dst_stride0) = scale * s23;
1702
1703    let dst_row3 = dst_row0.offset(3 * dst_stride1);
1704    *dst_row3 = scale * s30;
1705    *dst_row3.offset(dst_stride0) = scale * s31;
1706    *dst_row3.offset(2 * dst_stride0) = scale * s32;
1707    *dst_row3.offset(3 * dst_stride0) = scale * s33;
1708}
1709
1710#[inline]
1711// Tile kernel: both bases, both stride pairs, the tile bounds, the scale and the token.
1712#[allow(clippy::too_many_arguments)]
1713unsafe fn copy_transpose_scale_2d_identity_tiled_raw<T>(
1714    dst: *mut T,
1715    dst_stride0: isize,
1716    dst_stride1: isize,
1717    src: *const T,
1718    src_stride0: isize,
1719    src_stride1: isize,
1720    src_rows: usize,
1721    src_cols: usize,
1722    scale: T,
1723    exec: Exec<'_>,
1724) where
1725    T: Copy + Mul<Output = T> + Send + Sync,
1726{
1727    const TILE: usize = 4;
1728    let row_full = src_rows / TILE * TILE;
1729    let col_full = src_cols / TILE * TILE;
1730
1731    let total = src_rows.saturating_mul(src_cols);
1732    let exec = crate::cost::for_len(exec, KernelClass::Map, total);
1733    if !exec.is_serial() {
1734        let dst_send = SendPtr(dst);
1735        let src_send = SendPtr(src as *mut T);
1736        let row_tiles = row_full / TILE;
1737        crate::threading::parallel_for_each(0..row_tiles, exec, &|tiles| {
1738            for tile_i in tiles {
1739                let i = tile_i * TILE;
1740                let dst = dst_send.as_ptr();
1741                let src = src_send.as_const();
1742                unsafe {
1743                    let mut j = 0;
1744                    while j < col_full {
1745                        transpose_scale_4x4_identity(
1746                            dst,
1747                            dst_stride0,
1748                            dst_stride1,
1749                            src,
1750                            src_stride0,
1751                            src_stride1,
1752                            i,
1753                            j,
1754                            scale,
1755                        );
1756                        j += TILE;
1757                    }
1758                    for j in col_full..src_cols {
1759                        for ii in i..i + TILE {
1760                            *dst.offset(j as isize * dst_stride0 + ii as isize * dst_stride1) =
1761                                scale
1762                                    * *src.offset(
1763                                        ii as isize * src_stride0 + j as isize * src_stride1,
1764                                    );
1765                        }
1766                    }
1767                }
1768            }
1769        });
1770        for i in row_full..src_rows {
1771            for j in 0..src_cols {
1772                *dst.offset(j as isize * dst_stride0 + i as isize * dst_stride1) =
1773                    scale * *src.offset(i as isize * src_stride0 + j as isize * src_stride1);
1774            }
1775        }
1776        return;
1777    }
1778
1779    let mut i = 0;
1780    while i < row_full {
1781        let mut j = 0;
1782        while j < col_full {
1783            transpose_scale_4x4_identity(
1784                dst,
1785                dst_stride0,
1786                dst_stride1,
1787                src,
1788                src_stride0,
1789                src_stride1,
1790                i,
1791                j,
1792                scale,
1793            );
1794            j += TILE;
1795        }
1796        for j in col_full..src_cols {
1797            for ii in i..i + TILE {
1798                *dst.offset(j as isize * dst_stride0 + ii as isize * dst_stride1) =
1799                    scale * *src.offset(ii as isize * src_stride0 + j as isize * src_stride1);
1800            }
1801        }
1802        i += TILE;
1803    }
1804    for i in row_full..src_rows {
1805        for j in 0..src_cols {
1806            *dst.offset(j as isize * dst_stride0 + i as isize * dst_stride1) =
1807                scale * *src.offset(i as isize * src_stride0 + j as isize * src_stride1);
1808        }
1809    }
1810}
1811
1812#[inline]
1813unsafe fn try_copy_transpose_scale_2d_identity_tiled<T>(
1814    dest: &mut StridedViewMut<T>,
1815    src: &StridedView<T>,
1816    scale: T,
1817    exec: Exec<'_>,
1818) -> bool
1819where
1820    T: Copy + Mul<Output = T> + Send + Sync,
1821{
1822    if src.ndim() != 2 || dest.ndim() != 2 {
1823        return false;
1824    }
1825    let src_dims = src.dims();
1826    if dest.dims() != [src_dims[1], src_dims[0]] {
1827        return false;
1828    }
1829    if src.strides()[0] != 1 || dest.strides()[0] != 1 {
1830        return false;
1831    }
1832
1833    copy_transpose_scale_2d_identity_tiled_raw(
1834        dest.as_mut_ptr(),
1835        dest.strides()[0],
1836        dest.strides()[1],
1837        src.ptr(),
1838        src.strides()[0],
1839        src.strides()[1],
1840        src_dims[0],
1841        src_dims[1],
1842        scale,
1843        exec,
1844    );
1845    true
1846}
1847
1848#[inline]
1849// Same signature as the tiled kernels, so the loop and tiled paths stay comparable.
1850#[allow(clippy::too_many_arguments)]
1851unsafe fn copy_transpose_scale_2d_loop<T>(
1852    dst: *mut T,
1853    dst_stride0: isize,
1854    dst_stride1: isize,
1855    src: *const T,
1856    src_stride0: isize,
1857    src_stride1: isize,
1858    src_rows: usize,
1859    src_cols: usize,
1860    scale: T,
1861    exec: Exec<'_>,
1862) where
1863    T: Copy + ElementOpApply + Mul<Output = T> + Send + Sync,
1864{
1865    let total = src_rows.saturating_mul(src_cols);
1866    let exec = crate::cost::for_len(exec, KernelClass::Map, total);
1867    if !exec.is_serial() {
1868        let dst_send = SendPtr(dst);
1869        let src_send = SendPtr(src as *mut T);
1870        if dst_stride0.unsigned_abs() <= dst_stride1.unsigned_abs() {
1871            crate::threading::parallel_for_each(0..src_rows, exec, &|rows| {
1872                for i in rows {
1873                    let dst = dst_send.as_ptr();
1874                    let src = src_send.as_const();
1875                    unsafe {
1876                        for j in 0..src_cols {
1877                            let value = (*src
1878                                .offset(i as isize * src_stride0 + j as isize * src_stride1))
1879                            .transpose();
1880                            *dst.offset(j as isize * dst_stride0 + i as isize * dst_stride1) =
1881                                scale * value;
1882                        }
1883                    }
1884                }
1885            });
1886        } else {
1887            crate::threading::parallel_for_each(0..src_cols, exec, &|columns| {
1888                for j in columns {
1889                    let dst = dst_send.as_ptr();
1890                    let src = src_send.as_const();
1891                    unsafe {
1892                        for i in 0..src_rows {
1893                            let value = (*src
1894                                .offset(i as isize * src_stride0 + j as isize * src_stride1))
1895                            .transpose();
1896                            *dst.offset(j as isize * dst_stride0 + i as isize * dst_stride1) =
1897                                scale * value;
1898                        }
1899                    }
1900                }
1901            });
1902        }
1903        return;
1904    }
1905
1906    if dst_stride0.unsigned_abs() <= dst_stride1.unsigned_abs() {
1907        for i in 0..src_rows {
1908            for j in 0..src_cols {
1909                let value =
1910                    (*src.offset(i as isize * src_stride0 + j as isize * src_stride1)).transpose();
1911                *dst.offset(j as isize * dst_stride0 + i as isize * dst_stride1) = scale * value;
1912            }
1913        }
1914    } else {
1915        for j in 0..src_cols {
1916            for i in 0..src_rows {
1917                let value =
1918                    (*src.offset(i as isize * src_stride0 + j as isize * src_stride1)).transpose();
1919                *dst.offset(j as isize * dst_stride0 + i as isize * dst_stride1) = scale * value;
1920            }
1921        }
1922    }
1923}
1924
1925/// Copy with transpose and scaling: `dest[j,i] = scale * src[i,j]`.
1926///
1927/// # Errors
1928///
1929/// Returns [`StridedError::RankMismatch`] when `src` or `dest` is not rank
1930/// 2, [`StridedError::ShapeMismatch`] when `dest` does not have the
1931/// transposed extents of `src`, and
1932/// [`StridedError::OffsetOverflow`] when the element count does not fit in
1933/// `usize`. When `scale` is one and `T`'s transpose is the identity, the
1934/// permutation path also returns [`StridedError::OffsetOverflow`] when the
1935/// layout cannot be expressed in `isize` stride arithmetic or a fused extent
1936/// overflows, and [`StridedError::NonInjectiveOutputLayout`] when the
1937/// destination layout cannot be proven representable and injective. The
1938/// injectivity check runs on every route, before the first write.
1939pub fn copy_transpose_scale_into<T>(
1940    dest: &mut StridedViewMut<T>,
1941    src: &StridedView<T>,
1942    scale: T,
1943    exec: Exec<'_>,
1944) -> Result<()>
1945where
1946    T: Copy + ElementOpApply + Mul<Output = T> + Zero + One + PartialEq + Send + Sync + 'static,
1947{
1948    let mut exec = exec;
1949    if src.ndim() != 2 || dest.ndim() != 2 {
1950        return Err(StridedError::RankMismatch(src.ndim(), 2));
1951    }
1952
1953    let src_dims = src.dims();
1954    let expected_dims = [src_dims[1], src_dims[0]];
1955    ensure_same_shape(dest.dims(), &expected_dims)?;
1956    validate_destination_layout(dest.dims(), dest.strides())?;
1957    // Reject an element count beyond usize (a huge stride-0 broadcast) up
1958    // front instead of looping over it.
1959    total_len(src_dims)?;
1960
1961    if scale == T::zero() {
1962        unsafe {
1963            if same_contiguous_layout(dest.dims(), &[dest.strides()]).is_some() {
1964                fill_contiguous(dest.as_mut_ptr(), total_len(dest.dims())?, T::zero());
1965            } else {
1966                fill_2d(
1967                    dest.as_mut_ptr(),
1968                    dest.dims()[0],
1969                    dest.dims()[1],
1970                    dest.strides()[0],
1971                    dest.strides()[1],
1972                    T::zero(),
1973                    exec,
1974                );
1975            }
1976        }
1977        return Ok(());
1978    }
1979
1980    let transpose_is_identity = element_transpose_is_identity::<T>();
1981
1982    unsafe {
1983        if transpose_is_identity
1984            && try_copy_transpose_scale_2d_f64_tiled_typed(dest, src, scale, exec.reborrow())
1985        {
1986            return Ok(());
1987        }
1988        if transpose_is_identity
1989            && try_copy_transpose_scale_2d_identity_tiled(dest, src, scale, exec.reborrow())
1990        {
1991            return Ok(());
1992        }
1993    }
1994
1995    if scale == T::one() && transpose_is_identity {
1996        let src_t = src.permute(&[1, 0])?;
1997        return crate::threading::copy_permuted(dest, &src_t, exec);
1998    }
1999
2000    unsafe {
2001        copy_transpose_scale_2d_loop(
2002            dest.as_mut_ptr(),
2003            dest.strides()[0],
2004            dest.strides()[1],
2005            src.ptr(),
2006            src.strides()[0],
2007            src.strides()[1],
2008            src_dims[0],
2009            src_dims[1],
2010            scale,
2011            exec,
2012        );
2013    }
2014    Ok(())
2015}
2016
2017#[cfg(test)]
2018#[path = "ops_view/tests/tiled_tests.rs"]
2019mod tiled_tests;
2020
2021#[cfg(test)]
2022#[path = "ops_view/tests/conj_route_tests.rs"]
2023mod conj_route_tests;