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
#![no_std]
#![feature(core_intrinsics, step_trait)]

use core::intrinsics::{likely, unlikely};
use core::iter::Step;
use core::ops::{
  Bound::{Excluded, Included, Unbounded},
  RangeBounds,
};

use crate::utils::max_value;

mod utils;

/// The [`Iterator`](core::iter::Iterator)-implementing struct through which the functionality of
/// [`inc_by`](crate::IntoIncBy::inc_by) actually operates. Not useful by itself.
pub struct IncBy<T: Copy + Default + Step, const STEP: usize> {
  start: T,
  end: T,
  had_overflow: bool,
  was_unbound: bool,
}

/// The [`Iterator`](core::iter::Iterator)-implementing struct through which the functionality of
/// [`dec_by`](crate::IntoDecBy::dec_by) actually operates. Not useful by itself.
pub struct DecBy<T: Copy + Default + Step, const STEP: usize> {
  start: T,
  end: T,
  had_overflow: bool,
}

impl<T: Copy + Default + Step, const STEP: usize> IncBy<T, STEP> {
  #[inline(always)]
  fn new<R: RangeBounds<T>>(bounds: R) -> IncBy<T, STEP> {
    let start = match bounds.start_bound() {
      Included(&idx) => idx,
      Excluded(&idx) => idx,
      Unbounded => Default::default(),
    };
    let mut had_overflow = false;
    let mut was_unbound = false;
    let end = match bounds.end_bound() {
      Included(&idx) => {
        if let Some(res) = Step::forward_checked(idx, STEP) {
          res
        } else {
          had_overflow = true;
          idx
        }
      }
      Excluded(&idx) => {
        if let Some(res) = Step::forward_checked(idx, STEP - 1) {
          res
        } else {
          had_overflow = true;
          idx
        }
      }
      Unbounded => {
        was_unbound = true;
        Step::forward(Default::default(), max_value(&start))
      }
    };
    IncBy {
      start,
      end,
      had_overflow,
      was_unbound,
    }
  }
}

impl<T: Copy + Default + Step, const STEP: usize> DecBy<T, STEP> {
  #[inline(always)]
  fn new<R: RangeBounds<T>>(bounds: R) -> DecBy<T, STEP> {
    let start = match bounds.end_bound() {
      Included(&idx) => idx,
      Excluded(&idx) => Step::forward_checked(idx, 1).unwrap_or(idx),
      Unbounded => Step::forward(Default::default(), 1),
    };
    let mut had_overflow = false;
    let end = match bounds.start_bound() {
      Included(&idx) => {
        if let Some(res) = Step::forward_checked(idx, STEP) {
          res
        } else {
          had_overflow = true;
          idx
        }
      }
      Excluded(&idx) => {
        if let Some(res) = Step::forward_checked(idx, STEP + 1) {
          res
        } else {
          had_overflow = true;
          idx
        }
      }
      Unbounded => Default::default(),
    };
    DecBy {
      start,
      end,
      had_overflow,
    }
  }
}

impl<T: Copy + Default + Step, const STEP: usize> Iterator for IncBy<T, STEP> {
  type Item = T;

  #[inline(always)]
  fn next(&mut self) -> Option<T> {
    if unlikely(self.had_overflow) {
      self.had_overflow = false;
      let res = Some(self.start);
      self.start = Step::forward_checked(self.start, STEP).unwrap_or(self.start);
      res
    } else if let Some(end_back) = Step::backward_checked(self.end, STEP) {
      if likely(self.start <= end_back) {
        let res = Some(self.start);
        self.start = Step::forward(self.start, STEP);
        res
      } else if unlikely(self.was_unbound) {
        self.was_unbound = false;
        Some(self.start)
      } else {
        None
      }
    } else {
      None
    }
  }
}

impl<T: Copy + Default + Step, const STEP: usize> Iterator for DecBy<T, STEP> {
  type Item = T;

  #[inline(always)]
  fn next(&mut self) -> Option<T> {
    if unlikely(self.had_overflow) {
      self.had_overflow = false;
      Some(self.end)
    } else if let Some(start_forward) = Step::forward_checked(self.start, STEP) {
      if likely(start_forward <= self.end) {
        self.end = Step::backward(self.end, STEP);
        Some(self.end)
      } else {
        None
      }
    } else {
      None
    }
  }
}

/// A subtrait of [`RangeBounds<T>`](core::ops::RangeBounds) where `T` is `Copy + Default + Step`
/// that turns implementers of it into an instance of [`IncBy`][crate::IncBy] when
/// [`inc_by`](crate::IntoIncBy::inc_by) is called. Currently, the blanket implementation of this
/// trait exported from the crate for `RangeBounds` is the only possible useful implementation, but
/// it was decided not to make it a "sealed" trait in case additional methods are added in the
/// future that would be implementable by end-user code in a meaningfully varied way.
pub trait IntoIncBy<T: Copy + Default + Step>: RangeBounds<T> {
  /// Functionally equivalent to what [`step_by`](core::iter::Iterator::step_by) does when it is
  /// called through a primitive range, but written specifically with primitive ranges in mind such
  /// that it optimizes identically to a `while` loop in every case the author of this crate has
  /// examined so far.
  ///
  /// # Example usage:
  /// ```
  /// # use staticstep::*;
  /// // Exclusive, so prints: 'A C E'
  /// for i in ('A'..'G').inc_by::<2>() {
  ///   print!("{} ", i);
  /// }
  ///
  /// // Inclusive, so prints: '0 4 8 12'
  /// for i in (0isize..=12isize).inc_by::<4>() {
  ///   print!("{} ", i);
  /// }
  fn inc_by<const STEP: usize>(self) -> IncBy<T, STEP>;
}

/// A subtrait of [`RangeBounds<T>`](core::ops::RangeBounds) where `T` is `Copy + Default + Step`
/// that turns implementers of it into an instance of [`DecBy`][crate::DecBy] when
/// [`dec_by`](crate::IntoDecBy::dec_by) is called. Currently, the blanket implementation of this
/// trait exported from the crate for `RangeBounds` is the only possible useful implementation, but
/// it was decided not to make it a "sealed" trait in case additional methods are added in the
/// future that would be implementable by end-user code in a meaningfully varied way.
pub trait IntoDecBy<T: Copy + Default + Step>: RangeBounds<T> {
  /// Functionally equivalent to what [`step_by`](core::iter::Iterator::step_by) does when it is
  /// called through a primitive range, but specifically in reverse and operating directly on
  /// ranges that are themselves syntactically "backwards", while offering the same level of
  /// optimizability as [`inc_by`](crate::IntoIncBy::inc_by).
  ///
  /// # Example usage:
  /// ```
  /// # use staticstep::*;
  /// // Exclusive, so prints: 'G E C'
  /// for i in ('G'..'A').dec_by::<2>() {
  ///   print!("{} ", i);
  /// }
  ///
  /// // Inclusive, so prints: '4 1 -2'
  /// for i in (4isize..=-4isize).dec_by::<3>() {
  ///   print!("{} ", i);
  /// }
  fn dec_by<const STEP: usize>(self) -> DecBy<T, STEP>;
}

/// The actual implementation of [`IntoIncBy`](crate::IntoIncBy) for
/// [`RangeBounds`](core::ops::RangeBounds).
impl<T: Copy + Default + Step, R: RangeBounds<T>> IntoIncBy<T> for R {
  #[inline(always)]
  fn inc_by<const STEP: usize>(self) -> IncBy<T, STEP> {
    IncBy::<T, STEP>::new(self)
  }
}

/// The actual implementation of [`IntoDecBy`](crate::IntoDecBy) for
/// [`RangeBounds`](core::ops::RangeBounds).
impl<T: Copy + Default + Step, R: RangeBounds<T>> IntoDecBy<T> for R {
  #[inline(always)]
  fn dec_by<const STEP: usize>(self) -> DecBy<T, STEP> {
    DecBy::<T, STEP>::new(self)
  }
}