use std::sync::atomic::{AtomicBool, Ordering};
use zmq::{Error, SocketType};
use crate::socket::{MessageBuf, Sender, SocketBuilder, ZmqSocket};
pub fn reply(endpoint: &str) -> Result<SocketBuilder<'_, Reply>, zmq::Error> {
let socket = zmq::Context::new().socket(SocketType::REP)?;
Ok(SocketBuilder::new(socket, endpoint))
}
pub struct Reply {
inner: Sender,
received: AtomicBool,
}
impl From<zmq::Socket> for Reply {
fn from(socket: zmq::Socket) -> Self {
Self {
inner: Sender {
socket: ZmqSocket::from(socket),
buffer: MessageBuf::default(),
},
received: AtomicBool::new(false),
}
}
}
impl Reply {
pub async fn recv(&self) -> Result<MessageBuf, Error> {
let msg = async_std::future::poll_fn(|cx| self.inner.socket.recv(cx)).await?;
self.received.store(true, Ordering::Relaxed);
Ok(msg)
}
pub async fn send<T: Into<MessageBuf>>(&self, msg: T) -> Result<(), Error> {
let mut msg = msg.into();
let res =
async_std::future::poll_fn(move |cx| self.inner.socket.send(cx, &mut msg)).await?;
self.received.store(false, Ordering::Relaxed);
Ok(res)
}
pub fn as_raw_socket(&self) -> &zmq::Socket {
&self.inner.socket.get_ref().0
}
}