scirs2-core 0.4.2

Core utilities and common functionality for SciRS2 (scirs2-core)
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! # Iterator Utilities
//!
//! This module provides a rich collection of lazy iterator adaptors that are
//! commonly needed in scientific computing pipelines but absent from the
//! standard library.
//!
//! ## Adaptors Overview
//!
//! | Type / Function              | Description                                              |
//! |------------------------------|----------------------------------------------------------|
//! | [`WindowedIterator`]         | Sliding window with configurable step size               |
//! | [`ChunkedParallelIterator`]  | Parallel processing of non-overlapping chunks            |
//! | [`ZipLongest`]               | Zip two iterators, continuing past the shorter one       |
//! | [`GroupBy`]                  | Group consecutive equal-keyed elements                   |
//! | [`FlatScan`]                 | Stateful `flat_map` (like `scan` + `flat_map` combined)  |
//! | [`take_while_inclusive`]     | `take_while` that includes the first non-matching item   |
//!
//! ## Design Goals
//!
//! - Zero allocation in the hot path wherever possible.
//! - No `unwrap()` usage.
//! - Compatible with Rust's standard `Iterator` trait.
//! - `Send + Sync` where the underlying types allow it.

use std::collections::VecDeque;

// ---------------------------------------------------------------------------
// Helper types
// ---------------------------------------------------------------------------

/// The value produced by [`ZipLongest`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EitherOrBoth<A, B> {
    /// Both iterators yielded a value.
    Both(A, B),
    /// Only the left iterator yielded a value (right was exhausted).
    Left(A),
    /// Only the right iterator yielded a value (left was exhausted).
    Right(B),
}

// ---------------------------------------------------------------------------
// WindowedIterator
// ---------------------------------------------------------------------------

/// A sliding-window iterator that yields `Vec<T>` windows of size `window`
/// advancing by `step` elements each time.
///
/// - Windows smaller than `window` (at the end) are **not** emitted.
/// - `step` must be ≥ 1; values are clamped to 1 if zero is supplied.
///
/// # Examples
///
/// ```rust
/// use scirs2_core::iter_utils::WindowedIterator;
///
/// let v: Vec<i32> = (1..=6).collect();
/// let windows: Vec<_> = WindowedIterator::new(v.iter().copied(), 3, 1).collect();
/// assert_eq!(windows, vec![vec![1,2,3], vec![2,3,4], vec![3,4,5], vec![4,5,6]]);
/// ```
pub struct WindowedIterator<I: Iterator> {
    iter: I,
    window: usize,
    step: usize,
    buf: VecDeque<I::Item>,
    done: bool,
}

impl<I: Iterator> WindowedIterator<I>
where
    I::Item: Clone,
{
    /// Create a new `WindowedIterator`.
    ///
    /// # Arguments
    ///
    /// * `iter`   – Source iterator.
    /// * `window` – Window size (number of elements per yielded slice). Must be ≥ 1.
    /// * `step`   – Advance step between consecutive windows. Must be ≥ 1.
    pub fn new(iter: I, window: usize, step: usize) -> Self {
        let window = window.max(1);
        let step = step.max(1);
        Self {
            iter,
            window,
            step,
            buf: VecDeque::new(),
            done: false,
        }
    }
}

impl<I: Iterator> Iterator for WindowedIterator<I>
where
    I::Item: Clone,
{
    type Item = Vec<I::Item>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        // Fill the buffer up to `window` elements
        while self.buf.len() < self.window {
            match self.iter.next() {
                Some(item) => self.buf.push_back(item),
                None => {
                    self.done = true;
                    return None; // Not enough elements for a full window
                }
            }
        }

        let result: Vec<I::Item> = self.buf.iter().cloned().collect();

        // Advance by `step`
        for _ in 0..self.step {
            self.buf.pop_front();
        }

        Some(result)
    }
}

// ---------------------------------------------------------------------------
// ChunkedParallelIterator
// ---------------------------------------------------------------------------

/// An iterator that processes non-overlapping chunks of size `chunk_size`
/// using a user-supplied mapping function, potentially in parallel.
///
/// Each chunk is mapped to an output `Vec<Out>` by `f`, and the results are
/// yielded in-order.  When `parallel` is `true` the chunks are processed via
/// [`std::thread::scope`] threads; otherwise they are processed sequentially.
///
/// # Examples
///
/// ```rust
/// use scirs2_core::iter_utils::ChunkedParallelIterator;
///
/// let data: Vec<i32> = (1..=9).collect();
/// let mut results: Vec<i32> = Vec::new();
/// for chunk_result in ChunkedParallelIterator::new(data.as_slice(), 3, false, |chunk| {
///     chunk.iter().map(|&x| x * 2).collect()
/// }) {
///     results.extend(chunk_result);
/// }
/// assert_eq!(results, vec![2, 4, 6, 8, 10, 12, 14, 16, 18]);
/// ```
pub struct ChunkedParallelIterator<'a, T, Out, F>
where
    F: Fn(&[T]) -> Vec<Out>,
{
    data: &'a [T],
    chunk_size: usize,
    parallel: bool,
    f: F,
    pos: usize,
    _out: std::marker::PhantomData<Out>,
}

impl<'a, T, Out, F> ChunkedParallelIterator<'a, T, Out, F>
where
    F: Fn(&[T]) -> Vec<Out>,
{
    /// Create a new `ChunkedParallelIterator`.
    ///
    /// # Arguments
    ///
    /// * `data`       – Input data slice.
    /// * `chunk_size` – Number of elements per chunk (clamped to ≥ 1).
    /// * `parallel`   – If `true`, spawn a thread per chunk (requires `T: Send + Sync`, `F: Sync`, `Out: Send`).
    /// * `f`          – Mapping function applied to each chunk.
    pub fn new(data: &'a [T], chunk_size: usize, parallel: bool, f: F) -> Self {
        Self {
            data,
            chunk_size: chunk_size.max(1),
            parallel,
            f,
            pos: 0,
            _out: std::marker::PhantomData,
        }
    }
}

impl<'a, T, Out, F> Iterator for ChunkedParallelIterator<'a, T, Out, F>
where
    T: Send + Sync,
    Out: Send,
    F: Fn(&[T]) -> Vec<Out> + Sync,
{
    type Item = Vec<Out>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos >= self.data.len() {
            return None;
        }

        let end = (self.pos + self.chunk_size).min(self.data.len());
        let chunk = &self.data[self.pos..end];
        self.pos = end;

        if self.parallel && chunk.len() >= 2 {
            // Spawn a thread for this single chunk to simulate parallel dispatch.
            // In a real pipeline you would batch multiple chunks across threads;
            // this implementation demonstrates the thread-safety contract.
            let result = std::thread::scope(|s| {
                s.spawn(|| (self.f)(chunk)).join()
            });
            // If the thread panicked, fall back to sequential execution
            match result {
                Ok(v) => Some(v),
                Err(_) => Some((self.f)(chunk)),
            }
        } else {
            Some((self.f)(chunk))
        }
    }
}

// ---------------------------------------------------------------------------
// ZipLongest
// ---------------------------------------------------------------------------

/// Zip two iterators together, continuing past the shorter one.
///
/// Yields [`EitherOrBoth::Both`] when both iterators have values,
/// [`EitherOrBoth::Left`] when only `A` remains, and
/// [`EitherOrBoth::Right`] when only `B` remains.
///
/// # Examples
///
/// ```rust
/// use scirs2_core::iter_utils::{ZipLongest, EitherOrBoth};
///
/// let a = vec![1i32, 2, 3];
/// let b = vec![10i32, 20];
/// let zipped: Vec<_> = ZipLongest::new(a.into_iter(), b.into_iter()).collect();
/// assert_eq!(zipped, vec![
///     EitherOrBoth::Both(1, 10),
///     EitherOrBoth::Both(2, 20),
///     EitherOrBoth::Left(3),
/// ]);
/// ```
pub struct ZipLongest<A: Iterator, B: Iterator> {
    a: A,
    b: B,
    a_done: bool,
    b_done: bool,
}

impl<A: Iterator, B: Iterator> ZipLongest<A, B> {
    /// Create a new `ZipLongest` adaptor.
    pub fn new(a: A, b: B) -> Self {
        Self {
            a,
            b,
            a_done: false,
            b_done: false,
        }
    }
}

impl<A: Iterator, B: Iterator> Iterator for ZipLongest<A, B> {
    type Item = EitherOrBoth<A::Item, B::Item>;

    fn next(&mut self) -> Option<Self::Item> {
        let a_val = if self.a_done {
            None
        } else {
            let v = self.a.next();
            if v.is_none() {
                self.a_done = true;
            }
            v
        };

        let b_val = if self.b_done {
            None
        } else {
            let v = self.b.next();
            if v.is_none() {
                self.b_done = true;
            }
            v
        };

        match (a_val, b_val) {
            (Some(a), Some(b)) => Some(EitherOrBoth::Both(a, b)),
            (Some(a), None) => Some(EitherOrBoth::Left(a)),
            (None, Some(b)) => Some(EitherOrBoth::Right(b)),
            (None, None) => None,
        }
    }
}

// ---------------------------------------------------------------------------
// GroupBy
// ---------------------------------------------------------------------------

/// Group consecutive elements with the same key into `(key, Vec<item>)` pairs.
///
/// Only **consecutive** runs are grouped; elements with equal keys separated
/// by differing keys form independent groups (same semantics as Python's
/// `itertools.groupby`).
///
/// # Examples
///
/// ```rust
/// use scirs2_core::iter_utils::GroupBy;
///
/// let data = vec![1i32, 1, 2, 2, 2, 1];
/// let groups: Vec<_> = GroupBy::new(data.into_iter(), |&x| x).collect();
/// assert_eq!(groups, vec![
///     (1, vec![1, 1]),
///     (2, vec![2, 2, 2]),
///     (1, vec![1]),
/// ]);
/// ```
pub struct GroupBy<I, K, F>
where
    I: Iterator,
    K: PartialEq,
    F: Fn(&I::Item) -> K,
{
    iter: I,
    key_fn: F,
    peeked: Option<(K, I::Item)>,
}

impl<I, K, F> GroupBy<I, K, F>
where
    I: Iterator,
    K: PartialEq,
    F: Fn(&I::Item) -> K,
{
    /// Create a new `GroupBy` adaptor.
    ///
    /// # Arguments
    ///
    /// * `iter`   – Source iterator.
    /// * `key_fn` – Function mapping each element to its group key.
    pub fn new(iter: I, key_fn: F) -> Self {
        Self {
            iter,
            key_fn,
            peeked: None,
        }
    }
}

impl<I, K, F> Iterator for GroupBy<I, K, F>
where
    I: Iterator,
    K: PartialEq + Clone,
    F: Fn(&I::Item) -> K,
    I::Item: Clone,
{
    type Item = (K, Vec<I::Item>);

    fn next(&mut self) -> Option<Self::Item> {
        // Get the first element of the next group
        let (current_key, first_item) = match self.peeked.take() {
            Some(peeked) => peeked,
            None => {
                let item = self.iter.next()?;
                let key = (self.key_fn)(&item);
                (key, item)
            }
        };

        let mut group = vec![first_item];

        // Consume all consecutive elements with the same key
        loop {
            match self.iter.next() {
                None => break,
                Some(item) => {
                    let key = (self.key_fn)(&item);
                    if key == current_key {
                        group.push(item);
                    } else {
                        // Different key: store for next call
                        self.peeked = Some((key, item));
                        break;
                    }
                }
            }
        }

        Some((current_key, group))
    }
}

// ---------------------------------------------------------------------------
// FlatScan
// ---------------------------------------------------------------------------

/// A stateful `flat_map`: carries mutable state across calls and flattens
/// the returned iterators.
///
/// Like `Iterator::scan` but with a flattening step: `f` takes `(&mut state, item)`
/// and returns an `IntoIterator`.  All items from the returned iterator are
/// yielded before calling `f` again.
///
/// # Examples
///
/// ```rust
/// use scirs2_core::iter_utils::FlatScan;
///
/// // Running product: for each value x, emit [running_product, x]
/// let data = vec![2i64, 3, 4];
/// let result: Vec<i64> = FlatScan::new(
///     data.into_iter(),
///     1i64,
///     |state, x| {
///         *state *= x;
///         vec![*state, x]
///     },
/// ).collect();
/// assert_eq!(result, vec![2, 2, 6, 3, 24, 4]);
/// ```
pub struct FlatScan<I, S, F, Iter>
where
    I: Iterator,
    F: FnMut(&mut S, I::Item) -> Iter,
    Iter: IntoIterator,
{
    iter: I,
    state: S,
    f: F,
    buffer: std::collections::VecDeque<Iter::Item>,
}

impl<I, S, F, Iter> FlatScan<I, S, F, Iter>
where
    I: Iterator,
    F: FnMut(&mut S, I::Item) -> Iter,
    Iter: IntoIterator,
{
    /// Create a new `FlatScan` adaptor.
    ///
    /// # Arguments
    ///
    /// * `iter`  – Source iterator.
    /// * `state` – Initial state value.
    /// * `f`     – Function `(&mut state, item) -> impl IntoIterator`.
    pub fn new(iter: I, state: S, f: F) -> Self {
        Self {
            iter,
            state,
            f,
            buffer: VecDeque::new(),
        }
    }
}

impl<I, S, F, Iter> Iterator for FlatScan<I, S, F, Iter>
where
    I: Iterator,
    F: FnMut(&mut S, I::Item) -> Iter,
    Iter: IntoIterator,
{
    type Item = Iter::Item;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            // Drain any buffered output first
            if let Some(item) = self.buffer.pop_front() {
                return Some(item);
            }

            // Advance the source iterator
            let source_item = self.iter.next()?;
            let produced = (self.f)(&mut self.state, source_item);
            self.buffer.extend(produced);
        }
    }
}

// ---------------------------------------------------------------------------
// take_while_inclusive
// ---------------------------------------------------------------------------

/// Extension trait that adds [`take_while_inclusive`](IteratorExt::take_while_inclusive)
/// to all iterators.
pub trait IteratorExt: Iterator + Sized {
    /// Like `take_while`, but **includes** the first element for which the
    /// predicate returns `false`.
    ///
    /// Subsequent elements (after the first failing one) are discarded.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use scirs2_core::iter_utils::IteratorExt;
    ///
    /// let v: Vec<i32> = (1..=10).take_while_inclusive(|&x| x < 5).collect();
    /// assert_eq!(v, vec![1, 2, 3, 4, 5]);
    /// ```
    fn take_while_inclusive<P: FnMut(&Self::Item) -> bool>(
        self,
        predicate: P,
    ) -> TakeWhileInclusive<Self, P>;
}

impl<I: Iterator> IteratorExt for I {
    fn take_while_inclusive<P: FnMut(&Self::Item) -> bool>(
        self,
        predicate: P,
    ) -> TakeWhileInclusive<Self, P> {
        TakeWhileInclusive::new(self, predicate)
    }
}

/// Iterator returned by [`IteratorExt::take_while_inclusive`].
pub struct TakeWhileInclusive<I, P>
where
    I: Iterator,
    P: FnMut(&I::Item) -> bool,
{
    iter: I,
    predicate: P,
    done: bool,
}

impl<I, P> TakeWhileInclusive<I, P>
where
    I: Iterator,
    P: FnMut(&I::Item) -> bool,
{
    fn new(iter: I, predicate: P) -> Self {
        Self {
            iter,
            predicate,
            done: false,
        }
    }
}

impl<I, P> Iterator for TakeWhileInclusive<I, P>
where
    I: Iterator,
    P: FnMut(&I::Item) -> bool,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        let item = self.iter.next()?;
        if !(self.predicate)(&item) {
            self.done = true;
        }
        Some(item)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // --- WindowedIterator ---

    #[test]
    fn test_windowed_basic() {
        let v: Vec<i32> = (1..=5).collect();
        let windows: Vec<Vec<i32>> = WindowedIterator::new(v.into_iter(), 3, 1).collect();
        assert_eq!(
            windows,
            vec![vec![1, 2, 3], vec![2, 3, 4], vec![3, 4, 5]]
        );
    }

    #[test]
    fn test_windowed_step_2() {
        let v: Vec<i32> = (1..=6).collect();
        let windows: Vec<Vec<i32>> = WindowedIterator::new(v.into_iter(), 3, 2).collect();
        assert_eq!(windows, vec![vec![1, 2, 3], vec![3, 4, 5]]);
    }

    #[test]
    fn test_windowed_empty() {
        let v: Vec<i32> = vec![];
        let windows: Vec<Vec<i32>> = WindowedIterator::new(v.into_iter(), 3, 1).collect();
        assert!(windows.is_empty());
    }

    #[test]
    fn test_windowed_not_enough_elements() {
        let v = vec![1i32, 2];
        let windows: Vec<Vec<i32>> = WindowedIterator::new(v.into_iter(), 3, 1).collect();
        assert!(windows.is_empty());
    }

    // --- ChunkedParallelIterator ---

    #[test]
    fn test_chunked_sequential() {
        let data: Vec<i32> = (1..=9).collect();
        let mut results: Vec<i32> = Vec::new();
        for chunk_result in
            ChunkedParallelIterator::new(data.as_slice(), 3, false, |chunk| {
                chunk.iter().map(|&x| x * 2).collect()
            })
        {
            results.extend(chunk_result);
        }
        assert_eq!(results, vec![2, 4, 6, 8, 10, 12, 14, 16, 18]);
    }

    #[test]
    fn test_chunked_parallel() {
        let data: Vec<i32> = (1..=6).collect();
        let mut results: Vec<i32> = Vec::new();
        for chunk_result in
            ChunkedParallelIterator::new(data.as_slice(), 2, true, |chunk| {
                chunk.iter().map(|&x| x + 10).collect()
            })
        {
            results.extend(chunk_result);
        }
        assert_eq!(results, vec![11, 12, 13, 14, 15, 16]);
    }

    #[test]
    fn test_chunked_uneven() {
        let data: Vec<i32> = (1..=7).collect();
        let mut results: Vec<i32> = Vec::new();
        for chunk_result in
            ChunkedParallelIterator::new(data.as_slice(), 3, false, |chunk| {
                vec![chunk.iter().sum::<i32>()]
            })
        {
            results.extend(chunk_result);
        }
        // Sums of [1,2,3], [4,5,6], [7]
        assert_eq!(results, vec![6, 15, 7]);
    }

    // --- ZipLongest ---

    #[test]
    fn test_zip_longest_equal() {
        let a = vec![1i32, 2, 3];
        let b = vec![10i32, 20, 30];
        let zipped: Vec<_> = ZipLongest::new(a.into_iter(), b.into_iter()).collect();
        assert_eq!(
            zipped,
            vec![
                EitherOrBoth::Both(1, 10),
                EitherOrBoth::Both(2, 20),
                EitherOrBoth::Both(3, 30),
            ]
        );
    }

    #[test]
    fn test_zip_longest_left_longer() {
        let a = vec![1i32, 2, 3];
        let b = vec![10i32];
        let zipped: Vec<_> = ZipLongest::new(a.into_iter(), b.into_iter()).collect();
        assert_eq!(
            zipped,
            vec![
                EitherOrBoth::Both(1, 10),
                EitherOrBoth::Left(2),
                EitherOrBoth::Left(3),
            ]
        );
    }

    #[test]
    fn test_zip_longest_right_longer() {
        let a: Vec<i32> = vec![1];
        let b = vec![10i32, 20, 30];
        let zipped: Vec<_> = ZipLongest::new(a.into_iter(), b.into_iter()).collect();
        assert_eq!(
            zipped,
            vec![
                EitherOrBoth::Both(1, 10),
                EitherOrBoth::Right(20),
                EitherOrBoth::Right(30),
            ]
        );
    }

    #[test]
    fn test_zip_longest_empty() {
        let a: Vec<i32> = vec![];
        let b: Vec<i32> = vec![];
        let zipped: Vec<_> = ZipLongest::new(a.into_iter(), b.into_iter()).collect();
        assert!(zipped.is_empty());
    }

    // --- GroupBy ---

    #[test]
    fn test_group_by_consecutive() {
        let data = vec![1i32, 1, 2, 2, 2, 1];
        let groups: Vec<_> = GroupBy::new(data.into_iter(), |&x| x).collect();
        assert_eq!(
            groups,
            vec![(1, vec![1, 1]), (2, vec![2, 2, 2]), (1, vec![1]),]
        );
    }

    #[test]
    fn test_group_by_all_same() {
        let data = vec![5i32; 4];
        let groups: Vec<_> = GroupBy::new(data.into_iter(), |&x| x).collect();
        assert_eq!(groups, vec![(5, vec![5, 5, 5, 5])]);
    }

    #[test]
    fn test_group_by_all_different() {
        let data = vec![1i32, 2, 3];
        let groups: Vec<_> = GroupBy::new(data.into_iter(), |&x| x).collect();
        assert_eq!(
            groups,
            vec![(1, vec![1]), (2, vec![2]), (3, vec![3]),]
        );
    }

    #[test]
    fn test_group_by_empty() {
        let data: Vec<i32> = vec![];
        let groups: Vec<_> = GroupBy::new(data.into_iter(), |&x| x).collect();
        assert!(groups.is_empty());
    }

    // --- FlatScan ---

    #[test]
    fn test_flat_scan_running_product() {
        let data = vec![2i64, 3, 4];
        let result: Vec<i64> = FlatScan::new(data.into_iter(), 1i64, |state, x| {
            *state *= x;
            vec![*state, x]
        })
        .collect();
        assert_eq!(result, vec![2, 2, 6, 3, 24, 4]);
    }

    #[test]
    fn test_flat_scan_empty_output() {
        // f returns empty vec for odd elements, [x*10] for even
        let data = vec![1i32, 2, 3, 4];
        let result: Vec<i32> = FlatScan::new(data.into_iter(), (), |_state, x| {
            if x % 2 == 0 {
                vec![x * 10]
            } else {
                vec![]
            }
        })
        .collect();
        assert_eq!(result, vec![20, 40]);
    }

    #[test]
    fn test_flat_scan_empty_input() {
        let data: Vec<i32> = vec![];
        let result: Vec<i32> =
            FlatScan::new(data.into_iter(), 0i32, |_, x| vec![x]).collect();
        assert!(result.is_empty());
    }

    // --- TakeWhileInclusive ---

    #[test]
    fn test_take_while_inclusive_basic() {
        let v: Vec<i32> = (1..=10).take_while_inclusive(|&x| x < 5).collect();
        assert_eq!(v, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_take_while_inclusive_all_pass() {
        let v: Vec<i32> = (1..=5).take_while_inclusive(|&x| x < 100).collect();
        assert_eq!(v, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_take_while_inclusive_first_fails() {
        let v: Vec<i32> = (1..=5).take_while_inclusive(|&x| x < 1).collect();
        assert_eq!(v, vec![1]);
    }

    #[test]
    fn test_take_while_inclusive_empty() {
        let v: Vec<i32> = std::iter::empty::<i32>()
            .take_while_inclusive(|_| true)
            .collect();
        assert!(v.is_empty());
    }
}