Guest User

Untitled

a guest
Nov 17th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. #![allow(unused)]
  2. use std::cell::RefCell;
  3. use std::collections::HashMap;
  4. use std::rc::Rc;
  5. use std::thread::{self, sleep};
  6.  
  7. struct Core {
  8. m: HashMap<u8, Rc<RefCell<State>>>,
  9. tx_msg: std::sync::mpsc::Sender<Msg>,
  10. }
  11.  
  12. trait State {
  13. fn terminate(&mut self, &mut Core);
  14. }
  15.  
  16. struct QueuedReq<T, F>(Option<F>, std::marker::PhantomData<T>);
  17. struct Inner<T, F>(u8, Option<F>, Option<T>);
  18. impl<T: 'static, F: FnOnce(T) + 'static> QueuedReq<T, F> {
  19. fn new(co: &mut Core, f: F) -> Self {
  20. QueuedReq(Some(f), std::marker::PhantomData)
  21. }
  22.  
  23. fn fire(&mut self, co: &mut Core, t: T) {
  24. let f = self.0.take().unwrap();
  25. let qr = Inner(99, Some(f), Some(t));
  26. let qr = Rc::new(RefCell::new(qr));
  27. co.m.insert(99, qr);
  28.  
  29. co.tx_msg.send(Msg::new(move |co| {
  30. let qr = co.m.get(&99).unwrap().clone();
  31. qr.borrow_mut().terminate(co);
  32. }));
  33. }
  34. }
  35.  
  36. impl<T: 'static, F: FnOnce(T) + 'static> State for Inner<T, F> {
  37. fn terminate(&mut self, co: &mut Core) {
  38. co.m.remove(&self.0).unwrap();
  39. let t = self.2.take().unwrap();
  40. self.1.take().unwrap()(t);
  41. }
  42. }
  43.  
  44. fn foo(co: &mut Core) {
  45. let mut c = "C".to_string();
  46. let h = move |(a, b)| {
  47. let c = std::mem::replace(&mut c, Default::default());
  48. handle(a, b, c);
  49. };
  50. let qr = QueuedReq::new(co, h);
  51. bar(co, qr);
  52. }
  53.  
  54. fn handle(a: String, b: Vec<u8>, c: String) {
  55. println!("{},\t{:?},\t{}", a, b, c);
  56. }
  57.  
  58. type Finish<F> = QueuedReq<(String, Vec<u8>), F>;
  59.  
  60. fn bar<F: FnMut((String, Vec<u8>)) + 'static>(co: &mut Core, mut f: Finish<F>) {
  61. let a = "hello".to_string();
  62. let b = vec![2, 3, 4];
  63. f.fire(co, (a, b));
  64. }
  65.  
  66. fn main() {
  67. let (tx_done, rx_done) = std::sync::mpsc::channel::<()>();
  68. thread::spawn(move || run(tx_done));
  69. rx_done.recv().unwrap();
  70. }
  71.  
  72. struct Msg(Box<FnMut(&mut Core) + 'static + Send>);
  73. impl Msg {
  74. fn new<F: FnOnce(&mut Core) + Send + 'static>(f: F) -> Self {
  75. let mut f = Some(f);
  76. Msg(Box::new(move |co: &mut Core| {
  77. let f = f.take().unwrap();
  78. f(co)
  79. }))
  80. }
  81. fn invoke(&mut self, co: &mut Core) {
  82. (self.0)(co)
  83. }
  84. }
  85.  
  86. fn run(tx_done: std::sync::mpsc::Sender<()>) {
  87. let (tx_msg, rx_msg) = std::sync::mpsc::channel::<Msg>();
  88.  
  89. let mut co = Core {
  90. m: Default::default(),
  91. tx_msg,
  92. };
  93.  
  94. foo(&mut co);
  95.  
  96. rx_msg.recv().unwrap().invoke(&mut co);
  97. }
Add Comment
Please, Sign In to add comment