Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::iter::Iterator;
- use std::sync::{Arc, Mutex};
- use std::thread;
- pub trait Storage {
- fn store(&mut self, message: i32);
- }
- struct A;
- impl Storage for A {
- fn store(&mut self, message: i32) {
- println!("Store A {}", message);
- }
- }
- struct B;
- impl Storage for B {
- fn store(&mut self, message: i32) {
- println!("Store B {}", message);
- }
- }
- struct Server {
- storage: Arc<Mutex<Vec<Box<Storage + Send>>>>,
- }
- impl Server {
- pub fn new() -> Self {
- Server {
- storage: Arc::new(Mutex::new(vec![])),
- }
- }
- pub fn add_storage<S>(&mut self, storage: Box<S>)
- where
- S: Storage + Send + 'static,
- {
- self.storage
- .lock()
- .and_then(|mut store| {
- store.push(storage);
- Ok(())
- })
- .expect("unable to lock storage mutex");
- }
- pub fn debug_push(self) {
- let storage = Arc::clone(&self.storage);
- thread::spawn(move || handle_stream(storage));
- }
- }
- impl Storage for Box<Storage + Send> {
- fn store(&mut self, message: i32) {
- (**self).store(message);
- }
- }
- fn handle_stream<S>(storage: Arc<Mutex<Vec<S>>>)
- where
- S: Storage + Send + 'static,
- {
- let msg = 42; //generate by server
- match storage.lock().and_then(|mut storage| {
- storage.iter_mut().for_each(|storage| {
- storage.store(msg);
- });
- Ok(())
- }) {
- Ok(_) => println!("Stored message"),
- Err(err) => println!("Problem storing message: {:?}", err),
- };
- }
- fn main() {
- let mut server = Server::new();
- server.add_storage(Box::new(A {}));
- server.add_storage(Box::new(B {}));
- server.debug_push();
- }
Add Comment
Please, Sign In to add comment