jaaptools 0.1.14

I really just wanted to try publishing a package, but this contains stuff I find useful in many circumstances.
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
use core::iter::{Cycle, Peekable, Skip, Take};
use core::ops::{AddAssign, Sub};
use itertools::{Intersperse, Itertools};
use num::Num;
use std::time::Instant;

impl<T: Iterator + Itertools + Sized> IterJaap for T {}

pub trait IterJaap: Iterator + Itertools {
    /// Rotates the iterator to the left by n
    /// Only available for iterators with an exact size
    /// Sample:
    /// ```
    /// use jaaptools::iter::IterJaap;
    /// let iter = (0..5); // Your iterator here
    /// assert_eq!(iter.rotate_left(2).collect::<Vec<_>>(), [2,3,4,0,1]);
    /// ```
    /// The method above is also how this is implemented, where the RotateLeft struct is just a
    /// wrapper arount a `Take<Skip<Cycle<impl Iterator>>>`
    ///
    /// Note that this method could have unintended consequences if the encapsulated iterator has
    /// any side effects.
    fn rotate_left(self, n: usize) -> Rotate<Self>
    where
        Self: Clone + ExactSizeIterator,
    {
        let length = self.len();
        let n = n % length;
        self.cycle().skip(n).take(length)
    }

    /// Rotates the iterator to the right by n
    /// Only available for iterators with an exact size
    /// Sample:
    /// ```
    /// use jaaptools::iter::IterJaap;
    /// let iter = (0..5); // Your iterator here
    /// assert_eq!(iter.rotate_right(2).collect::<Vec<_>>(), [3,4,0,1,2]);
    /// ```
    /// The method above is also how this is implemented, where the `RotateRight` struct is just a
    /// wrapper arount a `Take<Skip<Cycle<impl Iterator>>>`
    ///
    /// Note that this method could have unintended consequences if the encapsulated iterator has
    /// any side effects.
    fn rotate_right(self, n: usize) -> Rotate<Self>
    where
        Self: Clone + ExactSizeIterator,
    {
        let length = self.len();
        let n = n % length; // Prevent unneccessary cycling
        self.cycle().skip(length - n).take(length)
    }

    /// Iterate over the accumulative sum of an iterator
    /// Example:
    /// ```
    /// use jaaptools::iter::IterJaap;
    /// let slice = [1, 2, 3, 4, 5];
    /// assert_eq!(
    ///     slice.into_iter().cumsum().collect::<Vec<_>>(),
    ///     [1, 3, 6, 10, 15]
    /// );
    /// ```
    /// This is analogous to the numpy `.cumsum()` method
    /// ```python
    /// import numpy as np
    /// a = np.array([1,2,3,4,5])
    /// assert a.cumsum() == np.array([1,3,6,10,15])
    /// ```
    fn cumsum(self) -> CumSum<Self>
    where
        Self: Sized,
        Self::Item: Default + AddAssign<Self::Item> + Copy,
    {
        CumSum {
            iter: self,
            acc: Self::Item::default(),
        }
    }

    /// Allows to peek back at the previous value
    /// This could also be considered the current value, depending on your perspective.
    /// ```
    /// use jaaptools::iter::IterJaap;
    /// let mut iterator = (3..10).backpeekable();
    /// assert_eq!(iterator.peek_back(), None);
    /// let _ = iterator.next();
    /// assert_eq!(iterator.peek_back(), Some(3));
    /// ```
    fn backpeekable(self) -> BackPeekable<Self>
    where
        Self: Sized,
    {
        BackPeekable {
            iter: self,
            previous: None,
        }
    }

    /// Intersperses `value` every `size` items
    /// ```
    /// use jaaptools::iter::IterJaap;
    ///
    /// let v1:Vec<_> = (0..7).intersperse_runs(2,-1).collect();
    /// assert_eq!(vec![0,1,-1,2,3,-1,4,5,-1,6], v1);
    /// ```
    fn intersperse_runs(self, size: usize, value: <Self as Iterator>::Item) -> IntersperseRuns<Self>
    where
        Self: Sized,
        <Self as Iterator>::Item: Clone,
    {
        IntersperseRuns {
            iter: self,
            size,
            index: 0,
            value,
            done_this: true,
        }
    }

    /// Does the same as `intersperse` but also adds the element to the start and end
    /// ```
    /// use jaaptools::iter::IterJaap;
    ///
    /// let v:Vec<_> = (1..=3).outersperse(0).collect();
    /// assert_eq!(v , vec![0,1,0,2,0,3,0]);
    /// ```
    fn outersperse(self, value: <Self as Iterator>::Item) -> Outersperse<Self>
    where
        Self: Sized,
        <Self as Iterator>::Item: Clone,
    {
        #[allow(unstable_name_collisions)]
        self.intersperse(value.clone()).surround(value)
    }

    /// Surround the iterator with a value at the start and end
    /// ```
    /// use jaaptools::iter::IterJaap;
    ///
    /// let v:Vec<_> = (0..3).surround(42).collect();
    /// assert_eq!(v , vec![42,0,1,2,42]);
    /// ```
    fn surround(self, value: <Self as Iterator>::Item) -> Surround<Self>
    where
        Self: Sized,
        <Self as Iterator>::Item: Clone,
    {
        self.prepend(value.clone()).append(value)
    }

    /// Prepends a single value to the iterator
    /// ```
    /// use jaaptools::iter::IterJaap;
    ///
    /// let v:Vec<_> = ["world","!"].into_iter().prepend("hello").collect();
    /// assert_eq!(v , vec!["hello","world","!"]);
    /// ```
    fn prepend(self, value: <Self as Iterator>::Item) -> Prepend<Self>
    where
        Self: Sized,
    {
        [value].into_iter().chain(self)
    }

    /// Appends a single value to the iterator
    /// ```
    /// use jaaptools::iter::IterJaap;
    ///
    /// let v:Vec<_> = ["hello","world"].into_iter().append("!").collect();
    /// assert_eq!(v , vec!["hello","world","!"]);
    /// ```
    fn append(self, value: <Self as Iterator>::Item) -> Append<Self>
    where
        Self: Sized,
    {
        self.chain([value].into_iter())
    }

    /// Returns an iterator that yield the time at which `next` was called
    /// This could be useful when doing a bunch of computations that can take a long time and you
    /// want to know at what time each was completed.
    fn timer() -> TimeIter {
        TimeIter
    }

    /// Iterate over consecutive pairs
    /// skips the last value if length is odd
    fn pairs(self) -> Pairs<Self>
    where
        Self: Sized,
    {
        Pairs { iter: self }
    }

    fn recursive_iterator<T, F>(init: T, f: F) -> RecursiveIterator<T, F>
    where
        T: Clone,
        F: Fn(&T) -> T,
    {
        RecursiveIterator {
            state: init,
            callback: f,
        }
    }

    /// Find the intersection between two sorted iterators without repeated values
    /// ```
    /// use jaaptools::iter::IterJaap;
    ///
    /// let iter1 = [2, 3, 5].into_iter();
    /// let iter2 = [2, 5, 6].into_iter();
    /// let intersection: Vec<_> = iter1.intersect(iter2).collect();
    /// assert_eq!(intersection, [2, 5]);
    /// ```
    fn intersect<I>(self, iter2: I) -> Intersection<Self, I>
    where
        I: Iterator,
        Self: Sized,
    {
        Intersection { iter1: self, iter2 }
    }

    /// Find the intersection between two sorted iterators without repeated values
    /// ```
    /// use jaaptools::iter::IterJaap;
    ///
    /// let iter = [1, 2, 3, 5, 6, 8, 10,11].into_iter();
    /// let result: Vec<_> = iter.collapse_consecutives().collect();
    /// assert_eq!(result, [3,6,8,11]);
    /// ```
    fn collapse_consecutives(self) -> CollapseConsecutives<Self>
    where
        Self: Sized,
    {
        CollapseConsecutives {
            iter: self.peekable(),
        }
    }

    /// Returns the difference between consecutive elements
    /// A zero element is implicity prepended to the iterator
    /// ```
    /// use jaaptools::iter::IterJaap;
    ///
    /// let iter = [3,4,7,5,8].into_iter();
    /// let result = iter.difference().collect::<Vec<_>>();
    /// assert_eq!(result, [3,1,3,-2,3]);
    ///
    /// let iter = [0,4,5].into_iter();
    /// let result = iter.difference().collect::<Vec<_>>();
    /// assert_eq!(result, [0,4,1]);
    fn difference(self) -> Difference<Self>
    where
        Self: Sized,
        Self::Item: Copy + Sub,
    {
        Difference {
            iter: self.backpeekable(),
        }
    }
}

pub type Rotate<T> = Take<Skip<Cycle<T>>>;
pub type Append<T> = std::iter::Chain<T, std::array::IntoIter<<T as Iterator>::Item, 1>>;
pub type Prepend<T> = std::iter::Chain<std::array::IntoIter<<T as Iterator>::Item, 1>, T>;
/// Type alias for the return of surround
pub type Surround<T> = Append<Prepend<T>>;
/// Type alias for the return of outersperse
pub type Outersperse<T> = Surround<Intersperse<T>>;

pub struct TimeIter;

impl Iterator for TimeIter {
    type Item = Instant;
    fn next(&mut self) -> Option<Self::Item> {
        Some(Instant::now())
    }
}

pub struct IntersperseRuns<I>
where
    I: Iterator,
    <I as Iterator>::Item: Clone,
{
    iter: I,
    size: usize,
    index: usize,
    value: <I as Iterator>::Item,
    done_this: bool,
}

impl<I> Iterator for IntersperseRuns<I>
where
    I: Iterator,
    <I as Iterator>::Item: Clone,
{
    type Item = <I as Iterator>::Item;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index % self.size == 0 && !self.done_this {
            self.done_this = true;
            Some(self.value.clone())
        } else {
            self.done_this = false;
            self.index += 1;
            self.iter.next()
        }
    }
}

pub struct BackPeekable<I>
where
    I: Iterator,
{
    iter: I,
    previous: Option<<I as Iterator>::Item>,
}

impl<I> Iterator for BackPeekable<I>
where
    I: Iterator,
    <I as Iterator>::Item: Copy,
{
    type Item = <I as Iterator>::Item;

    fn next(&mut self) -> Option<Self::Item> {
        self.previous = self.iter.next();
        self.previous
    }
}

impl<I> BackPeekable<I>
where
    I: Iterator,
    <I as Iterator>::Item: Copy,
{
    pub fn peek_back(&self) -> Option<<Self as Iterator>::Item> {
        self.previous
    }
}

#[derive(Debug)]
pub struct CumSum<I>
where
    I: Iterator,
    I::Item: Default + AddAssign<I::Item> + Copy,
{
    iter: I,
    acc: I::Item,
}

impl<I> Iterator for CumSum<I>
where
    I: Iterator,
    I::Item: Default + AddAssign<I::Item> + Copy,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        self.acc += self.iter.next()?;
        Some(self.acc)
    }
}

#[derive(Debug)]
pub struct Pairs<I: Iterator> {
    iter: I,
}

impl<I> Iterator for Pairs<I>
where
    I: Iterator,
{
    type Item = (I::Item, I::Item);

    fn next(&mut self) -> Option<Self::Item> {
        let first = self.iter.next()?;
        let second = self.iter.next()?;
        Some((first, second))
    }
}

#[derive(Debug)]
pub struct RecursiveIterator<T, F>
where
    F: Fn(&T) -> T,
    T: Clone,
{
    state: T,
    callback: F,
}

impl<T, F> Iterator for RecursiveIterator<T, F>
where
    F: Fn(&T) -> T,
    T: Clone,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        let next_state = (self.callback)(&self.state);
        self.state = next_state.clone();
        Some(next_state)
    }
}

pub struct CollapseConsecutives<I>
where
    I: Iterator,
{
    iter: Peekable<I>,
}

impl<I> Iterator for CollapseConsecutives<I>
where
    I: Iterator<Item = usize>,
{
    type Item = I::Item;
    fn next(&mut self) -> Option<Self::Item> {
        let next_value = self.iter.next()?;
        match self.iter.peek() {
            Some(&value) if value == next_value + 1 => self.next(),
            _ => Some(next_value),
        }
    }
}

pub struct Intersection<I, J>
where
    I: Iterator,
    J: Iterator,
{
    iter1: I,
    iter2: J,
}

impl<I, J> Intersection<I, J>
where
    I: Iterator,
    J: Iterator,
    I::Item: Eq,
    J::Item: Eq,
{
    pub fn new(iter1: I, iter2: J) -> Self {
        Self { iter1, iter2 }
    }
}

impl<I, J, T> Iterator for Intersection<I, J>
where
    I: Iterator<Item = T>,
    J: Iterator<Item = T>,
    T: Ord,
{
    type Item = T;
    fn next(&mut self) -> Option<Self::Item> {
        let mut v1 = self.iter1.next()?;
        let mut v2 = self.iter2.next()?;
        loop {
            if v1 < v2 {
                v1 = self.iter1.next()?;
            } else if v1 > v2 {
                v2 = self.iter2.next()?;
            } else {
                break Some(v1);
            }
        }
    }
}

pub struct Difference<I>
where
    I: Iterator,
    I::Item: Sub + Copy,
{
    iter: BackPeekable<I>,
}

impl<I> Iterator for Difference<I>
where
    I: Iterator,
    I::Item: Sub<Output = I::Item> + Copy + Default,
{
    type Item = I::Item;
    fn next(&mut self) -> Option<Self::Item> {
        let last = self.iter.peek_back().unwrap_or(Default::default());
        self.iter.next().map(|next| next - last)
    }
}

pub trait SumResult<T: Num, E>: Iterator<Item = Result<T, E>> {
    /// Sums the values of an Iterator over Result Values, shortcutting if it finds an Err
    /// This allows summing with constant stack space and no heap space, rather than the
    /// default way of first collecting into a Vec and then summing.
    fn sum_result(self) -> Result<T, E>
    where
        Self: Sized,
    {
        let mut acc = T::zero();
        for item in self {
            acc = acc + item?;
        }
        Ok(acc)
    }
}

impl<T: Num, E, I: Iterator<Item = Result<T, E>>> SumResult<T, E> for I {}