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
//! Push-pull dataflow network.
//!
//! A dataflow network is a directed acyclic graph (DAG) of processing nodes.
//! Data flows from [`Source`] nodes, through transformation nodes ([`Map`],
//! [`Filter`], [`Zip`], [`Buffer`]), and is consumed by [`Sink`] nodes.
//!
//! ## Execution model
//!
//! The network is **lazy on the pull side** and **eager on the push side**:
//!
//! - Each node implements the [`DataflowNode<T>`] trait that exposes both
//!   `push` (send a value downstream) and `pull` (request the next value from
//!   upstream).
//! - [`DataflowGraph`] manages a set of named nodes and their connections.
//!   Calling [`DataflowGraph::run`] drains all `Source` nodes, pushing every
//!   available value through the graph in topological order.
//!
//! ## Example
//!
//! ```rust
//! use scirs2_core::reactive::dataflow::{DataflowGraph, Source, Map, Filter, Sink};
//!
//! let mut graph = DataflowGraph::new();
//! let src = Source::from_iter(0..10i32);
//! let map = Map::new(|x: i32| x * 2);
//! let filter = Filter::new(|x: &i32| *x > 8);
//! let sink: Sink<i32> = Sink::new();
//!
//! let src_id = graph.add_source(src);
//! let map_id = graph.add_map(map);
//! let flt_id = graph.add_filter(filter);
//! let snk_id = graph.add_sink(sink);
//!
//! graph.connect(src_id, map_id);
//! graph.connect(map_id, flt_id);
//! graph.connect(flt_id, snk_id);
//!
//! graph.run();
//!
//! let results = graph.collect_sink(snk_id);
//! assert_eq!(results, vec![10, 12, 14, 16, 18]);
//! ```

use std::sync::{Arc, Mutex};

// ---------------------------------------------------------------------------
// NodeId
// ---------------------------------------------------------------------------

/// Opaque node identifier within a [`DataflowGraph`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NodeId(usize);

// ---------------------------------------------------------------------------
// DataflowNode trait (type-erased)
// ---------------------------------------------------------------------------

/// Trait for nodes in the dataflow graph.
///
/// Both `push` and `pull` are provided so a node can act as either a consumer
/// (pull from upstream, push downstream) or a pure transformer.
pub trait DataflowNode<T>: Send + Sync {
    /// Push a value into this node.  The node may buffer or forward it.
    fn push(&self, value: T);

    /// Pull the next available value from this node's output queue.
    fn pull(&self) -> Option<T>;
}

// ---------------------------------------------------------------------------
// Source<T>
// ---------------------------------------------------------------------------

struct SourceInner<T> {
    buffer: std::collections::VecDeque<T>,
}

/// A source node that produces values from an iterator or via manual push.
pub struct Source<T> {
    inner: Arc<Mutex<SourceInner<T>>>,
}

impl<T: Clone + Send + Sync + 'static> Source<T> {
    /// Create a source pre-loaded with values from an iterator.
    #[allow(clippy::should_implement_trait)]
    pub fn from_iter(iter: impl Iterator<Item = T>) -> Self {
        let buffer: std::collections::VecDeque<T> = iter.collect();
        Source {
            inner: Arc::new(Mutex::new(SourceInner { buffer })),
        }
    }

    /// Create an empty source (values added via `push_value`).
    pub fn empty() -> Self {
        Source {
            inner: Arc::new(Mutex::new(SourceInner {
                buffer: std::collections::VecDeque::new(),
            })),
        }
    }

    /// Manually push a value into the source buffer.
    pub fn push_value(&self, value: T) {
        if let Ok(mut g) = self.inner.lock() {
            g.buffer.push_back(value);
        }
    }

    /// Number of buffered values.
    pub fn len(&self) -> usize {
        self.inner.lock().map(|g| g.buffer.len()).unwrap_or(0)
    }

    /// `true` if the source buffer is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<T: Clone + Send + Sync + 'static> DataflowNode<T> for Source<T> {
    fn push(&self, value: T) {
        if let Ok(mut g) = self.inner.lock() {
            g.buffer.push_back(value);
        }
    }

    fn pull(&self) -> Option<T> {
        self.inner.lock().ok()?.buffer.pop_front()
    }
}

// ---------------------------------------------------------------------------
// Sink<T>
// ---------------------------------------------------------------------------

struct SinkInner<T> {
    collected: Vec<T>,
    callback: Option<Box<dyn Fn(T) + Send + Sync + 'static>>,
}

/// A sink node that consumes values and optionally applies a callback.
pub struct Sink<T> {
    inner: Arc<Mutex<SinkInner<T>>>,
}

impl<T: Clone + Send + Sync + 'static> Sink<T> {
    /// Create a collecting sink (values are stored in an internal `Vec`).
    pub fn new() -> Self {
        Sink {
            inner: Arc::new(Mutex::new(SinkInner {
                collected: Vec::new(),
                callback: None,
            })),
        }
    }

    /// Create a sink that applies `f` to every received value.
    pub fn for_each(f: impl Fn(T) + Send + Sync + 'static) -> Self {
        Sink {
            inner: Arc::new(Mutex::new(SinkInner {
                collected: Vec::new(),
                callback: Some(Box::new(f)),
            })),
        }
    }

    /// Return the collected values, leaving the internal buffer empty.
    pub fn drain(&self) -> Vec<T> {
        self.inner
            .lock()
            .map(|mut g| std::mem::take(&mut g.collected))
            .unwrap_or_default()
    }

    /// Return a clone of collected values without draining.
    pub fn collect(&self) -> Vec<T>
    where
        T: Clone,
    {
        self.inner
            .lock()
            .map(|g| g.collected.clone())
            .unwrap_or_default()
    }
}

impl<T: Clone + Send + Sync + 'static> DataflowNode<T> for Sink<T> {
    fn push(&self, value: T) {
        if let Ok(mut g) = self.inner.lock() {
            if let Some(cb) = &g.callback {
                cb(value);
            } else {
                g.collected.push(value);
            }
        }
    }

    fn pull(&self) -> Option<T> {
        // Sinks do not produce values.
        None
    }
}

// ---------------------------------------------------------------------------
// Map<T, U>
// ---------------------------------------------------------------------------

/// A transformation node that applies a function `T -> U`.
pub struct Map<T, U> {
    func: Arc<dyn Fn(T) -> U + Send + Sync + 'static>,
    output: Arc<Mutex<std::collections::VecDeque<U>>>,
}

impl<T: Send + Sync + 'static, U: Send + Sync + 'static> Map<T, U> {
    /// Create a `Map` node with the given transformation function.
    pub fn new(f: impl Fn(T) -> U + Send + Sync + 'static) -> Self {
        Map {
            func: Arc::new(f),
            output: Arc::new(Mutex::new(std::collections::VecDeque::new())),
        }
    }
}

impl<T: Send + Sync + 'static, U: Send + Sync + 'static> DataflowNode<T> for Map<T, U> {
    fn push(&self, value: T) {
        let out = (self.func)(value);
        if let Ok(mut q) = self.output.lock() {
            q.push_back(out);
        }
    }

    fn pull(&self) -> Option<T> {
        // Map produces U, not T; this method is not meaningful here.
        // It is only called on Map<T,T> or via the graph which uses
        // the type-erased output queue directly.
        None
    }
}

impl<T: Send + Sync + 'static, U: Send + Sync + 'static> Map<T, U> {
    /// Pull from the output queue (produces `U`).
    pub fn pull_out(&self) -> Option<U> {
        self.output.lock().ok()?.pop_front()
    }
}

// ---------------------------------------------------------------------------
// Filter<T>
// ---------------------------------------------------------------------------

/// A filter node that forwards values satisfying a predicate.
pub struct Filter<T> {
    pred: Arc<dyn Fn(&T) -> bool + Send + Sync + 'static>,
    output: Arc<Mutex<std::collections::VecDeque<T>>>,
}

impl<T: Send + Sync + 'static> Filter<T> {
    /// Create a `Filter` node with the given predicate.
    pub fn new(pred: impl Fn(&T) -> bool + Send + Sync + 'static) -> Self {
        Filter {
            pred: Arc::new(pred),
            output: Arc::new(Mutex::new(std::collections::VecDeque::new())),
        }
    }
}

impl<T: Send + Sync + 'static> DataflowNode<T> for Filter<T> {
    fn push(&self, value: T) {
        if (self.pred)(&value) {
            if let Ok(mut q) = self.output.lock() {
                q.push_back(value);
            }
        }
    }

    fn pull(&self) -> Option<T> {
        self.output.lock().ok()?.pop_front()
    }
}

// ---------------------------------------------------------------------------
// Zip<T, U>
// ---------------------------------------------------------------------------

/// A zip node that combines values from two input queues into pairs.
///
/// A pair `(T, U)` is emitted only when both queues have at least one element.
pub struct Zip<T, U> {
    left: Arc<Mutex<std::collections::VecDeque<T>>>,
    right: Arc<Mutex<std::collections::VecDeque<U>>>,
    output: Arc<Mutex<std::collections::VecDeque<(T, U)>>>,
}

impl<T: Send + Sync + 'static, U: Send + Sync + 'static> Zip<T, U> {
    /// Create a new `Zip` node.
    pub fn new() -> Self {
        Zip {
            left: Arc::new(Mutex::new(std::collections::VecDeque::new())),
            right: Arc::new(Mutex::new(std::collections::VecDeque::new())),
            output: Arc::new(Mutex::new(std::collections::VecDeque::new())),
        }
    }

    /// Push a value for the **left** stream.
    pub fn push_left(&self, value: T) {
        if let Ok(mut l) = self.left.lock() {
            l.push_back(value);
        }
        self.try_pair();
    }

    /// Push a value for the **right** stream.
    pub fn push_right(&self, value: U) {
        if let Ok(mut r) = self.right.lock() {
            r.push_back(value);
        }
        self.try_pair();
    }

    fn try_pair(&self) {
        loop {
            let pair = {
                let mut l = match self.left.lock() {
                    Ok(g) => g,
                    Err(_) => break,
                };
                let mut r = match self.right.lock() {
                    Ok(g) => g,
                    Err(_) => break,
                };
                match (l.pop_front(), r.pop_front()) {
                    (Some(lv), Some(rv)) => (lv, rv),
                    (Some(lv), None) => {
                        l.push_front(lv);
                        break;
                    }
                    (None, Some(rv)) => {
                        r.push_front(rv);
                        break;
                    }
                    (None, None) => break,
                }
            };
            if let Ok(mut out) = self.output.lock() {
                out.push_back(pair);
            }
        }
    }

    /// Pull the next `(T, U)` pair.
    pub fn pull_pair(&self) -> Option<(T, U)> {
        self.output.lock().ok()?.pop_front()
    }
}

// ---------------------------------------------------------------------------
// Buffer<T>
// ---------------------------------------------------------------------------

/// A buffering node that accumulates `batch_size` items before releasing them
/// as a batch (`Vec<T>`).
pub struct Buffer<T> {
    batch_size: usize,
    input: Arc<Mutex<std::collections::VecDeque<T>>>,
    output: Arc<Mutex<std::collections::VecDeque<Vec<T>>>>,
}

impl<T: Send + Sync + 'static> Buffer<T> {
    /// Create a `Buffer` that emits batches of `batch_size` items.
    pub fn new(batch_size: usize) -> Self {
        Buffer {
            batch_size: batch_size.max(1),
            input: Arc::new(Mutex::new(std::collections::VecDeque::new())),
            output: Arc::new(Mutex::new(std::collections::VecDeque::new())),
        }
    }

    fn flush_if_ready(&self) {
        loop {
            let batch: Option<Vec<T>> = {
                let mut inp = match self.input.lock() {
                    Ok(g) => g,
                    Err(_) => break,
                };
                if inp.len() >= self.batch_size {
                    Some(inp.drain(..self.batch_size).collect())
                } else {
                    None
                }
            };
            match batch {
                Some(b) => {
                    if let Ok(mut out) = self.output.lock() {
                        out.push_back(b);
                    }
                }
                None => break,
            }
        }
    }

    /// Pull the next complete batch.
    pub fn pull_batch(&self) -> Option<Vec<T>> {
        self.output.lock().ok()?.pop_front()
    }

    /// Number of complete batches available.
    pub fn batch_count(&self) -> usize {
        self.output.lock().map(|g| g.len()).unwrap_or(0)
    }
}

impl<T: Send + Sync + 'static> DataflowNode<T> for Buffer<T> {
    fn push(&self, value: T) {
        if let Ok(mut inp) = self.input.lock() {
            inp.push_back(value);
        }
        self.flush_if_ready();
    }

    fn pull(&self) -> Option<T> {
        // Buffer exposes batches, not individual items.
        None
    }
}

// ---------------------------------------------------------------------------
// DataflowGraph
// ---------------------------------------------------------------------------

/// Type-erased node wrapper stored inside the graph.
enum AnyNode {
    SourceI32(Arc<Source<i32>>),
    SinkI32(Arc<Sink<i32>>),
    MapI32(Arc<Map<i32, i32>>),
    FilterI32(Arc<Filter<i32>>),
    BufferI32(Arc<Buffer<i32>>),
    SourceF64(Arc<Source<f64>>),
    SinkF64(Arc<Sink<f64>>),
}

/// A typed node descriptor for building the graph with [`DataflowGraph`].
///
/// The graph stores nodes as typed variants internally; connections between
/// nodes of compatible types are resolved at `run()` time.
#[allow(missing_debug_implementations)]
pub struct DataflowGraph {
    nodes: Vec<AnyNode>,
    edges: Vec<(NodeId, NodeId)>,
}

impl DataflowGraph {
    /// Create a new, empty graph.
    pub fn new() -> Self {
        DataflowGraph {
            nodes: Vec::new(),
            edges: Vec::new(),
        }
    }

    // --- i32 nodes ---------------------------------------------------------

    /// Add an `i32` source node and return its [`NodeId`].
    pub fn add_source(&mut self, src: Source<i32>) -> NodeId {
        let id = NodeId(self.nodes.len());
        self.nodes.push(AnyNode::SourceI32(Arc::new(src)));
        id
    }

    /// Add an `i32 → i32` map node and return its [`NodeId`].
    pub fn add_map(&mut self, map: Map<i32, i32>) -> NodeId {
        let id = NodeId(self.nodes.len());
        self.nodes.push(AnyNode::MapI32(Arc::new(map)));
        id
    }

    /// Add an `i32` filter node and return its [`NodeId`].
    pub fn add_filter(&mut self, filter: Filter<i32>) -> NodeId {
        let id = NodeId(self.nodes.len());
        self.nodes.push(AnyNode::FilterI32(Arc::new(filter)));
        id
    }

    /// Add an `i32` sink node and return its [`NodeId`].
    pub fn add_sink(&mut self, sink: Sink<i32>) -> NodeId {
        let id = NodeId(self.nodes.len());
        self.nodes.push(AnyNode::SinkI32(Arc::new(sink)));
        id
    }

    /// Add an `i32` buffer node and return its [`NodeId`].
    pub fn add_buffer(&mut self, buf: Buffer<i32>) -> NodeId {
        let id = NodeId(self.nodes.len());
        self.nodes.push(AnyNode::BufferI32(Arc::new(buf)));
        id
    }

    // --- f64 nodes ---------------------------------------------------------

    /// Add an `f64` source node and return its [`NodeId`].
    pub fn add_source_f64(&mut self, src: Source<f64>) -> NodeId {
        let id = NodeId(self.nodes.len());
        self.nodes.push(AnyNode::SourceF64(Arc::new(src)));
        id
    }

    /// Add an `f64` sink node and return its [`NodeId`].
    pub fn add_sink_f64(&mut self, sink: Sink<f64>) -> NodeId {
        let id = NodeId(self.nodes.len());
        self.nodes.push(AnyNode::SinkF64(Arc::new(sink)));
        id
    }

    // --- edges -------------------------------------------------------------

    /// Connect the output of `src` to the input of `dst`.
    pub fn connect(&mut self, src: NodeId, dst: NodeId) {
        self.edges.push((src, dst));
    }

    // --- execution ---------------------------------------------------------

    /// Drive all source nodes and push values through the graph until all
    /// sources are empty.
    pub fn run(&self) {
        // Build an adjacency list: for each node, which nodes receive its output?
        let mut adjacency: Vec<Vec<usize>> = vec![Vec::new(); self.nodes.len()];
        for &(NodeId(src), NodeId(dst)) in &self.edges {
            if src < adjacency.len() {
                adjacency[src].push(dst);
            }
        }

        // Pull from every source and propagate.
        let mut changed = true;
        while changed {
            changed = false;
            for (src_idx, node) in self.nodes.iter().enumerate() {
                match node {
                    AnyNode::SourceI32(src) => {
                        while let Some(v) = src.pull() {
                            changed = true;
                            self.propagate_i32(v, &adjacency[src_idx]);
                        }
                    }
                    AnyNode::MapI32(map) => {
                        while let Some(v) = map.pull_out() {
                            changed = true;
                            self.propagate_i32(v, &adjacency[src_idx]);
                        }
                    }
                    AnyNode::FilterI32(flt) => {
                        while let Some(v) = flt.pull() {
                            changed = true;
                            self.propagate_i32(v, &adjacency[src_idx]);
                        }
                    }
                    AnyNode::SourceF64(src) => {
                        while let Some(v) = src.pull() {
                            changed = true;
                            self.propagate_f64(v, &adjacency[src_idx]);
                        }
                    }
                    _ => {}
                }
            }
        }
    }

    fn propagate_i32(&self, value: i32, dst_indices: &[usize]) {
        for &dst in dst_indices {
            match self.nodes.get(dst) {
                Some(AnyNode::MapI32(map)) => map.push(value),
                Some(AnyNode::FilterI32(flt)) => flt.push(value),
                Some(AnyNode::SinkI32(sink)) => sink.push(value),
                Some(AnyNode::BufferI32(buf)) => buf.push(value),
                _ => {}
            }
        }
    }

    fn propagate_f64(&self, value: f64, dst_indices: &[usize]) {
        for &dst in dst_indices {
            if let Some(AnyNode::SinkF64(sink)) = self.nodes.get(dst) {
                sink.push(value)
            }
        }
    }

    /// Collect and drain all values accumulated in the `i32` sink at `id`.
    pub fn collect_sink(&self, id: NodeId) -> Vec<i32> {
        match self.nodes.get(id.0) {
            Some(AnyNode::SinkI32(sink)) => sink.drain(),
            _ => Vec::new(),
        }
    }

    /// Collect and drain all values accumulated in the `f64` sink at `id`.
    pub fn collect_sink_f64(&self, id: NodeId) -> Vec<f64> {
        match self.nodes.get(id.0) {
            Some(AnyNode::SinkF64(sink)) => sink.drain(),
            _ => Vec::new(),
        }
    }

    /// Return available batches from a `Buffer` node at `id`.
    pub fn collect_buffer(&self, id: NodeId) -> Vec<Vec<i32>> {
        match self.nodes.get(id.0) {
            Some(AnyNode::BufferI32(buf)) => {
                let mut batches = Vec::new();
                while let Some(b) = buf.pull_batch() {
                    batches.push(b);
                }
                batches
            }
            _ => Vec::new(),
        }
    }
}

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

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

    #[test]
    fn test_dataflow_map() {
        let mut graph = DataflowGraph::new();
        let src = Source::from_iter(0..5i32);
        let map = Map::new(|x: i32| x * 3);
        let sink: Sink<i32> = Sink::new();

        let src_id = graph.add_source(src);
        let map_id = graph.add_map(map);
        let snk_id = graph.add_sink(sink);

        graph.connect(src_id, map_id);
        graph.connect(map_id, snk_id);
        graph.run();

        let res = graph.collect_sink(snk_id);
        assert_eq!(res, vec![0, 3, 6, 9, 12]);
    }

    #[test]
    fn test_dataflow_filter() {
        let mut graph = DataflowGraph::new();
        let src = Source::from_iter(0..10i32);
        let flt = Filter::new(|x: &i32| x % 2 == 0);
        let sink: Sink<i32> = Sink::new();

        let src_id = graph.add_source(src);
        let flt_id = graph.add_filter(flt);
        let snk_id = graph.add_sink(sink);

        graph.connect(src_id, flt_id);
        graph.connect(flt_id, snk_id);
        graph.run();

        let res = graph.collect_sink(snk_id);
        assert_eq!(res, vec![0, 2, 4, 6, 8]);
    }

    #[test]
    fn test_dataflow_source_sink() {
        let mut graph = DataflowGraph::new();
        let src = Source::from_iter(1..=5i32);
        let sink: Sink<i32> = Sink::new();

        let src_id = graph.add_source(src);
        let snk_id = graph.add_sink(sink);

        graph.connect(src_id, snk_id);
        graph.run();

        let res = graph.collect_sink(snk_id);
        assert_eq!(res, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_dataflow_buffer() {
        let mut graph = DataflowGraph::new();
        let src = Source::from_iter(0..9i32);
        let buf = Buffer::new(3);
        let src_id = graph.add_source(src);
        let snk_buf_id = graph.add_buffer(buf);

        graph.connect(src_id, snk_buf_id);
        graph.run();

        let batches = graph.collect_buffer(snk_buf_id);
        assert_eq!(batches.len(), 3);
        assert_eq!(batches[0], vec![0, 1, 2]);
        assert_eq!(batches[1], vec![3, 4, 5]);
        assert_eq!(batches[2], vec![6, 7, 8]);
    }

    #[test]
    fn test_dataflow_zip() {
        let zip: Zip<i32, i32> = Zip::new();
        zip.push_left(1);
        zip.push_left(2);
        zip.push_right(10);
        zip.push_right(20);
        zip.push_left(3);
        zip.push_right(30);

        let mut pairs = Vec::new();
        while let Some(p) = zip.pull_pair() {
            pairs.push(p);
        }
        assert_eq!(pairs, vec![(1, 10), (2, 20), (3, 30)]);
    }

    #[test]
    fn test_source_manual_push() {
        let src: Source<i32> = Source::empty();
        src.push_value(5);
        src.push_value(6);
        assert_eq!(src.pull(), Some(5));
        assert_eq!(src.pull(), Some(6));
        assert_eq!(src.pull(), None);
    }

    #[test]
    fn test_sink_collect() {
        let sink: Sink<i32> = Sink::new();
        sink.push(1);
        sink.push(2);
        sink.push(3);
        assert_eq!(sink.collect(), vec![1, 2, 3]);
    }

    #[test]
    fn test_dataflow_map_filter_pipeline() {
        let mut graph = DataflowGraph::new();
        let src = Source::from_iter(0..10i32);
        let map = Map::new(|x: i32| x * 2);
        let filter = Filter::new(|x: &i32| *x > 8);
        let sink: Sink<i32> = Sink::new();

        let src_id = graph.add_source(src);
        let map_id = graph.add_map(map);
        let flt_id = graph.add_filter(filter);
        let snk_id = graph.add_sink(sink);

        graph.connect(src_id, map_id);
        graph.connect(map_id, flt_id);
        graph.connect(flt_id, snk_id);
        graph.run();

        let res = graph.collect_sink(snk_id);
        assert_eq!(res, vec![10, 12, 14, 16, 18]);
    }
}