use std::marker::PhantomData;
use serde::{de::DeserializeOwned, Serialize};
use tokio::sync::oneshot;
use crate::{channel::Channel, convert::from_bytes};
pub struct ChannelTask<R> {
channel: Channel,
result_rx: oneshot::Receiver<Vec<u8>>,
_phantom: PhantomData<R>,
}
impl<R: DeserializeOwned> ChannelTask<R> {
#[doc(hidden)]
pub fn new(channel: Channel, result_rx: oneshot::Receiver<Vec<u8>>) -> Self {
Self {
channel,
result_rx,
_phantom: PhantomData,
}
}
pub async fn recv<T: DeserializeOwned>(&self) -> Option<T> {
self.channel.recv().await
}
pub async fn recv_bytes(&self) -> Option<Box<[u8]>> {
self.channel.recv_bytes().await
}
pub fn send<T: Serialize>(&self, msg: &T) {
self.channel.send(msg);
}
pub fn send_bytes(&self, bytes: &[u8]) {
self.channel.send_bytes(bytes);
}
pub async fn result(self) -> R {
let bytes = self
.result_rx
.await
.expect("WebWorker result sender dropped");
from_bytes(&bytes)
}
}