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
use futures::{pin_mut, select, FutureExt};
use melodium_core::common::executive::{GetData, Value};
use melodium_macro::{check, mel_treatment};
use std::collections::VecDeque;

pub mod vec;

/// Chain two streams.
///
///
/// ```mermaid
/// graph LR
///     T("chain()")
///     A["🟨 🟨 🟨 🟨 🟨 🟨"] -->|first| T
///     B["… 🟪 🟪 🟪"] -->|second| T
///     
///     T -->|chained| O["… 🟪 🟪 🟪 🟨 🟨 🟨 🟨 🟨 🟨"]
///
///     style A fill:#ffff,stroke:#ffff
///     style B fill:#ffff,stroke:#ffff
///     style O fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input first Stream<T>
    input second Stream<T>
    output chained Stream<T>
)]
pub async fn chain() {
    while let Ok(values) = first.recv_many().await {
        check!(chained.send_many(values).await)
    }

    while let Ok(values) = second.recv_many().await {
        check!(chained.send_many(values).await)
    }
}

/// Trigger on a stream start and end.
///
/// Emit `start` when a first value is send through the stream.
/// Emit `end` when stream is finally over.
///
/// Emit `first` with the first value coming in the stream.
/// Emit `last` with the last value coming in the stream.
///
/// ℹ️ `start` and `first` are always emitted together.
/// If the stream only contains one element, `first` and `last` both contains it.
/// If the stream never transmit any data before being ended, only `end` is emitted.
///
/// ```mermaid
/// graph LR
///     T("trigger()")
///     B["🟥 … 🟨 🟨 🟨 🟨 🟨 🟨 … 🟩"] -->|stream| T
///     
///     T -->|start| S["〈🟦〉"]
///     T -->|first| F["〈🟩〉"]
///     T -->|last| L["〈🟥〉"]
///     T -->|end| E["〈🟦〉"]
///
///     style B fill:#ffff,stroke:#ffff
///     style S fill:#ffff,stroke:#ffff
///     style F fill:#ffff,stroke:#ffff
///     style L fill:#ffff,stroke:#ffff
///     style E fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input stream Stream<T>
    output start Block<void>
    output end Block<void>
    output first Block<T>
    output last Block<T>
)]
pub async fn trigger() {
    let mut last_value = None;

    if let Ok(mut values) = stream.recv_many().await {
        let _ = start.send_one(().into()).await;
        if let Some(val) = values.pop_front() {
            let _ = first.send_one(val).await;
        }
        last_value = Into::<VecDeque<Value>>::into(values).pop_back();
        let _ = futures::join!(start.close(), first.close());
    }

    while let Ok(values) = stream.recv_many().await {
        last_value = Into::<VecDeque<Value>>::into(values).pop_back();
    }

    let _ = end.send_one(().into()).await;
    if let Some(val) = last_value {
        let _ = last.send_one(val).await;
    }

    // We don't close `end` and `last` explicitly here,
    // because it would be redundant with boilerplate
    // implementation of treatments.
}

/// Check a blocking value.
///
/// When `value` block is received, `check` is emitted.
///
/// ```mermaid
/// graph LR
///     T("check()")
///     B["〈🟨〉"] -->|value| T
///         
///     T -->|check| S["〈🟦〉"]
///     
///     style B fill:#ffff,stroke:#ffff
///     style S fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input value Block<T>
    output check Block<void>
)]
pub async fn check() {
    if let Ok(_) = value.recv_one().await {
        let _ = check.send_one(().into()).await;
    }
}

/// Emit a blocking value.
///
/// When `trigger` is enabled, `value` is emitted as block.
///
/// ```mermaid
/// graph LR
///     T("emit(value=🟨)")
///     B["〈🟦〉"] -->|trigger| T
///         
///     T -->|emit| S["〈🟨〉"]
///     
///     style B fill:#ffff,stroke:#ffff
///     style S fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input trigger Block<void>
    output emit Block<T>
)]
pub async fn emit(value: T) {
    if let Ok(_) = trigger.recv_one().await {
        let _ = emit.send_one(value).await;
    }
}

/// Stream a blocking value.
///
/// ```mermaid
/// graph LR
///     T("stream()")
///     B["〈🟦〉"] -->|block| T
///         
///     T -->|stream| S["🟦"]
///     
///     
///     style B fill:#ffff,stroke:#ffff
///     style S fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input block Block<T>
    output stream Stream<T>
)]
pub async fn stream() {
    if let Ok(val) = block.recv_one().await {
        let _ = stream.send_one(val).await;
    }
}

/// Merge two streams.
///
/// The two streams are merged without predictible order.
///
/// ℹ️ Merge continues as long as `a` or `b` continues too, while the other can be ended.
///
/// ```mermaid
/// graph LR
///     T("merge()")
///     A["… 🟦 🟫 …"] -->|a| T
///     B["… 🟧 🟪 🟨 …"] -->|b| T
///     
///
///     T -->|value| V["… 🟦 🟧 🟪 🟫 🟨 …"]
///
///     style V fill:#ffff,stroke:#ffff
///     style A fill:#ffff,stroke:#ffff
///     style B fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input a Stream<T>
    input b Stream<T>
    output value Stream<T>
)]
pub async fn merge() {
    let xa = async {
        while let Ok(a) = (&a).recv_many().await {
            check!(value.send_many(a).await);
        }
    }
    .fuse();
    let xb = async {
        while let Ok(b) = (&b).recv_many().await {
            check!(value.send_many(b).await);
        }
    }
    .fuse();

    pin_mut!(xa, xb);

    loop {
        select! {
            () = xa => {},
            () = xb => {},
            complete => break,
        };
    }
}

/// Arrange two streams as one.
///
/// The two streams are merged using the `select` stream:
/// - when `true`, value from `a` is used;
/// - when `false`, value from `b` is used.
///
/// ℹ️ No value from either `a` or `b` are discarded, they are used when `select` give turn.
///
/// ⚠️ When `select` ends merge terminates without treating the remaining values from `a` and `b`.
/// When `select` give turn to `a` or `b` while the concerned stream is ended, the merge terminates.
/// Merge continues as long as `select` and concerned stream does, while the other can be ended.
///
/// ```mermaid
/// graph LR
///     T("arrange()")
///     A["… 🟦 🟫 …"] -->|a| T
///     B["… 🟧 🟪 🟨 …"] -->|b| T
///     O["… 🟩 🟥 🟥 🟩 🟥 …"] -->|select|T
///     
///
///     T -->|value| V["… 🟦 🟧 🟪 🟫 🟨 …"]
///
///     style V fill:#ffff,stroke:#ffff
///     style O fill:#ffff,stroke:#ffff
///     style A fill:#ffff,stroke:#ffff
///     style B fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input a Stream<T>
    input b Stream<T>
    input select Stream<bool>
    output value Stream<T>
)]
pub async fn arrange() {
    while let Ok(select) = select
        .recv_one()
        .await
        .map(|val| GetData::<bool>::try_data(val).unwrap())
    {
        let val;
        if select {
            if let Ok(v) = a.recv_one().await {
                val = v;
            } else {
                break;
            }
        } else {
            if let Ok(v) = b.recv_one().await {
                val = v;
            } else {
                break;
            }
        }

        check!(value.send_one(val).await)
    }
}

/// Fill a pattern stream with a `value.
///
/// ```mermaid
/// graph LR
/// T("fill(value=🟧)")
/// B["… 🟦 🟦 🟦 …"] -->|pattern| T
///
/// T -->|filled| O["… 🟧 🟧 🟧 …"]
///
/// style B fill:#ffff,stroke:#ffff
/// style O fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input pattern Stream<void>
    output filled Stream<T>
)]
pub async fn fill(value: T) {
    while let Ok(pat) = pattern.recv_many().await {
        let mut transmission = melodium_core::TransmissionValue::new(value.clone());
        for _ in 1..pat.len() {
            transmission.push(value.clone());
        }
        check!(filled.send_many(transmission).await)
    }
}

/// Filter a stream according to `bool` stream.
///
/// ℹ️ If both streams are not the same size nothing is sent through accepted nor rejected.
///  
/// ```mermaid
/// graph LR
///     T("filter()")
///     V["… 🟦 🟧 🟪 🟫 🟨 …"] -->|value| T
///     D["… 🟩 🟥 🟥 🟩 🟥 …"] -->|select|T
///     
///     T -->|accepted| A["… 🟦 🟫 …"]
///     T -->|rejected| R["… 🟧 🟪 🟨 …"]
///
///     style V fill:#ffff,stroke:#ffff
///     style D fill:#ffff,stroke:#ffff
///     style A fill:#ffff,stroke:#ffff
///     style R fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input value Stream<T>
    input select Stream<bool>
    output accepted Stream<T>
    output rejected Stream<T>
)]
pub async fn filter() {
    let mut accepted_op = true;
    let mut rejected_op = true;

    while let (Ok(value), Ok(select)) = futures::join!(value.recv_one(), select.recv_one()) {
        let select = GetData::<bool>::try_data(select).unwrap();
        if select {
            if let Err(_) = accepted.send_one(value).await {
                // If we cannot send anymore on accepted, we note it,
                // and check if rejected is still valid, else just terminate.
                accepted_op = false;
                if !rejected_op {
                    break;
                }
            }
        } else {
            if let Err(_) = rejected.send_one(value).await {
                // If we cannot send anymore on rejected, we note it,
                // and check if accepted is still valid, else just terminate.
                rejected_op = false;
                if !accepted_op {
                    break;
                }
            }
        }
    }
}

/// Fit a stream into a pattern.
///
/// ℹ️ If some remaining values doesn't fit into the pattern, they are trashed.
///
/// ```mermaid
/// graph LR
///     T("fit()")
///     A["… 🟨 🟨 🟨 🟨 🟨 🟨"] -->|value| T
///     B["🟦 🟦 🟦 🟦"] -->|pattern| T
///     
///     T -->|fitted| O["🟨 🟨 🟨 🟨"]
///
///     style A fill:#ffff,stroke:#ffff
///     style B fill:#ffff,stroke:#ffff
///     style O fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input value Stream<T>
    input pattern Stream<void>
    output fitted Stream<T>
)]
pub async fn fit() {
    'main: while let Ok(pattern) = pattern
        .recv_many()
        .await
        .map(|values| TryInto::<Vec<()>>::try_into(values).unwrap())
    {
        for _ in pattern {
            if let Ok(val) = value.recv_one().await {
                check!('main, fitted.send_one(val).await)
            } else {
                break 'main;
            }
        }
    }
}

/// Gives count of elements passing through stream.
///
/// This count increment one for each element within the stream, starting at 1.
///
/// ```mermaid
/// graph LR
///     T("count()")
///     V["🟦 🟦 🟦 …"] -->|iter| T
///     
///     T -->|count| P["1️⃣ 2️⃣ 3️⃣ …"]
///
///     style V fill:#ffff,stroke:#ffff
///     style P fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input stream Stream<T>
    output count Stream<u128>
)]
pub async fn count() {
    let mut i: u128 = 0;
    while let Ok(iter) = stream.recv_many().await {
        let next_i = i + iter.len() as u128;
        check!(
            count
                .send_many((i..next_i).collect::<VecDeque<_>>().into())
                .await
        );
        i = next_i;
    }
}

/// Generate a stream with a given length.
///
/// ```mermaid
/// graph LR
///     T("generate()")
///     B["〈🟨〉"] -->|length| T
///         
///     T -->|stream| S["… 🟦 🟦 🟦 🟦 🟦 🟦"]
///     
///     
///     style B fill:#ffff,stroke:#ffff
///     style S fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input length Block<u128>
    output stream Stream<T>
)]
pub async fn generate(data: T) {
    if let Ok(length) = length
        .recv_one()
        .await
        .map(|val| GetData::<u128>::try_data(val).unwrap())
    {
        const CHUNK: u128 = 2u128.pow(20);
        let mut total = 0u128;
        while total < length {
            let chunk = u128::min(CHUNK, length - total) as usize;
            let mut transmission = melodium_core::TransmissionValue::new(data.clone());
            for _ in 1..chunk {
                transmission.push(data.clone());
            }
            check!(stream.send_many(transmission).await);
            total += chunk as u128;
        }
    }
}

/// Generate a stream indefinitely.
///
/// This generates a continuous stream, until stream consumers closes it.
///
/// ```mermaid
/// graph LR
///     T("generateIndefinitely()")
///     B["〈🟦〉"] -->|trigger| T
///         
///     T -->|stream| S["… 🟦 🟦 🟦 🟦 🟦 🟦"]
///     
///     
///     style B fill:#ffff,stroke:#ffff
///     style S fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input trigger Block<void>
    output stream Stream<T>
)]
pub async fn generate_indefinitely(data: T) {
    if let Ok(_) = trigger.recv_one().await {
        const CHUNK: usize = 2usize.pow(20);
        loop {
            let mut transmission = melodium_core::TransmissionValue::new(data.clone());
            for _ in 1..CHUNK {
                transmission.push(data.clone());
            }
            check!(stream.send_many(transmission).await);
        }
    }
}

/// Insert a block into a stream.
///
/// `block` is inserted into `stream` when it comes and everything is streamed to `output`.
///
/// ℹ️ No assumption on block insertion position in stream can be made.
///
/// ```mermaid
/// graph LR
///     T("insert()")
///     A["… 🟦 🟦 🟦 🟦 …"] -->|stream| T
///     B["〈🟧〉"] -->|block| T
///     
///
///     T -->|output| V["… 🟦 🟧 🟦 🟦 🟦 …"]
///
///     style V fill:#ffff,stroke:#ffff
///     style A fill:#ffff,stroke:#ffff
///     style B fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input stream Stream<T>
    input block Block<T>
    output output Stream<T>
)]
pub async fn insert() {
    let streaming = async {
        while let Ok(values) = (&stream).recv_many().await {
            check!(output.send_many(values).await);
        }
    }
    .fuse();
    let insert_block = async {
        if let Ok(val) = (&block).recv_one().await {
            let _ = output.send_one(val).await;
        }
    }
    .fuse();

    pin_mut!(streaming, insert_block);

    loop {
        select! {
            () = streaming => {},
            () = insert_block => {},
            complete => break,
        };
    }
}

/// Merge two incoming blocks as a stream.
///
/// Each block is taken when it arrives and send through `stream`.
///
/// ℹ️ No priority on blocks order in stream can be assumed.
///
/// ```mermaid
/// graph LR
///     T("flock()")
///     A["〈🟦〉"] -->|a| T
///     B["〈🟧〉"] -->|b| T
///     
///
///     T -->|stream| V["🟧 🟦"]
///
///     style V fill:#ffff,stroke:#ffff
///     style A fill:#ffff,stroke:#ffff
///     style B fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input a Block<T>
    input b Block<T>
    output stream Stream<T>
)]
pub async fn flock() {
    let xa = async {
        if let Ok(a) = (&a).recv_one().await {
            let _ = stream.send_one(a).await;
        }
    }
    .fuse();
    let xb = async {
        if let Ok(b) = (&b).recv_one().await {
            let _ = stream.send_one(b).await;
        }
    }
    .fuse();

    pin_mut!(xa, xb);

    loop {
        select! {
            () = xa => {},
            () = xb => {},
            complete => break,
        };
    }
}

/// Emit one block.
///
/// Take first block coming among `a` or `b` and emit it in `value`, ignoring the remaining one.
///
/// ℹ️ No priority between blocks can be assumed if they are ready at same moment.
///
/// ```mermaid
/// graph LR
///     T("one()")
///     A["…"] -->|a| T
///     B["〈🟧〉"] -->|b| T
///     
///
///     T -->|value| V["〈🟧〉"]
///
///     style V fill:#ffff,stroke:#ffff
///     style A fill:#ffff,stroke:#ffff
///     style B fill:#ffff,stroke:#ffff
/// ```
#[mel_treatment(
    generic T ()
    input a Block<T>
    input b Block<T>
    output value Block<T>
)]
pub async fn one() {
    let xa = async { (&a).recv_one().await.ok() }.fuse();
    let xb = async { (&b).recv_one().await.ok() }.fuse();

    pin_mut!(xa, xb);

    loop {
        let val = select! {
            val = xa => val,
            val = xb => val,
            complete => break,
        };

        if let Some(val) = val {
            let _ = value.send_one(val).await;
            break;
        }
    }
}