ndsparse 0.8.1

Sparse structures for N-dimensions
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
//! CSL (Compressed Sparse Line).
//!
//! A generalization of the [`CSC`]/[`CSR`] structures for N dimensions. Beware that this structure
//! doesn't make any distinction of what is a `column` or a `row` because the order of the elements
//! is up to the caller.
//!
//! [`CSC`]: en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_column_(CSC_or_CCS)
//! [`CSR`]: en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_row_(CSR,_CRS_or_Yale_format)

#![allow(
  // Serde
  clippy::integer_arithmetic
)]

mod csl_error;
mod csl_line_constructor;
mod csl_line_iter;
#[cfg(feature = "with-rayon")]
mod csl_rayon;
#[cfg(feature = "with-rand")]
mod csl_rnd;
mod csl_utils;

use crate::utils::{are_in_ascending_order, are_in_upper_bound, has_duplicates, max_nnz, windows2};
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use cl_traits::{Clear, Push, Storage, Truncate, WithCapacity};
use core::ops::Range;
#[cfg(feature = "with-rayon")]
pub use csl_rayon::*;
use csl_utils::*;
pub use {csl_error::*, csl_line_constructor::*, csl_line_iter::*};

/// CSL backed by a static array.
pub type CslArray<DATA, const D: usize, const N: usize, const O: usize> =
  Csl<[DATA; N], [usize; N], [usize; O], D>;
/// CSL backed by a mutable slice
pub type CslMut<'a, DATA, const D: usize> = Csl<&'a mut [DATA], &'a [usize], &'a [usize], D>;
/// CSL backed by a slice
pub type CslRef<'a, DATA, const D: usize> = Csl<&'a [DATA], &'a [usize], &'a [usize], D>;
/// CSL backed by a dynamic vector.
#[cfg(feature = "alloc")]
pub type CslVec<DATA, const D: usize> = Csl<Vec<DATA>, Vec<usize>, Vec<usize>, D>;

/// Base structure for all CSL* variants.
///
/// It is possible to define your own fancy CSL, e.g., `Csl<
///   staticvec::StaticVec<num_bigint::BigNum, 32>,
///   arrayvec::ArrayVec<[usize; 32]>,
///   smallvec::SmallVec<[usize; 321]>,
///   123
/// >`.
///
/// # Types
///
/// * `DA`: Dimensions Array
/// * `DS`: Data Storage
/// * `IS`: Indices Storage
/// * `OS`: Offsets Storage
#[cfg_attr(feature = "with-serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Csl<DS, IS, OS, const D: usize> {
  pub(crate) data: DS,
  #[cfg_attr(feature = "with-serde", serde(with = "serde_big_array::BigArray"))]
  pub(crate) dims: [usize; D],
  pub(crate) indcs: IS,
  pub(crate) offs: OS,
}

impl<DS, IS, OS, const D: usize> Csl<DS, IS, OS, D>
where
  DS: WithCapacity<Input = usize>,
  IS: WithCapacity<Input = usize>,
  OS: WithCapacity<Input = usize>,
{
  /// Creates an empty instance with initial capacity.
  ///
  /// For storages involving solely arrays, all arguments will be discarted.
  ///
  /// # Arguments
  ///
  /// * `nnz`: Number of Non-Zero elements
  /// * `nolp1`: Number Of Lines Plus 1, i.e., the dimensions product
  /// (without the innermost dimension) plus 1
  ///
  /// # Example
  #[cfg_attr(feature = "alloc", doc = "```rust")]
  #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
  /// use ndsparse::csl::CslVec;
  /// let dims = [11, 10, 1];
  /// let nolp1 = dims.iter().rev().skip(1).product::<usize>() + 1;
  /// let nnz = 2;
  /// let _ = CslVec::<i32, 3>::with_capacity(nnz, nolp1);
  /// ```
  #[inline]
  pub fn with_capacity(nnz: usize, nolp1: usize) -> Self {
    Self {
      data: DS::with_capacity(nnz),
      dims: cl_traits::default_array(),
      indcs: IS::with_capacity(nnz),
      offs: OS::with_capacity(nolp1),
    }
  }
}

impl<DS, IS, OS, const D: usize> Csl<DS, IS, OS, D> {
  /// The definitions of all dimensions.
  ///
  /// # Example
  ///
  /// ```rust
  /// use ndsparse::doc_tests::csl_array_4;
  /// assert_eq!(csl_array_4().dims(), &[2, 3, 4, 5]);
  /// ```
  #[inline]
  pub fn dims(&self) -> &[usize; D] {
    &self.dims
  }
}

impl<DATA, DS, IS, OS, const D: usize> Csl<DS, IS, OS, D>
where
  DS: AsRef<[DATA]> + Storage<Item = DATA>,
  IS: AsRef<[usize]>,
  OS: AsRef<[usize]>,
{
  /// Creates a valid CSL instance.
  ///
  /// The compressed fields are a bit complex and unless you really know what you are doing, this
  /// method shouldn't probably be used directly. Please, try to consider using [`#constructor`]
  /// instead.
  ///
  /// # Arguments
  ///
  /// * `dims`: Array of dimensions
  /// * `data`: Data collection
  /// * `indcs`: Indices of each data item
  /// * `offs`: Offset of each innermost line
  ///
  /// # Example
  #[cfg_attr(feature = "alloc", doc = "```rust")]
  #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
  /// use ndsparse::csl::{CslArray, CslVec};
  /// // Sparse array ([8, _, _, _, _, 9, _, _, _, _])
  /// let mut _sparse_array = CslArray::new([10], [8.0, 9.0], [0, 5], [0, 2]);
  /// // A bunch of nothing for your overflow needs
  /// let mut _over_nine: ndsparse::Result<CslVec<(), 9001>>;
  /// _over_nine = CslVec::new([0; 9001], vec![], vec![], vec![]);
  /// ```
  #[inline]
  pub fn new(dims: [usize; D], data: DS, indcs: IS, offs: OS) -> crate::Result<Self> {
    let data_ref = data.as_ref();
    let indcs_ref = indcs.as_ref();
    let offs_ref = offs.as_ref();

    let innermost_dim_is_zero = {
      let mut iter = dims.iter().copied();
      for dim in &mut iter {
        if dim != 0 {
          break;
        }
      }
      iter.any(|v| v == 0)
    };
    if innermost_dim_is_zero {
      return Err(CslError::InnermostDimsZero.into());
    }

    if data_ref.len() != indcs_ref.len() {
      return Err(CslError::DiffDataIndcsLength.into());
    }

    if !are_in_ascending_order(offs_ref, |a, b| [a, b]) {
      return Err(CslError::InvalidOffsetsOrder.into());
    }

    let data_indcs_length_greater_than_dims_length = {
      let max_nnz = max_nnz(&dims);
      data_ref.len() > max_nnz || indcs_ref.len() > max_nnz
    };
    if data_indcs_length_greater_than_dims_length {
      return Err(CslError::DataIndcsLengthGreaterThanDimsLength.into());
    }

    if let Some(last) = dims.last() {
      let are_in_upper_bound = are_in_upper_bound(indcs_ref, last);
      if !are_in_upper_bound {
        return Err(CslError::IndcsGreaterThanEqualDimLength.into());
      }
      if offs_ref.len() != correct_offs_len(&dims)? {
        return Err(CslError::InvalidOffsetsLength.into());
      }
    }

    let first_off = if let Some(r) = offs_ref.first().copied() {
      r
    } else {
      return Ok(Self { data, dims, indcs, offs });
    };

    if let Some(last_ref) = offs_ref.last() {
      if let Some(last) = last_ref.checked_sub(first_off) {
        if last != data_ref.len() || last != indcs_ref.len() {
          return Err(CslError::LastOffsetDifferentNnz.into());
        }
      }
    }

    let has_duplicated_indices = windows2(offs_ref).any(|[a, b]| {
      let fun = || {
        let first = a.checked_sub(first_off)?;
        let last = b.checked_sub(first_off)?;
        indcs_ref.get(first..last)
      };
      if let Some(indcs) = fun() {
        has_duplicates(indcs)
      } else {
        false
      }
    });
    if has_duplicated_indices {
      return Err(CslError::DuplicatedIndices.into());
    }

    Ok(Self { data, dims, indcs, offs })
  }

  /// The data that is being stored.
  ///
  /// # Example
  ///
  /// ```rust
  /// use ndsparse::doc_tests::csl_array_4;
  /// assert_eq!(csl_array_4().data(), &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
  /// ```
  #[inline]
  pub fn data(&self) -> &[DATA] {
    self.data.as_ref()
  }

  /// Indices (indcs) of a line, i.e., indices of the innermost dimension.
  ///
  /// # Example
  ///
  /// ```rust
  /// use ndsparse::doc_tests::csl_array_4;
  /// assert_eq!(csl_array_4().indcs(), &[0, 3, 1, 3, 4, 2, 2, 4, 2]);
  /// ```
  #[inline]
  pub fn indcs(&self) -> &[usize] {
    self.indcs.as_ref()
  }

  /// Any immutable line reference determined by `indcs`. The innermost dimension is ignored.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use ndsparse::{csl::CslRef, doc_tests::csl_array_4};
  /// let csl = csl_array_4();
  /// assert_eq!(csl.line([0, 0, 2, 0]), CslRef::new([5], &[][..], &[][..], &[3, 3][..]).ok());
  /// assert_eq!(csl.line([0, 1, 0, 0]), CslRef::new([5], &[6][..], &[2][..], &[5, 6][..]).ok());
  /// ```
  #[inline]
  pub fn line(&self, indcs: [usize; D]) -> Option<CslRef<'_, DATA, 1>> {
    line(self, indcs)
  }

  /// Number of NonZero elements.
  ///
  /// # Example
  ///
  /// ```rust
  /// use ndsparse::doc_tests::csl_array_4;
  /// assert_eq!(csl_array_4().nnz(), 9);
  /// ```
  #[inline]
  pub fn nnz(&self) -> usize {
    self.data.as_ref().len()
  }

  /// The joining of two consecutives offsets (offs) represent the starting and ending points of a
  /// line in the `data` and `indcs` slices.
  ///
  /// # Example
  ///
  /// ```rust
  /// use ndsparse::doc_tests::csl_array_4;
  /// assert_eq!(
  ///   csl_array_4().offs(),
  ///   &[0, 2, 3, 3, 5, 6, 6, 6, 6, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
  /// );
  /// ```
  #[inline]
  pub fn offs(&self) -> &[usize] {
    self.offs.as_ref()
  }

  /// Iterator that returns immutable line references of the outermost dimension
  ///
  /// # Examples
  ///
  /// ```rust
  /// # fn main() -> ndsparse::Result<()> {
  /// use ndsparse::{csl::CslRef, doc_tests::csl_array_4};
  /// let csl = csl_array_4();
  /// let sub_csl = csl.sub_dim(0..3).unwrap();
  /// let mut iter = sub_csl.outermost_line_iter()?;
  /// assert_eq!(
  ///   iter.next(),
  ///   CslRef::new([1, 4, 5], &[1, 2, 3, 4, 5][..], &[0, 3, 1, 3, 4][..], &[0, 2, 3, 3, 5][..]).ok()
  /// );
  /// assert_eq!(iter.next(), CslRef::new([1, 4, 5], &[6][..], &[2][..], &[5, 6, 6, 6, 6][..]).ok());
  /// assert_eq!(
  ///   iter.next(),
  ///   CslRef::new([1, 4, 5], &[7, 8][..], &[2, 4][..], &[6, 7, 8, 8, 8][..]).ok()
  /// );
  /// assert_eq!(iter.next(), None);
  /// # Ok(()) }
  #[inline]
  pub fn outermost_line_iter(&self) -> crate::Result<CslLineIterRef<'_, DATA, D>> {
    CslLineIterRef::new(self.dims, self.data.as_ref(), self.indcs.as_ref(), self.offs.as_ref())
  }

  /// Parallel iterator that returns all immutable line references of the current dimension
  /// using `rayon`.
  ///
  /// # Examples
  #[cfg_attr(all(feature = "alloc", feature = "with-rayon"), doc = "```rust")]
  #[cfg_attr(not(all(feature = "alloc", feature = "with-rayon")), doc = "```ignore")]
  /// # fn main() -> ndsparse::Result<()> {
  /// use ndsparse::doc_tests::csl_array_4;
  /// use rayon::prelude::*;
  /// let csl = csl_array_4();
  /// let outermost_rayon_iter = csl.outermost_line_rayon_iter()?;
  /// outermost_rayon_iter.enumerate().for_each(|(idx, csl_ref)| {
  ///   assert_eq!(csl_ref, csl.outermost_line_iter().unwrap().nth(idx).unwrap());
  /// });
  /// # Ok(()) }
  /// ```
  #[cfg(feature = "with-rayon")]
  #[inline]
  pub fn outermost_line_rayon_iter(
    &self,
  ) -> crate::Result<crate::ParallelIteratorWrapper<CslLineIterRef<'_, DATA, D>>> {
    Ok(crate::ParallelIteratorWrapper(self.outermost_line_iter()?))
  }

  /// Retrieves an immutable reference of any sub dimension.
  ///
  /// # Arguments
  ///
  /// * `range`: Starting and ending of the desired dimension
  ///
  /// # Example
  ///
  /// ```rust
  /// use ndsparse::{csl::CslRef, doc_tests::csl_array_4};
  /// let csl = csl_array_4();
  /// // The last cuboid
  /// assert_eq!(
  ///   csl.sub_dim(1..2),
  ///   CslRef::new([1, 3, 4, 5], &[9][..], &[2][..], &[8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9][..])
  ///     .ok()
  /// );
  /// // The last 2 matrices of the first cuboid;
  /// assert_eq!(
  ///   csl.sub_dim(1..3),
  ///   CslRef::new([2, 4, 5], &[6, 7, 8][..], &[2, 2, 4][..], &[5, 6, 6, 6, 6, 7, 8, 8, 8][..]).ok()
  /// );
  /// ```
  #[inline]
  pub fn sub_dim<const TD: usize>(&self, range: Range<usize>) -> Option<CslRef<'_, DATA, TD>> {
    sub_dim(self, range)
  }

  /// Retrieves an immutable reference of a single data value.
  ///
  /// # Arguments
  ///
  /// * `indcs`: Indices of all dimensions
  ///
  /// # Example
  ///
  /// ```rust
  /// use ndsparse::doc_tests::csl_array_4;
  /// let csl = csl_array_4();
  /// assert_eq!(csl.value([1, 0, 2, 2]), Some(&9));
  /// let line = csl.line([0, 0, 3, 0]).unwrap();
  /// assert_eq!(line.value([3]), Some(&4));
  /// ```
  #[inline]
  pub fn value(&self, indcs: [usize; D]) -> Option<&DATA> {
    let idx = data_idx(self, indcs)?;
    self.data.as_ref().get(idx)
  }
}

impl<DATA, DS, IS, OS, const D: usize> Csl<DS, IS, OS, D>
where
  DS: AsMut<[DATA]> + AsRef<[DATA]> + Storage<Item = DATA>,
  IS: AsRef<[usize]>,
  OS: AsRef<[usize]>,
{
  /// Clears all values and dimensions.
  ///
  /// # Example
  #[cfg_attr(feature = "alloc", doc = "```rust")]
  #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
  /// use ndsparse::{csl::CslVec, doc_tests::csl_vec_4};
  /// let mut csl = csl_vec_4();
  /// csl.clear();
  /// assert_eq!(csl, CslVec::default());
  /// ```
  #[inline]
  pub fn clear(&mut self)
  where
    DS: Clear,
    IS: Clear,
    OS: Clear,
  {
    self.dims = cl_traits::default_array();
    let _ = self.data.clear();
    let _ = self.indcs.clear();
    let _ = self.offs.clear();
  }

  /// See [`CslLineConstructor`](CslLineConstructor) for more information.
  #[inline]
  pub fn constructor(&mut self) -> crate::Result<CslLineConstructor<'_, DS, IS, OS, D>>
  where
    DS: Push<Input = DATA>,
    IS: Push<Input = usize>,
    OS: Push<Input = usize>,
  {
    CslLineConstructor::new(self)
  }

  /// Mutable version of [`data`](#method.data).
  #[inline]
  pub fn data_mut(&mut self) -> &mut [DATA] {
    self.data.as_mut()
  }

  /// Mutable version of [`line`](#method.line).
  #[inline]
  pub fn line_mut(&mut self, indcs: [usize; D]) -> Option<CslMut<'_, DATA, 1>> {
    line_mut(self, indcs)
  }

  /// Mutable version of [`outermost_line_iter`](#method.outermost_line_iter).
  #[inline]
  pub fn outermost_line_iter_mut(&mut self) -> crate::Result<CslLineIterMut<'_, DATA, D>> {
    CslLineIterMut::new(self.dims, self.data.as_mut(), self.indcs.as_ref(), self.offs.as_ref())
  }

  /// Mutable version of [`outermost_line_rayon_iter`](#method.outermost_line_rayon_iter).
  #[cfg(feature = "with-rayon")]
  #[inline]
  pub fn outermost_line_rayon_iter_mut(
    &mut self,
  ) -> crate::Result<crate::ParallelIteratorWrapper<CslLineIterMut<'_, DATA, D>>> {
    Ok(crate::ParallelIteratorWrapper(self.outermost_line_iter_mut()?))
  }

  /// Mutable version of [`sub_dim`](#method.sub_dim).
  #[inline]
  pub fn sub_dim_mut<const TD: usize>(
    &mut self,
    range: Range<usize>,
  ) -> Option<CslMut<'_, DATA, TD>> {
    sub_dim_mut(self, range)
  }

  /// Intra-swap a single data value.
  ///
  /// # Arguments
  ///
  /// * `a`: First set of indices
  /// * `b`: Second set of indices
  ///
  /// # Example
  #[cfg_attr(feature = "alloc", doc = "```rust")]
  #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
  /// use ndsparse::doc_tests::csl_vec_4;
  /// let mut csl = csl_vec_4();
  /// csl.swap_value([0, 0, 0, 0], [1, 0, 2, 2]);
  /// assert_eq!(csl.data(), &[9, 2, 3, 4, 5, 6, 7, 8, 1]);
  /// ```
  #[inline]
  pub fn swap_value(&mut self, a: [usize; D], b: [usize; D]) -> bool {
    if let Some(a_idx) = data_idx(self, a) {
      if let Some(b_idx) = data_idx(self, b) {
        self.data.as_mut().swap(a_idx, b_idx);
        return true;
      }
    }
    false
  }

  /// Truncates all values in the exactly exclusive line defined by `indcs`. The last index is ignored.
  ///
  /// # Example
  #[cfg_attr(feature = "alloc", doc = "```rust")]
  #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
  /// use ndsparse::{csl::CslVec, doc_tests::csl_vec_4};
  /// let mut csl = csl_vec_4();
  /// csl.truncate([0, 0, 3, 0]);
  /// assert_eq!(
  ///   Ok(csl),
  ///   CslVec::new([0, 0, 4, 5], vec![1, 2, 3], vec![0, 3, 1], vec![0, 2, 3, 3, 3])
  /// );
  /// ```
  #[inline]
  pub fn truncate(&mut self, indcs: [usize; D])
  where
    DS: Truncate<Input = usize>,
    IS: Truncate<Input = usize>,
    OS: AsMut<[usize]> + Truncate<Input = usize>,
  {
    let [offs_indcs, values] = if let Some(r) = line_offs(&self.dims, &indcs, self.offs.as_ref()) {
      r
    } else {
      return;
    };
    let cut_point = values.start;
    let _ = self.data.truncate(cut_point);
    let _ = self.indcs.truncate(cut_point);
    let _ = self.offs.truncate(offs_indcs.end);
    let iter = indcs.iter().zip(self.dims.iter_mut()).rev().skip(1).rev();
    iter.filter(|&(a, _)| *a == 0).for_each(|(_, b)| *b = 0);
    let before_last = if let Some(rslt) = self.offs.as_ref().get(offs_indcs.end.saturating_sub(2)) {
      *rslt
    } else {
      return;
    };
    if let Some(rslt) = self.offs.as_mut().get_mut(offs_indcs.end.saturating_sub(1)) {
      *rslt = before_last;
    }
  }

  /// Mutable version of [`value`](#method.value).
  #[inline]
  pub fn value_mut(&mut self, indcs: [usize; D]) -> Option<&mut DATA> {
    let idx = data_idx(self, indcs)?;
    self.data.as_mut().get_mut(idx)
  }
}

#[cfg(feature = "with-rand")]
impl<DATA, DS, IS, OS, const D: usize> Csl<DS, IS, OS, D>
where
  DS: AsMut<[DATA]> + AsRef<[DATA]> + Default + Push<Input = DATA> + Storage<Item = DATA>,
  IS: AsMut<[usize]> + AsRef<[usize]> + Default + Push<Input = usize>,
  OS: AsMut<[usize]> + AsRef<[usize]> + Default + Push<Input = usize>,
{
  /// Creates a new random and valid instance delimited by the passed arguments.
  ///
  /// # Arguments
  ///
  /// * `dims`: Array of dimensions
  /// * `nnz`: Number of Non-Zero elements
  /// * `rng`: `rand::Rng` trait
  /// * `cb`: Callback to control data creation
  ///
  /// # Example
  #[cfg_attr(feature = "alloc", doc = "```rust")]
  #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
  /// use ndsparse::csl::CslVec;
  /// use rand::{Rng, rngs::mock::StepRng};
  /// let mut rng = StepRng::new(0, 1);
  /// let dims = [1, 2, 3];
  /// let mut _random: ndsparse::Result<CslVec<u8, 3>>;
  /// _random = CslVec::new_controlled_random_rand(dims, 9, &mut rng, |r, _| r.gen());
  /// ```
  #[inline]
  pub fn new_controlled_random_rand<F, R>(
    dims: [usize; D],
    nnz: usize,
    rng: &mut R,
    cb: F,
  ) -> crate::Result<Self>
  where
    F: FnMut(&mut R, [usize; D]) -> DATA,
    R: rand::Rng,
  {
    let mut csl = Csl { dims, ..Default::default() };
    csl_rnd::CslRnd::new(&mut csl, nnz, rng)?.fill(cb).ok_or(crate::Error::UnknownError)?;
    Self::new(csl.dims, csl.data, csl.indcs, csl.offs)
  }

  /// Creates a new random and valid instance.
  ///
  /// # Arguments
  ///
  /// * `rng`: `rand::Rng` trait
  /// * `upper_bound`: The maximum allowed exclusive dimension
  ///
  /// # Example
  ///
  /// # Example
  #[cfg_attr(feature = "alloc", doc = "```rust")]
  #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
  /// # fn main() -> ndsparse::Result<()> {
  /// use ndsparse::csl::CslVec;
  /// use rand::{rngs::mock::StepRng, seq::SliceRandom};
  /// let mut rng = StepRng::new(0, 1);
  /// let upper_bound = 5;
  /// let random: ndsparse::Result<CslVec<u8, 8>>;
  /// random = CslVec::new_random_rand(&mut rng, upper_bound);
  /// assert!(random?.dims().choose(&mut rng).unwrap() < &upper_bound);
  /// # Ok(()) }
  #[inline]
  pub fn new_random_rand<R>(rng: &mut R, upper_bound: usize) -> crate::Result<Self>
  where
    R: rand::Rng,
    rand::distributions::Standard: rand::distributions::Distribution<DATA>,
  {
    let dims = crate::utils::valid_random_dims(rng, upper_bound);
    let max_nnz = max_nnz(&dims);
    let nnz = if max_nnz == 0 { 0 } else { rng.gen_range(0..max_nnz) };
    Self::new_controlled_random_rand(dims, nnz, rng, |rng, _| rng.gen())
  }
}

impl<DS, IS, OS, const D: usize> Default for Csl<DS, IS, OS, D>
where
  DS: Default,
  IS: Default,
  OS: Default,
{
  #[inline]
  fn default() -> Self {
    Self {
      data: Default::default(),
      dims: cl_traits::default_array(),
      indcs: Default::default(),
      offs: Default::default(),
    }
  }
}