Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// A type encapsulating inter-thread channels. This is present mainly to allow various sources of
- /// data sent along one channel to be disambiguated by the EventManager, but it also abstracts the
- /// specific API used. The type T is the data to be sent along the channel and the type I defines
- /// what shall be used for the unique identifier.
- pub trait Channel<I, T>
- where I: Sync + Send,
- T: Sync + Send {
- /// Send a message along the channel. This routine should never be implemented in such a
- /// fashion that it blocks. It is expected to panic if you call it on the RX end of the
- /// channel.
- fn send(&mut self, value: T) -> Result<(), ()>;
- /// Receive the next message from the channel, or block until a message arrives if none are
- /// available currently. This function is expected to panic if you call it on the TX end of the
- /// channel.
- fn recv(&mut self) -> (I, T);
- /// Construct a new Channel object.
- fn new(&mut self) -> Self;
- /// Construct a new 'sender' suitable for passing into some other thread, given the (hopefully
- /// unique) value `tag` to identify that thread.
- fn get_tx(&mut self, tag: I) -> Self;
- }
- /// A simple API to allow one thread to `ping' another thread, implemented with tags of type `usize`
- /// and `std::sync::mpsc` channels.
- struct DataChannel<T> {
- rx: Option<mpsc::Receiver<(usize, T)>>,
- tx: mpsc::Sender<(usize, T)>,
- tag: usize,
- is_rx: bool,
- }
- impl<T> Channel<usize, T> for DataChannel<T> {
- fn send(&mut self, value: T) -> Result<(), ()> {
- if self.is_rx {
- panic!("Tried to send() down RX end of a Channel.");
- }
- self.tx.send((self.tag, value));
- }
- fn recv(&mut self, value: T) -> (usize, T) {
- match self.rx {
- Some(rx) => rx.recv(),
- None => { panic!("Tried to recv() from TX end of a Channel."); }
- }
- }
- fn new(&mut self, tag: usize) -> DataChannel {
- let (tx, rx) = mpsc::channel::<(usize, T)>();
- DataChannel {
- rx: Some(rx),
- tx,
- tag,
- is_rx: true
- }
- }
- fn get_tx(&mut self) -> Channel {
- DataChannel {
- rx: None,
- tx: self.tx.clone(),
- tag: self.tag,
- is_rx: false
- }
- }
- }
Add Comment
Please, Sign In to add comment