Guest User

Untitled

a guest
May 28th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. use std::iter::Iterator;
  2. use std::sync::{Arc, Mutex};
  3. use std::thread;
  4.  
  5. pub trait Storage {
  6. fn store(&mut self, message: i32);
  7. }
  8.  
  9. struct A;
  10. impl Storage for A {
  11. fn store(&mut self, message: i32) {
  12. println!("Store A {}", message);
  13. }
  14. }
  15.  
  16. struct B;
  17. impl Storage for B {
  18. fn store(&mut self, message: i32) {
  19. println!("Store B {}", message);
  20. }
  21. }
  22.  
  23. struct Server {
  24. storage: Arc<Mutex<Vec<Box<Storage + Send>>>>,
  25. }
  26.  
  27. impl Server {
  28. pub fn new() -> Self {
  29. Server {
  30. storage: Arc::new(Mutex::new(vec![])),
  31. }
  32. }
  33.  
  34. pub fn add_storage<S>(&mut self, storage: Box<S>)
  35. where
  36. S: Storage + Send + 'static,
  37. {
  38. self.storage
  39. .lock()
  40. .and_then(|mut store| {
  41. store.push(storage);
  42. Ok(())
  43. })
  44. .expect("unable to lock storage mutex");
  45. }
  46.  
  47. pub fn debug_push(self) {
  48. let storage = Arc::clone(&self.storage);
  49. thread::spawn(move || handle_stream(storage));
  50. }
  51. }
  52.  
  53. impl Storage for Box<Storage + Send> {
  54. fn store(&mut self, message: i32) {
  55. (**self).store(message);
  56. }
  57. }
  58.  
  59. fn handle_stream<S>(storage: Arc<Mutex<Vec<S>>>)
  60. where
  61. S: Storage + Send + 'static,
  62. {
  63. let msg = 42; //generate by server
  64.  
  65. match storage.lock().and_then(|mut storage| {
  66. storage.iter_mut().for_each(|storage| {
  67. storage.store(msg);
  68. });
  69. Ok(())
  70. }) {
  71. Ok(_) => println!("Stored message"),
  72. Err(err) => println!("Problem storing message: {:?}", err),
  73. };
  74. }
  75.  
  76. fn main() {
  77. let mut server = Server::new();
  78. server.add_storage(Box::new(A {}));
  79. server.add_storage(Box::new(B {}));
  80. server.debug_push();
  81. }
Add Comment
Please, Sign In to add comment