async_ach_ring/
lib.rs

1#![no_std]
2
3use ach_ring as ach;
4use ach_util::Error;
5use async_ach_notify::Notify;
6use futures_util::StreamExt;
7
8pub struct Ring<T, const N: usize, const MP: usize, const MC: usize> {
9    buf: ach::Ring<T, N>,
10    consumer: Notify<MP>,
11    producer: Notify<MC>,
12}
13impl<T, const N: usize, const MP: usize, const MC: usize> Ring<T, N, MP, MC> {
14    pub const fn new() -> Self {
15        Self {
16            buf: ach::Ring::new(),
17            consumer: Notify::new(),
18            producer: Notify::new(),
19        }
20    }
21    pub fn len(&self) -> usize {
22        self.buf.len()
23    }
24}
25impl<T: Unpin, const N: usize, const MP: usize, const MC: usize> Ring<T, N, MP, MC> {
26    /// Appends an element to the back of the Ring.
27    ///
28    /// Returns Err if the Ring is full or in critical section.
29    pub fn try_push(&self, val: T) -> Result<(), Error<T>> {
30        self.buf.push(val).map(|x| {
31            self.producer.notify_one();
32            x
33        })
34    }
35    /// Appends an element to the back of the Ring.
36    pub async fn push(&self, mut val: T) {
37        let mut wait_c = self.consumer.listen();
38        loop {
39            if let Err(err) = self.try_push(val) {
40                val = err.input;
41                wait_c.next().await;
42            } else {
43                break;
44            }
45        }
46    }
47
48    /// Removes the first element and returns it.
49    ///
50    /// Returns Err if the Ring is empty or in critical section.
51    pub fn try_pop(&self) -> Result<T, Error<()>> {
52        self.buf.pop().map(|x| {
53            self.consumer.notify_one();
54            x
55        })
56    }
57    /// Removes the first element and returns it.
58    pub async fn pop(&self) -> T {
59        let mut wait_p = self.producer.listen();
60        loop {
61            if let Ok(v) = self.try_pop() {
62                break v;
63            } else {
64                wait_p.next().await;
65            }
66        }
67    }
68}