use crate::combine::Combine;
pub const DEFAULT_DRAIN_CAP: usize = 32;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Storm {
pub cap: u16,
pub drained: u16,
}
impl core::fmt::Display for Storm {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"internal event storm: drained {} with cap {} (chart bug; Runtime::try_apply to Halt instead of die)",
self.drained, self.cap
)
}
}
pub fn unwrap_storm<T>(result: Result<T, Storm>) -> T {
result.unwrap_or_else(|s| panic!("{s}"))
}
#[cfg(feature = "std")]
impl std::error::Error for Storm {}
#[derive(Clone, Debug)]
pub struct Inbox<M, const N: usize = DEFAULT_DRAIN_CAP> {
slots: [Option<M>; N],
start: usize,
len: usize,
overflowed: bool,
}
impl<M, const N: usize> Inbox<M, N> {
pub fn new() -> Self {
Self {
slots: core::array::from_fn(|_| None),
start: 0,
len: 0,
overflowed: false,
}
}
pub fn push(&mut self, msg: M) {
if self.len >= N {
self.overflowed = true;
return;
}
let i = (self.start + self.len) % N;
self.slots[i] = Some(msg);
self.len += 1;
}
pub fn pop(&mut self) -> Option<M> {
if self.len == 0 {
return None;
}
let msg = self.slots[self.start].take();
self.start = (self.start + 1) % N;
self.len -= 1;
msg
}
#[inline]
pub const fn overflowed(&self) -> bool {
self.overflowed
}
#[inline]
pub const fn len(&self) -> usize {
self.len
}
#[inline]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
}
impl<M, const N: usize> Default for Inbox<M, N> {
fn default() -> Self {
Self::new()
}
}
pub fn rtc<M, C, F>(first: M, body: F) -> Result<C, Storm>
where
C: Combine,
F: FnMut(M, &mut Inbox<M>) -> C,
{
rtc_n::<M, C, F, DEFAULT_DRAIN_CAP>(first, body)
}
pub fn rtc_n<M, C, F, const N: usize>(first: M, mut body: F) -> Result<C, Storm>
where
C: Combine,
F: FnMut(M, &mut Inbox<M, N>) -> C,
{
let mut inbox = Inbox::<M, N>::new();
inbox.push(first);
let mut cmd = C::none();
let mut drained: u16 = 0;
let cap = N as u16;
while let Some(msg) = inbox.pop() {
if drained >= cap {
return Err(Storm { cap, drained });
}
drained = drained.saturating_add(1);
cmd = cmd.combine(body(msg, &mut inbox));
if inbox.overflowed() {
return Err(Storm { cap, drained });
}
}
Ok(cmd)
}
#[cfg(test)]
mod tests {
use super::{rtc, rtc_n, Inbox, Storm};
use crate::cmd::Cmd;
#[test]
fn single_message() {
let cmd = rtc::<_, Cmd<u8>, _>(1, |m, _| Cmd::single(m)).unwrap();
assert_eq!(cmd, Cmd::single(1));
}
#[cfg(feature = "alloc")]
#[test]
fn follow_up_drained() {
let cmd = rtc::<_, Cmd<u8>, _>(1, |m, inbox| {
if m == 1 {
inbox.push(2);
}
Cmd::single(m)
})
.unwrap();
assert_eq!(cmd, Cmd::single(1).and(Cmd::single(2)));
}
#[test]
fn storm_on_loop() {
let err = rtc_n::<_, (), _, 4>(0, |m, inbox| {
inbox.push(m + 1);
})
.unwrap_err();
assert_eq!(err, Storm { cap: 4, drained: 4 });
}
#[test]
fn inbox_fifo() {
let mut inbox = Inbox::<u8, 4>::new();
inbox.push(1);
inbox.push(2);
assert_eq!(inbox.pop(), Some(1));
assert_eq!(inbox.pop(), Some(2));
assert!(inbox.is_empty());
}
}