async-circe/src/stream/write.rs

40 lines
987 B
Rust

use parking_lot::RwLock;
use std::sync::Arc;
use tokio::io::{AsyncWriteExt, Error, WriteHalf};
use tokio::net::TcpStream;
#[cfg(feature = "tls")]
use tokio_rustls::client::TlsStream;
#[derive(Clone)]
pub struct Write {
#[cfg(feature = "tls")]
pub tx: Arc<RwLock<WriteHalf<TlsStream<TcpStream>>>>,
#[cfg(not(feature = "tls"))]
pub tx: Arc<RwLock<WriteHalf<TcpStream>>>,
}
impl Write {
#[cfg(not(feature = "tls"))]
pub async fn new(tx: WriteHalf<TcpStream>) -> Self {
Self {
tx: Arc::new(RwLock::new(tx)),
}
}
#[cfg(feature = "tls")]
pub async fn new(tx: WriteHalf<TlsStream<TcpStream>>) -> Self {
Self {
tx: Arc::new(RwLock::new(tx)),
}
}
/// # Errors
/// Returns errors from the ``TcpStream``.
pub async fn write(self, buf: String) -> Result<(), Error> {
tracing::trace!("{:?}", buf);
self.tx.write().write_all(buf.as_bytes()).await?;
Ok(())
}
}