Guest User

Untitled

a guest
Feb 15th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. /// A type encapsulating inter-thread channels. This is present mainly to allow various sources of
  2. /// data sent along one channel to be disambiguated by the EventManager, but it also abstracts the
  3. /// specific API used. The type T is the data to be sent along the channel and the type I defines
  4. /// what shall be used for the unique identifier.
  5. pub trait Channel<I, T>
  6. where I: Sync + Send,
  7. T: Sync + Send {
  8. /// Send a message along the channel. This routine should never be implemented in such a
  9. /// fashion that it blocks. It is expected to panic if you call it on the RX end of the
  10. /// channel.
  11. fn send(&mut self, value: T) -> Result<(), ()>;
  12.  
  13. /// Receive the next message from the channel, or block until a message arrives if none are
  14. /// available currently. This function is expected to panic if you call it on the TX end of the
  15. /// channel.
  16. fn recv(&mut self) -> (I, T);
  17.  
  18. /// Construct a new Channel object.
  19. fn new(&mut self) -> Self;
  20.  
  21. /// Construct a new 'sender' suitable for passing into some other thread, given the (hopefully
  22. /// unique) value `tag` to identify that thread.
  23. fn get_tx(&mut self, tag: I) -> Self;
  24. }
  25.  
  26.  
  27. /// A simple API to allow one thread to `ping' another thread, implemented with tags of type `usize`
  28. /// and `std::sync::mpsc` channels.
  29. struct DataChannel<T> {
  30. rx: Option<mpsc::Receiver<(usize, T)>>,
  31. tx: mpsc::Sender<(usize, T)>,
  32. tag: usize,
  33. is_rx: bool,
  34. }
  35.  
  36. impl<T> Channel<usize, T> for DataChannel<T> {
  37. fn send(&mut self, value: T) -> Result<(), ()> {
  38. if self.is_rx {
  39. panic!("Tried to send() down RX end of a Channel.");
  40. }
  41.  
  42. self.tx.send((self.tag, value));
  43. }
  44.  
  45. fn recv(&mut self, value: T) -> (usize, T) {
  46. match self.rx {
  47. Some(rx) => rx.recv(),
  48. None => { panic!("Tried to recv() from TX end of a Channel."); }
  49. }
  50. }
  51.  
  52. fn new(&mut self, tag: usize) -> DataChannel {
  53. let (tx, rx) = mpsc::channel::<(usize, T)>();
  54. DataChannel {
  55. rx: Some(rx),
  56. tx,
  57. tag,
  58. is_rx: true
  59. }
  60. }
  61.  
  62. fn get_tx(&mut self) -> Channel {
  63. DataChannel {
  64. rx: None,
  65. tx: self.tx.clone(),
  66. tag: self.tag,
  67. is_rx: false
  68. }
  69. }
  70. }
Add Comment
Please, Sign In to add comment