strided-basic 0.4.6

Shared typed strided CPU primitives and copy/reduction execution.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! Execution contract for operation-family implementations.
//!
//! This module is the shared kernel-extension interface, not a public mirror
//! of implementation modules. Prevalidated entries require the caller to prove
//! the exact destination geometry and every omitted shape check. A layout marker
//! alone does not prove those obligations. Ordinary callers should use the
//! checked APIs at the crate root. All families share the same execution policy.
//!
//! # Examples
//!
//! ```
//! use strided_basic::{StridedArray, execution::*};
//! let src = StridedArray::<f64>::col_major(&[2]);
//! let mut dst = StridedArray::<f64>::col_major(&[2]);
//! let marker = validate_destination_layout_without_alloc(&[2], &[1]).unwrap();
//! // SAFETY: both arrays have shape [2], distinct storage, and the checked layout.
//! unsafe { map_into_validated(&mut dst.view_mut(), &src.view(), |x| x, marker) }.unwrap();
//! ```
//!
//! A marker alone does not make the prevalidated entry safe to call:
//!
//! ```compile_fail,E0133
//! use strided_basic::{StridedArray, execution::*};
//! let src = StridedArray::<f64>::col_major(&[2]);
//! let mut dst = StridedArray::<f64>::col_major(&[2]);
//! let marker = validate_destination_layout_without_alloc(&[2], &[1]).unwrap();
//! map_into_validated(&mut dst.view_mut(), &src.view(), |x| x, marker).unwrap();
//! ```
pub use crate::erased_common::{
    check_dtype, check_static_indexing_dtype, erased_view, validate_uninit_no_overlap,
};
pub use crate::kernel::{ensure_same_shape, KernelPlan, SMALL_TENSOR_THRESHOLD};
pub use crate::layout_check::is_injective_layout;
pub use crate::map_view::{validate_destination_layout_without_alloc, ValidatedDestinationLayout};
#[cfg(feature = "parallel")]
pub use crate::threading::{
    parallel_map_reduce, parallel_threads_for_len, SendPtr, MINTHREADLENGTH,
};

use crate::{ElementOp, MaybeSendSync, MaybeSync, Result, StridedView, StridedViewMut};

/// Prevalidated build plan fused for kernel-family implementations.
///
/// # Safety
/// All rank-indexed arrays must have matching lengths and a valid destination
/// index (when present). Shape products, stride magnitudes, cost arithmetic,
/// and every intermediate offset used by planning/iteration must be representable.
/// Iteration blocks must be positive and offsets must correspond to the supplied
/// layouts; threaded partitioning additionally requires positive thread counts,
/// costs and nonnegative spacing. Callback memory accesses must be valid for each generated
/// block, with disjoint mutable regions when partitions execute concurrently.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// let (dims, _, plan) = unsafe { build_plan_fused(&[2, 3], &[&[1, 2]], Some(0), 8) };
/// assert_eq!(dims.iter().product::<usize>(), 6);
/// assert_eq!(plan.block.len(), dims.len());
/// ```
#[inline]
pub unsafe fn build_plan_fused(
    dims: &[usize],
    strides_list: &[&[isize]],
    dest_index: Option<usize>,
    elem_size: usize,
) -> (Vec<usize>, Vec<Vec<isize>>, KernelPlan) {
    // SAFETY: the caller supplies the same invariants as the owning checked entry.
    crate::kernel::build_plan_fused(dims, strides_list, dest_index, elem_size)
}

/// Prevalidated build plan fused small for kernel-family implementations.
///
/// # Safety
/// All rank-indexed arrays must have matching lengths and a valid destination
/// index (when present). Shape products, stride magnitudes, cost arithmetic,
/// and every intermediate offset used by planning/iteration must be representable.
/// Iteration blocks must be positive and offsets must correspond to the supplied
/// layouts; threaded partitioning additionally requires positive thread counts,
/// costs and nonnegative spacing. Callback memory accesses must be valid for each generated
/// block, with disjoint mutable regions when partitions execute concurrently.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// let (dims, _, _) = unsafe { build_plan_fused_small(&[2, 3], &[&[1, 2]]) };
/// assert_eq!(dims.iter().product::<usize>(), 6);
/// ```
#[inline]
pub unsafe fn build_plan_fused_small(
    dims: &[usize],
    strides_list: &[&[isize]],
) -> (Vec<usize>, Vec<Vec<isize>>, KernelPlan) {
    // SAFETY: the caller supplies the same invariants as the owning checked entry.
    crate::kernel::build_plan_fused_small(dims, strides_list)
}

/// Prevalidated for each inner block preordered for kernel-family implementations.
///
/// # Safety
/// All rank-indexed arrays must have matching lengths and a valid destination
/// index (when present). Shape products, stride magnitudes, cost arithmetic,
/// and every intermediate offset used by planning/iteration must be representable.
/// Iteration blocks must be positive and offsets must correspond to the supplied
/// layouts; threaded partitioning additionally requires positive thread counts,
/// costs and nonnegative spacing. Callback memory accesses must be valid for each generated
/// block, with disjoint mutable regions when partitions execute concurrently.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// let mut count = 0;
/// unsafe { for_each_inner_block_preordered(&[4], &[4], &[vec![1]], &[0], |_, n, _| { count += n; Ok(()) }) }.unwrap();
/// assert_eq!(count, 4);
/// ```
///
/// # Errors
/// Forwards errors from the owning kernel or callback; callers must still
/// satisfy the safety contract before invoking this prevalidated entry.
#[inline]
pub unsafe fn for_each_inner_block_preordered<F>(
    dims: &[usize],
    blocks: &[usize],
    strides: &[Vec<isize>],
    initial_offsets: &[isize],
    f: F,
) -> Result<()>
where
    F: FnMut(&[isize], usize, &[isize]) -> Result<()>,
{
    // SAFETY: the caller supplies the same invariants as the owning checked entry.
    crate::kernel::for_each_inner_block_preordered::<F>(dims, blocks, strides, initial_offsets, f)
}

/// Prevalidated map into validated for kernel-family implementations.
///
/// # Safety
/// All input shapes must match the destination. `validated` must have been
/// obtained for this destination's current geometry, proving injectivity;
/// possessing a marker from another layout is not sufficient. View/descriptor
/// bounds and aliasing contracts must continue to hold throughout replay.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// use strided_basic::StridedArray;
/// let src = StridedArray::<f64>::from_parts(vec![2.0; 2], &[2], &[1], 0).unwrap();
/// let mut dst = StridedArray::<f64>::col_major(&[2]);
/// let checked = validate_destination_layout_without_alloc(&[2], &[1]).unwrap();
/// unsafe { map_into_validated(&mut dst.view_mut(), &src.view(), |a| a, checked) }.unwrap();
/// assert_eq!(dst.get(&[1]), 2.0);
/// ```
///
/// # Errors
/// Forwards errors from the owning kernel or callback; callers must still
/// satisfy the safety contract before invoking this prevalidated entry.
#[inline]
pub unsafe fn map_into_validated<
    D: Copy + MaybeSendSync,
    A: Copy + MaybeSendSync,
    Op: ElementOp<A>,
>(
    dest: &mut StridedViewMut<D>,
    src: &StridedView<A, Op>,
    f: impl Fn(A) -> D + MaybeSync,
    validated: ValidatedDestinationLayout,
) -> Result<()> {
    // SAFETY: the caller supplies the same invariants as the owning checked entry.
    crate::map_view::map_into_validated::<D, A, Op>(dest, src, f, validated)
}

/// Prevalidated zip map2 into validated for kernel-family implementations.
///
/// # Safety
/// All input shapes must match the destination. `validated` must have been
/// obtained for this destination's current geometry, proving injectivity;
/// possessing a marker from another layout is not sufficient. View/descriptor
/// bounds and aliasing contracts must continue to hold throughout replay.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// use strided_basic::StridedArray;
/// let src = StridedArray::<f64>::from_parts(vec![2.0; 2], &[2], &[1], 0).unwrap();
/// let mut dst = StridedArray::<f64>::col_major(&[2]);
/// let checked = validate_destination_layout_without_alloc(&[2], &[1]).unwrap();
/// unsafe { zip_map2_into_validated(&mut dst.view_mut(), &src.view(), &src.view(), |a, b| a + b, checked) }.unwrap();
/// assert_eq!(dst.get(&[1]), 4.0);
/// ```
///
/// # Errors
/// Forwards errors from the owning kernel or callback; callers must still
/// satisfy the safety contract before invoking this prevalidated entry.
#[inline]
pub unsafe fn zip_map2_into_validated<
    D: Copy + MaybeSendSync,
    A: Copy + MaybeSendSync,
    B: Copy + MaybeSendSync,
    OpA: ElementOp<A>,
    OpB: ElementOp<B>,
>(
    dest: &mut StridedViewMut<D>,
    a: &StridedView<A, OpA>,
    b: &StridedView<B, OpB>,
    f: impl Fn(A, B) -> D + MaybeSync,
    validated: ValidatedDestinationLayout,
) -> Result<()> {
    // SAFETY: the caller supplies the same invariants as the owning checked entry.
    crate::map_view::zip_map2_into_validated::<D, A, B, OpA, OpB>(dest, a, b, f, validated)
}

/// Prevalidated zip map3 into validated for kernel-family implementations.
///
/// # Safety
/// All input shapes must match the destination. `validated` must have been
/// obtained for this destination's current geometry, proving injectivity;
/// possessing a marker from another layout is not sufficient. View/descriptor
/// bounds and aliasing contracts must continue to hold throughout replay.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// use strided_basic::StridedArray;
/// let src = StridedArray::<f64>::from_parts(vec![2.0; 2], &[2], &[1], 0).unwrap();
/// let mut dst = StridedArray::<f64>::col_major(&[2]);
/// let checked = validate_destination_layout_without_alloc(&[2], &[1]).unwrap();
/// unsafe { zip_map3_into_validated(&mut dst.view_mut(), &src.view(), &src.view(), &src.view(), |a, b, c| a + b + c, checked) }.unwrap();
/// assert_eq!(dst.get(&[1]), 6.0);
/// ```
///
/// # Errors
/// Forwards errors from the owning kernel or callback; callers must still
/// satisfy the safety contract before invoking this prevalidated entry.
#[inline]
pub unsafe fn zip_map3_into_validated<
    D: Copy + MaybeSendSync,
    A: Copy + MaybeSendSync,
    B: Copy + MaybeSendSync,
    C: Copy + MaybeSendSync,
    OpA: ElementOp<A>,
    OpB: ElementOp<B>,
    OpC: ElementOp<C>,
>(
    dest: &mut StridedViewMut<D>,
    a: &StridedView<A, OpA>,
    b: &StridedView<B, OpB>,
    c: &StridedView<C, OpC>,
    f: impl Fn(A, B, C) -> D + MaybeSync,
    validated: ValidatedDestinationLayout,
) -> Result<()> {
    // SAFETY: the caller supplies the same invariants as the owning checked entry.
    crate::map_view::zip_map3_into_validated::<D, A, B, C, OpA, OpB, OpC>(
        dest, a, b, c, f, validated,
    )
}

/// Prevalidated zip map4 into validated for kernel-family implementations.
///
/// # Safety
/// All input shapes must match the destination. `validated` must have been
/// obtained for this destination's current geometry, proving injectivity;
/// possessing a marker from another layout is not sufficient. View/descriptor
/// bounds and aliasing contracts must continue to hold throughout replay.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// use strided_basic::StridedArray;
/// let src = StridedArray::<f64>::from_parts(vec![2.0; 2], &[2], &[1], 0).unwrap();
/// let mut dst = StridedArray::<f64>::col_major(&[2]);
/// let checked = validate_destination_layout_without_alloc(&[2], &[1]).unwrap();
/// unsafe { zip_map4_into_validated(&mut dst.view_mut(), &src.view(), &src.view(), &src.view(), &src.view(), |a, b, c, d| a + b + c + d, checked) }.unwrap();
/// assert_eq!(dst.get(&[1]), 8.0);
/// ```
///
/// # Errors
/// Forwards errors from the owning kernel or callback; callers must still
/// satisfy the safety contract before invoking this prevalidated entry.
#[inline]
pub unsafe fn zip_map4_into_validated<
    D: Copy + MaybeSendSync,
    A: Copy + MaybeSendSync,
    B: Copy + MaybeSendSync,
    C: Copy + MaybeSendSync,
    E: Copy + MaybeSendSync,
    OpA: ElementOp<A>,
    OpB: ElementOp<B>,
    OpC: ElementOp<C>,
    OpE: ElementOp<E>,
>(
    dest: &mut StridedViewMut<D>,
    a: &StridedView<A, OpA>,
    b: &StridedView<B, OpB>,
    c: &StridedView<C, OpC>,
    e: &StridedView<E, OpE>,
    f: impl Fn(A, B, C, E) -> D + MaybeSync,
    validated: ValidatedDestinationLayout,
) -> Result<()> {
    // SAFETY: the caller supplies the same invariants as the owning checked entry.
    crate::map_view::zip_map4_into_validated::<D, A, B, C, E, OpA, OpB, OpC, OpE>(
        dest, a, b, c, e, f, validated,
    )
}

/// Prevalidated map raw into validated for kernel-family implementations.
///
/// # Safety
/// All input shapes must match the destination. `validated` must have been
/// obtained for this destination's current geometry, proving injectivity;
/// possessing a marker from another layout is not sufficient. View/descriptor
/// bounds and aliasing contracts must continue to hold throughout replay.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// use strided_basic::{RawStridedRef, RawStridedMut, Identity};
/// let values = [2.0_f64; 2];
/// let src = RawStridedRef::new(&values, &[2], &[1], 0).unwrap();
/// let mut output = [0.0; 2];
/// let mut dst = RawStridedMut::new(&mut output, &[2], &[1], 0).unwrap();
/// let checked = validate_destination_layout_without_alloc(&[2], &[1]).unwrap();
/// unsafe { map_raw_into_validated::<f64, f64, Identity>(&mut dst, &src, |a| a, checked) }.unwrap();
/// assert_eq!(output, [2.0; 2]);
/// ```
///
/// # Errors
/// Forwards errors from the owning kernel or callback; callers must still
/// satisfy the safety contract before invoking this prevalidated entry.
#[inline]
pub unsafe fn map_raw_into_validated<
    D: Copy + MaybeSendSync,
    A: Copy + MaybeSendSync,
    Op: ElementOp<A>,
>(
    dest: &mut crate::RawStridedMut<'_, D>,
    src: &crate::RawStridedRef<'_, A>,
    f: impl Fn(A) -> D + MaybeSync,
    validated: ValidatedDestinationLayout,
) -> Result<()> {
    // SAFETY: the caller supplies the same invariants as the owning checked entry.
    crate::map_view::map_raw_into_validated::<D, A, Op>(dest, src, f, validated)
}

/// Prevalidated zip map2 raw into validated for kernel-family implementations.
///
/// # Safety
/// All input shapes must match the destination. `validated` must have been
/// obtained for this destination's current geometry, proving injectivity;
/// possessing a marker from another layout is not sufficient. View/descriptor
/// bounds and aliasing contracts must continue to hold throughout replay.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// use strided_basic::{RawStridedRef, RawStridedMut, Identity};
/// let values = [2.0_f64; 2];
/// let src = RawStridedRef::new(&values, &[2], &[1], 0).unwrap();
/// let mut output = [0.0; 2];
/// let mut dst = RawStridedMut::new(&mut output, &[2], &[1], 0).unwrap();
/// let checked = validate_destination_layout_without_alloc(&[2], &[1]).unwrap();
/// unsafe { zip_map2_raw_into_validated::<f64, f64, f64, Identity, Identity>(&mut dst, &src, &src, |a, b| a + b, checked) }.unwrap();
/// assert_eq!(output, [4.0; 2]);
/// ```
///
/// # Errors
/// Forwards errors from the owning kernel or callback; callers must still
/// satisfy the safety contract before invoking this prevalidated entry.
#[inline]
pub unsafe fn zip_map2_raw_into_validated<
    D: Copy + MaybeSendSync,
    A: Copy + MaybeSendSync,
    B: Copy + MaybeSendSync,
    OpA: ElementOp<A>,
    OpB: ElementOp<B>,
>(
    dest: &mut crate::RawStridedMut<'_, D>,
    a: &crate::RawStridedRef<'_, A>,
    b: &crate::RawStridedRef<'_, B>,
    f: impl Fn(A, B) -> D + MaybeSync,
    validated: ValidatedDestinationLayout,
) -> Result<()> {
    // SAFETY: the caller supplies the same invariants as the owning checked entry.
    crate::map_view::zip_map2_raw_into_validated::<D, A, B, OpA, OpB>(dest, a, b, f, validated)
}

#[cfg(feature = "parallel")]
/// Prevalidated compute costs for kernel-family implementations.
///
/// # Safety
/// All rank-indexed arrays must have matching lengths and a valid destination
/// index (when present). Shape products, stride magnitudes, cost arithmetic,
/// and every intermediate offset used by planning/iteration must be representable.
/// Iteration blocks must be positive and offsets must correspond to the supplied
/// layouts; threaded partitioning additionally requires positive thread counts,
/// costs and nonnegative spacing. Callback memory accesses must be valid for each generated
/// block, with disjoint mutable regions when partitions execute concurrently.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// let costs = unsafe { compute_costs(&[vec![1, 4], vec![1, 8]]) };
/// assert_eq!(costs, [2, 8]);
/// ```
#[inline]
pub unsafe fn compute_costs<S: AsRef<[isize]>>(all_strides: &[S]) -> Vec<isize> {
    // SAFETY: the caller supplies the same invariants as the owning checked entry.
    crate::fuse::compute_costs::<S>(all_strides)
}

#[cfg(feature = "parallel")]
/// Prevalidated mapreduce threaded for kernel-family implementations.
///
/// # Safety
/// All rank-indexed arrays must have matching lengths and a valid destination
/// index (when present). Shape products, stride magnitudes, cost arithmetic,
/// and every intermediate offset used by planning/iteration must be representable.
/// Iteration blocks must be positive and offsets must correspond to the supplied
/// layouts; threaded partitioning additionally requires positive thread counts,
/// costs and nonnegative spacing. Callback memory accesses must be valid for each generated
/// block, with disjoint mutable regions when partitions execute concurrently.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// use std::sync::atomic::{AtomicUsize, Ordering};
/// let count = AtomicUsize::new(0);
/// unsafe { mapreduce_threaded(&[4], &[4], &[vec![1]], &[0], &[2], 1, 0, 1, &|dims, _, _, _| { count.fetch_add(dims.iter().product::<usize>(), Ordering::Relaxed); Ok(()) }) }.unwrap();
/// assert_eq!(count.load(Ordering::Relaxed), 4);
/// ```
///
/// # Errors
/// Forwards errors from the owning kernel or callback; callers must still
/// satisfy the safety contract before invoking this prevalidated entry.
#[inline]
pub unsafe fn mapreduce_threaded<F>(
    dims: &[usize],
    blocks: &[usize],
    strides_list: &[Vec<isize>],
    offsets: &[isize],
    costs: &[isize],
    nthreads: usize,
    spacing: isize,
    taskindex: usize,
    f: &F,
) -> Result<()>
where
    F: Fn(&[usize], &[usize], &[Vec<isize>], &[isize]) -> Result<()> + Sync,
{
    // SAFETY: the caller supplies the same invariants as the owning checked entry.
    crate::threading::mapreduce_threaded::<F>(
        dims,
        blocks,
        strides_list,
        offsets,
        costs,
        nthreads,
        spacing,
        taskindex,
        f,
    )
}

#[cfg(feature = "parallel")]
pub use crate::execution_policy::rayon_threads;

/// Full-overwrite indexed replay for an operation-family adapter.
///
/// # Safety
/// The adapter must reject input/output overlap before creating the input
/// references. All descriptor allocation and initialization contracts must
/// remain valid for the call. Output slots may be uninitialized; the owning
/// plan retains its checked layout/index validation and private initialization
/// receipt. No initialized reference to the output backing may be formed.
/// Gather into uninitialized output without exposing an initialization receipt.
///
/// # Examples
///
/// ```
/// use strided_basic::{RawStridedRef, RawStridedMut};
/// use strided_basic::execution::*;
/// use core::mem::MaybeUninit;
/// use strided_basic::{GatherPlan, GatherSpec};
/// let spec = GatherSpec { offset_dims: vec![], collapsed_slice_dims: vec![0], start_index_map: vec![0], index_vector_dim: 1, slice_sizes: vec![1] };
/// let plan = GatherPlan::compile(&[3], &[1], &[2, 1], &[1, 2], &[2], &[1], spec).unwrap();
/// let src = RawStridedRef::new(&[1_i32, 2, 3], &[3], &[1], 0).unwrap();
/// let indices = RawStridedRef::new(&[0_i32, 2], &[2, 1], &[1, 2], 0).unwrap();
/// let mut values = [MaybeUninit::<i32>::uninit(); 2];
/// let mut dst = RawStridedMut::new(&mut values, &[2], &[1], 0).unwrap();
/// // SAFETY: input and output allocations are disjoint and layouts match the plan.
/// unsafe { gather_into_uninit(&plan, &mut dst, &src, &indices) }.unwrap();
/// assert_eq!(unsafe { values[1].assume_init() }, 3);
/// ```
///
/// # Errors
/// Forwards the plan layout/index validation errors before successful overwrite.
#[inline]
pub unsafe fn gather_into_uninit<T, I>(
    plan: &crate::GatherPlan,
    dest: &mut crate::RawStridedMut<'_, core::mem::MaybeUninit<T>>,
    operand: &crate::RawStridedRef<'_, T>,
    start_indices: &crate::RawStridedRef<'_, I>,
) -> Result<()>
where
    T: Copy + MaybeSendSync,
    I: crate::GatherIndex,
{
    plan.execute_uninit(dest, operand, start_indices)
}

/// Full-overwrite indexed replay for an operation-family adapter.
///
/// # Safety
/// The adapter must reject input/output overlap before creating the input
/// references. All descriptor allocation and initialization contracts must
/// remain valid for the call. Output slots may be uninitialized; the owning
/// plan retains its checked layout/index validation and private initialization
/// receipt. No initialized reference to the output backing may be formed.
///
/// # Examples
///
/// ```
/// use strided_basic::execution::*;
/// // SAFETY: the example supplies matching bounded layouts and disjoint storage.
/// use strided_basic::{DynamicSlicePlan, RawStridedRef, RawStridedMut};
/// use core::mem::MaybeUninit;
/// let plan = DynamicSlicePlan::compile(&[3], &[1], &[1], &[1], &[2], &[1], &[2]).unwrap();
/// let src = RawStridedRef::new(&[1_i32, 2, 3], &[3], &[1], 0).unwrap();
/// let starts = RawStridedRef::new(&[1_i32], &[1], &[1], 0).unwrap();
/// let mut values = [MaybeUninit::<i32>::uninit(); 2];
/// let mut dst = RawStridedMut::new(&mut values, &[2], &[1], 0).unwrap();
/// unsafe { dynamic_slice_into_uninit(&plan, &mut dst, &src, &starts) }.unwrap();
/// assert_eq!(unsafe { values[1].assume_init() }, 3);
/// ```
///
/// # Errors
/// Forwards errors from the owning kernel or callback; callers must still
/// satisfy the safety contract before invoking this prevalidated entry.
#[inline]
pub unsafe fn dynamic_slice_into_uninit<T, I>(
    plan: &crate::DynamicSlicePlan,
    dest: &mut crate::RawStridedMut<'_, core::mem::MaybeUninit<T>>,
    operand: &crate::RawStridedRef<'_, T>,
    starts: &crate::RawStridedRef<'_, I>,
) -> Result<()>
where
    T: Copy + MaybeSendSync,
    I: crate::GatherIndex,
{
    plan.execute_uninit(dest, operand, starts)
}

/// Full-overwrite indexed replay for an operation-family adapter.
///
/// # Safety
/// The adapter must reject input/output overlap before creating the input
/// references. All descriptor allocation and initialization contracts must
/// remain valid for the call. Output slots may be uninitialized; the owning
/// plan retains its checked layout/index validation and private initialization
/// receipt. No initialized reference to the output backing may be formed.
/// Copy the operand and overwrite its selected window.
///
/// # Examples
///
/// ```
/// use strided_basic::{RawStridedRef, RawStridedMut};
/// use strided_basic::execution::*;
/// use core::mem::MaybeUninit;
/// use strided_basic::DynamicUpdateSlicePlan;
/// let plan = DynamicUpdateSlicePlan::compile(&[3], &[1], &[1], &[1], &[1], &[1], &[3], &[1]).unwrap();
/// let src = RawStridedRef::new(&[1_i32, 2, 3], &[3], &[1], 0).unwrap();
/// let update = RawStridedRef::new(&[9_i32], &[1], &[1], 0).unwrap();
/// let starts = RawStridedRef::new(&[1_i32], &[1], &[1], 0).unwrap();
/// let mut values = [MaybeUninit::<i32>::uninit(); 3];
/// let mut dst = RawStridedMut::new(&mut values, &[3], &[1], 0).unwrap();
/// // SAFETY: all inputs are initialized and disjoint from the matching output.
/// unsafe { dynamic_update_into_uninit(&plan, &mut dst, &src, &update, &starts) }.unwrap();
/// assert_eq!(unsafe { values[1].assume_init() }, 9);
/// ```
///
/// # Errors
/// Forwards the plan layout/index validation errors.
#[inline]
pub unsafe fn dynamic_update_into_uninit<'a, T, I>(
    plan: &crate::DynamicUpdateSlicePlan,
    dest: &'a mut crate::RawStridedMut<'a, core::mem::MaybeUninit<T>>,
    operand: &crate::RawStridedRef<'_, T>,
    update: &crate::RawStridedRef<'_, T>,
    starts: &crate::RawStridedRef<'_, I>,
) -> Result<()>
where
    T: Copy + MaybeSendSync,
    I: crate::GatherIndex,
{
    plan.execute_uninit(dest, operand, update, starts)
}

/// Full-overwrite indexed replay for an operation-family adapter.
///
/// # Safety
/// The adapter must reject input/output overlap before creating the input
/// references. All descriptor allocation and initialization contracts must
/// remain valid for the call. Output slots may be uninitialized; the owning
/// plan retains its checked layout/index validation and private initialization
/// receipt. No initialized reference to the output backing may be formed.
/// Copy the operand before additive scatter into its initialized logical slots.
///
/// # Examples
///
/// ```
/// use strided_basic::{RawStridedRef, RawStridedMut};
/// use strided_basic::execution::*;
/// use core::mem::MaybeUninit;
/// use strided_basic::{ScatterPlan, ScatterSpec};
/// let spec = ScatterSpec { update_window_dims: vec![], inserted_window_dims: vec![0], scatter_dims_to_operand_dims: vec![0], index_vector_dim: 1 };
/// let plan = ScatterPlan::compile(&[3], &[1], &[1, 1], &[1, 1], &[1], &[1], &[3], &[1], spec).unwrap();
/// let src = RawStridedRef::new(&[1_i32, 2, 3], &[3], &[1], 0).unwrap();
/// let update = RawStridedRef::new(&[9_i32], &[1], &[1], 0).unwrap();
/// let indices = RawStridedRef::new(&[1_i64], &[1, 1], &[1, 1], 0).unwrap();
/// let mut values = [MaybeUninit::<i32>::uninit(); 3];
/// let mut dst = RawStridedMut::new(&mut values, &[3], &[1], 0).unwrap();
/// // SAFETY: all inputs are initialized and disjoint from the matching output.
/// unsafe { scatter_into_uninit(&plan, &mut dst, &src, &indices, &update, i32::wrapping_add) }.unwrap();
/// assert_eq!(unsafe { values[1].assume_init() }, 11);
/// ```
///
/// # Errors
/// Forwards the plan layout/index validation errors.
#[inline]
pub unsafe fn scatter_into_uninit<'a, T, I>(
    plan: &crate::ScatterPlan,
    dest: &'a mut crate::RawStridedMut<'a, core::mem::MaybeUninit<T>>,
    operand: &crate::RawStridedRef<'_, T>,
    scatter_indices: &crate::RawStridedRef<'_, I>,
    updates: &crate::RawStridedRef<'_, T>,
    combine: fn(T, T) -> T,
) -> Result<()>
where
    T: Copy + core::ops::Add<Output = T> + MaybeSendSync,
    I: crate::GatherIndex,
{
    plan.execute_uninit(dest, operand, scatter_indices, updates, combine)
}