Review a generated event bus

from Cell and RefCell
Rust 1.98 advanced 8 min 4 issues to find

Review this generated single-threaded event bus against the stated contract.

Keep subscriber names unique, let callbacks subscribe safely, apply changes on the next publication, clone only cheap handles for a snapshot, and produce no output.

Rust
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone)]
struct Handler {
    name: String,
    run: Rc<dyn Fn(&Bus)>,
}
struct Bus { handlers: RefCell<Vec<Handler>> }
impl Bus {
    fn subscribe(&self, handler: Handler) -> bool {
        self.handlers.borrow_mut().push(handler);
        true
    }
    fn publish(&self) {
        let snapshot = self.handlers.borrow().clone();
        let _exclusive = self.handlers.borrow_mut();
        for handler in snapshot {
            (handler.run)(self);
        }
        println!("published");
    }
}

generated code is illustrative, not from any one model

Open in playground
Report an error