simple_message_channels/
writer.rs

1use crate::Message;
2use futures::io::{AsyncWrite, AsyncWriteExt};
3use std::io::Error;
4
5/// A writer for SMC messages.
6///
7/// Consumes an [`futures::io::AsyncWrite`] to which messages will be written.
8pub struct Writer<W> {
9    writer: W,
10}
11
12impl<W> Writer<W>
13where
14    W: AsyncWrite + Unpin,
15{
16    /// Create a new message writer.
17    pub fn new(writer: W) -> Self {
18        Self { writer }
19    }
20
21    /// Send a message.
22    ///
23    /// This encodes the message, writes it and flushes the writer.
24    pub async fn send(&mut self, message: Message) -> Result<(), Error> {
25        send(&mut self.writer, message).await
26    }
27
28    /// Send a batch of messages.
29    ///
30    /// This works like [`Writer::send`] but flushes after all messages are written.
31    pub async fn send_batch(&mut self, messages: Vec<Message>) -> Result<(), Error> {
32        send_batch(&mut self.writer, messages).await
33    }
34}
35
36pub async fn send<W>(writer: &mut W, message: Message) -> Result<(), Error>
37where
38    W: AsyncWrite + Unpin,
39{
40    let buf = message.encode()?;
41    writer.write_all(&buf).await?;
42    writer.flush().await?;
43    Ok(())
44}
45
46pub async fn send_batch<W>(writer: &mut W, messages: Vec<Message>) -> Result<(), Error>
47where
48    W: AsyncWrite + Unpin,
49{
50    for message in &messages {
51        let buf = message.encode()?;
52        writer.write_all(&buf).await?;
53    }
54    writer.flush().await?;
55    Ok(())
56}