use melodium_core::*;
use melodium_macro::{check, mel_treatment};
#[mel_treatment(
input first Stream<void>
input second Stream<void>
output chained Stream<void>
)]
pub async fn chain() {
while let Ok(values) = first.recv_void().await {
check!(chained.send_void(values).await)
}
while let Ok(values) = second.recv_void().await {
check!(chained.send_void(values).await)
}
}
#[mel_treatment(
input stream Stream<void>
output start Block<void>
output end Block<void>
output first Block<void>
output last Block<void>
)]
pub async fn trigger() {
let mut last_value = None;
if let Ok(values) = stream.recv_void().await {
let _ = start.send_one_void(()).await;
if let Some(val) = values.first().cloned() {
let _ = first.send_one_void(val).await;
}
last_value = values.last().cloned();
let _ = futures::join!(start.close(), first.close());
}
while let Ok(values) = stream.recv_void().await {
last_value = values.last().cloned();
}
let _ = end.send_one_void(()).await;
if let Some(val) = last_value {
let _ = last.send_one_void(val).await;
}
}
#[mel_treatment(
input block Block<void>
output stream Stream<void>
)]
pub async fn stream() {
if let Ok(val) = block.recv_one_void().await {
let _ = stream.send_one_void(val).await;
}
}
#[mel_treatment(
input stream Stream<void>
output count Stream<u128>
)]
pub async fn count() {
let mut i: u128 = 0;
while let Ok(iter) = stream.recv_void().await {
let next_i = i + iter.len() as u128;
check!(count.send_u128((i..next_i).collect()).await);
i = next_i;
}
}
#[mel_treatment(
input length Block<u128>
output stream Stream<void>
)]
pub async fn generate() {
if let Ok(length) = length.recv_one_u128().await {
const CHUNK: u128 = 2u128.pow(20);
let mut total = 0u128;
while total < length {
let chunk = u128::min(CHUNK, length - total) as usize;
check!(stream.send_void(vec![(); chunk]).await);
total += chunk as u128;
}
}
}
#[mel_treatment(
input trigger Block<void>
output stream Stream<void>
)]
pub async fn generate_indefinitely() {
if let Ok(_) = trigger.recv_one_void().await {
const CHUNK: usize = 2usize.pow(20);
loop {
check!(stream.send_void(vec![(); CHUNK]).await);
}
}
}