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
use crate::{csl::Csl, Dims};
use cl_traits::{Push, Storage};
use core::fmt;

/// Constructs valid lines in a easy and interactive manner, abstracting away the complexity
/// of the compressed sparse format.
#[derive(Debug, PartialEq)]
pub struct CslLineConstructor<'a, DA, DS, IS, PS>
where
  DA: Dims,
{
  csl: &'a mut Csl<DA, DS, IS, PS>,
  curr_dim_idx: usize,
  last_off: usize,
}

impl<'a, DA, DATA, DS, IS, PS> CslLineConstructor<'a, DA, DS, IS, PS>
where
  DA: Dims,
  DS: AsRef<[DATA]> + Push<Input = DATA> + Storage<Item = DATA>,
  IS: AsRef<[usize]> + Push<Input = usize>,
  PS: AsRef<[usize]> + Push<Input = usize>,
{
  pub(crate) fn new(csl: &'a mut Csl<DA, DS, IS, PS>) -> crate::Result<Self> {
    if DA::CAPACITY == 0 {
      return Err(CslLineConstructorError::EmptyDimension.into());
    }
    let curr_dim_idx = if let Some(idx) = csl.dims.slice().iter().copied().position(|x| x != 0) {
      idx
    } else {
      csl.dims.slice().len()
    };
    let last_off = Self::last_off(&*csl);
    Ok(Self { csl, curr_dim_idx, last_off })
  }

  /// Jumps to the next outermost dimension, i.e., from right to left.
  ///
  /// # Example
  #[cfg_attr(feature = "alloc", doc = "```rust")]
  #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
  /// # fn main() -> ndsparse::Result<()> {
  /// use ndsparse::csl::{CslRef, CslVec};
  /// let mut csl = CslVec::<[usize; 3], i32>::default();
  /// csl
  ///   .constructor()?
  ///   .next_outermost_dim(3)?
  ///   .push_line([(0, 1)].iter().copied())?
  ///   .next_outermost_dim(4)?
  ///   .push_line([(1, 2)].iter().copied())?
  ///   .push_empty_line()
  ///   .push_line([(0, 3), (1,4)].iter().copied())?;
  /// assert_eq!(
  ///   csl.sub_dim(0..4),
  ///   CslRef::new([4, 3], &[1, 2, 3, 4][..], &[0, 1, 0, 1][..], &[0, 1, 2, 2, 4][..]).ok()
  /// );
  /// # Ok(()) }
  pub fn next_outermost_dim(mut self, len: usize) -> crate::Result<Self> {
    self.curr_dim_idx =
      self.curr_dim_idx.checked_sub(1).ok_or(CslLineConstructorError::DimsOverflow)?;
    *self.curr_dim() = len;
    Ok(self)
  }

  /// This is the same as `push_line([].iter(), [].iter())`.
  ///
  /// # Example
  #[cfg_attr(feature = "alloc", doc = "```rust")]
  #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
  /// # fn main() -> ndsparse::Result<()> {
  /// use ndsparse::csl::{CslRef, CslVec};
  /// let mut csl = CslVec::<[usize; 3], i32>::default();
  /// let constructor = csl.constructor()?.next_outermost_dim(3)?;
  /// constructor.push_empty_line().next_outermost_dim(2)?.push_empty_line();
  /// assert_eq!(csl.line([0, 0, 0]), CslRef::new([3], &[][..], &[][..], &[0, 0][..]).ok());
  /// # Ok(()) }
  pub fn push_empty_line(self) -> Self {
    self.csl.offs.push(self.last_off);
    self
  }

  /// Pushes a new compressed line, modifying the internal structure and if applicable,
  /// increases the current dimension length.
  ///
  /// The iterator will be truncated to (usize::Max - last offset value + 1) or (last dimension value)
  /// and it can lead to a situation where no values will be inserted.
  ///
  /// # Arguments
  ///
  /// * `data`:  Iterator of cloned items.
  /// * `indcs`: Iterator of the respective indices of each item.
  ///
  /// # Example
  #[cfg_attr(feature = "alloc", doc = "```rust")]
  #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
  /// # fn main() -> ndsparse::Result<()> {
  /// use ndsparse::csl::{CslRef, CslVec};
  /// let mut csl = CslVec::<[usize; 3], i32>::default();
  /// csl.constructor()?.next_outermost_dim(50)?.push_line([(1, 1), (40, 2)].iter().copied())?;
  /// let line = csl.line([0, 0, 0]);
  /// assert_eq!(line, CslRef::new([50], &[1, 2][..], &[1, 40][..], &[0, 2][..]).ok());
  /// # Ok(()) }
  pub fn push_line<DI>(mut self, di: DI) -> crate::Result<Self>
  where
    DI: Iterator<Item = (usize, DATA)>,
  {
    let nnz_iter = 1..self.last_dim().saturating_add(1);
    let off_iter = self.last_off.saturating_add(1)..;
    let mut iter = off_iter.zip(nnz_iter.zip(di));
    let mut last_off = self.last_off;
    let mut nnz = 0;

    let mut push = |curr_last_off, curr_nnz, idx, value| {
      self.csl.indcs.push(idx);
      self.csl.data.push(value);
      nnz = curr_nnz;
      last_off = curr_last_off;
    };

    let mut last_line_idx = if let Some((curr_last_off, (curr_nnz, (idx, value)))) = iter.next() {
      push(curr_last_off, curr_nnz, idx, value);
      idx
    } else {
      return Ok(self.push_empty_line());
    };

    for (curr_last_off, (curr_nnz, (idx, value))) in iter {
      if idx <= last_line_idx {
        return Err(CslLineConstructorError::UnsortedIndices.into());
      }
      push(curr_last_off, curr_nnz, idx, value);
      last_line_idx = idx;
    }

    if nnz == 0 {
      return Ok(self.push_empty_line());
    }
    self.csl.offs.push(last_off);
    self.last_off = last_off;
    Ok(self)
  }

  // self.curr_dim_idx always points to a valid reference
  #[allow(clippy::unwrap_used)]
  fn curr_dim(&mut self) -> &mut usize {
    self.csl.dims.slice_mut().get_mut(self.curr_dim_idx).unwrap()
  }

  // Constructor doesn't contain empty dimensions
  #[allow(clippy::unwrap_used)]
  fn last_dim(&mut self) -> usize {
    *self.csl.dims.slice().last().unwrap()
  }

  // Always have at least one element
  #[allow(clippy::unwrap_used)]
  fn last_off(csl: &Csl<DA, DS, IS, PS>) -> usize {
    *csl.offs.as_ref().last().unwrap()
  }
}

/// Contains all errors related to CslLineConstructor.
#[derive(Debug, PartialEq)]
pub enum CslLineConstructorError {
  /// The maximum number of dimenstions has been reached
  DimsOverflow,
  /// All indices must be in ascending order
  UnsortedIndices,
  /// It isn't possible to construct new elements in an empty dimension
  EmptyDimension,
  /// The maximum number of lines for the currention dimension has been reached
  MaxNumOfLines,
}

impl fmt::Display for CslLineConstructorError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let s = match self {
      Self::DimsOverflow => "DimsOverflow",
      Self::UnsortedIndices => "UnsortedIndices",
      Self::EmptyDimension => "EmptyDimension",
      Self::MaxNumOfLines => "MaxNumOfLines",
    };
    write!(f, "{}", s)
  }
}

#[cfg(feature = "std")]
impl std::error::Error for CslLineConstructorError {}