pub mod types { pub use trixy_types::*; } pub mod macros { pub use trixy_macros::*; } pub mod oneshot { use std::{ mem, sync::mpsc::{self, RecvError, SendError, TryRecvError}, }; #[derive(Clone, Debug)] pub struct Sender { channel: mpsc::Sender, } #[derive(Debug)] pub struct Receiver { channel: mpsc::Receiver, last_value: Option, } pub fn channel() -> (Sender, Receiver) { let (tx, rx) = mpsc::channel(); ( Sender { channel: tx }, Receiver { channel: rx, last_value: None, }, ) } impl Sender { pub fn send(&self, input: T) -> Result<(), SendError> { self.channel.send(input) } } impl Receiver { pub fn try_recv(&mut self) -> Result { match self.channel.try_recv() { Ok(ok) => { self.close(); self.last_value = Some(ok); Ok(true) } Err(err) => Err(err), } } pub fn close(&mut self) { let (_, recv) = mpsc::channel(); let channel = mem::replace(&mut self.channel, recv); drop(channel); } pub fn recv(mut self) -> Result { match self.channel.recv() { Ok(ok) => { self.close(); Ok(ok) } Err(err) => { if let Some(val) = self.last_value { Ok(val) } else { Err(err) } } } } } }