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
use crate::ring_buffer::RingBuffer;
use async_channel::RecvError;
use futures::task::{Context, Poll};
use futures::Sink;
use std::pin::Pin;
use std::sync::Arc;

#[derive(Debug, Clone)]
pub struct AsyncPublishError;

impl std::fmt::Display for AsyncPublishError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "publisher encountered error it could not recover from")
    }
}

/// A handle to asynchronously publish to the event-bus
///
/// Implements the [`Sink`] trait to asynchronously publish a stream of events to the event-bus.
///
/// # Example
///
/// Basic usage:
///
/// ```ignore
/// let eventbus = Eventador::new(4)?;
/// let mut publisher: AsyncPublisher<usize> = eventbus.async_publisher();
///
/// let mut i: usize = 1234;
/// publisher.send(i).await?;
/// ```
///
pub struct AsyncPublisher<T> {
    ring: Arc<RingBuffer>,
    sequence: Option<u64>,
    event: Option<T>,
}

impl<T: 'static + Unpin> AsyncPublisher<T> {
    pub(crate) fn new(ring: Arc<RingBuffer>) -> Self {
        Self {
            ring,
            sequence: None,
            event: None,
        }
    }

    pub(crate) fn write_to_ring(&mut self) {
        if let Some(sequence) = self.sequence.take() {
            if let Some(envelope) = self.ring.get_envelope(sequence) {
                if let Some(event) = self.event.take() {
                    envelope.overwrite(sequence, event);
                }
            }
        }
    }
}

impl<T: 'static + Unpin> Sink<T> for AsyncPublisher<T> {
    type Error = RecvError;

    fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        if self.event.is_some() {
            Poll::Pending
        } else {
            Poll::Ready(Ok(()))
        }
    }

    fn start_send(mut self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
        let sequence = self.ring.next();

        self.sequence.replace(sequence);
        self.event.replace(item);

        Ok(())
    }

    fn poll_flush(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
    ) -> Poll<Result<(), Self::Error>> {
        self.write_to_ring();
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        drop(self);
        Poll::Ready(Ok(()))
    }
}

#[cfg(test)]
mod tests {
    // use crate::async_publisher::*;
}