use core::borrow::Borrow;
use smoltcp::iface::SocketHandle;
use crate::{ChannelClosedError, Command, Error, Netstack, Response, command::Request};
pub type Channel = flume::WeakSender<Request>;
pub trait HasChannel {
fn borrow_channel(&self) -> impl Borrow<Channel> + Send;
fn command_channel(&self) -> Channel {
self.borrow_channel().borrow().clone()
}
fn request_blocking(
&self,
handle: Option<SocketHandle>,
command: impl Into<Command>,
) -> Result<Response, ChannelClosedError> {
crate::request_blocking(self.borrow_channel().borrow(), handle, command)
}
fn request(
&self,
handle: Option<SocketHandle>,
command: impl Into<Command>,
) -> impl Future<Output = Result<Response, Error>> + Send {
let ch = self.command_channel();
let command = command.into();
async move { crate::request(&ch, handle, command).await }
}
fn request_nonblocking(
&self,
handle: Option<SocketHandle>,
command: impl Into<Command>,
) -> Result<(), ChannelClosedError> {
crate::request_nonblocking(self.borrow_channel().borrow(), handle, command)
}
}
impl HasChannel for Netstack {
fn borrow_channel(&self) -> impl Borrow<Channel> + Send {
self.command_tx.downgrade()
}
}
impl HasChannel for Channel {
fn borrow_channel(&self) -> impl Borrow<Channel> + Send {
self
}
}
impl<T> HasChannel for &T
where
T: HasChannel,
{
fn borrow_channel(&self) -> impl Borrow<Channel> + Send {
(**self).borrow_channel()
}
}
impl<T> HasChannel for &mut T
where
T: HasChannel,
{
fn borrow_channel(&self) -> impl Borrow<Channel> + Send {
(**self).borrow_channel()
}
}