Debian Codegraph @

src/slot.rs

raw symbols SCIP
1 /*
2 * Copyright 2024 Andrey Kutejko <[email protected]>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, see <http://www.gnu.org/licenses/>.
16 *
17 * For more details see the file COPYING.
18 */
19
20 use std::{
21 cell::RefCell,
22 collections::HashMap,
23 rc::Rc,
24 sync::atomic::{AtomicU32, Ordering},
25 };
26
27 pub type Listener<T> = Rc<dyn Fn(&T)>;
28
29 pub struct Slot<T> {
30 id: u32,
31 listeners: RefCell<HashMap<u32, Listener<T>>>,
32 }
33
34 pub struct ListenerId(u32, u32);
35
36 impl<T> Slot<T> {
37 pub fn new() -> Self {
38 Self {
39 id: new_id(),
40 listeners: RefCell::new(HashMap::new()),
41 }
42 }
43
44 pub fn connect(&self, listener: impl Fn(&T) + 'static) -> ListenerId {
45 let listener_id = new_id();
46 self.listeners
47 .borrow_mut()
48 .insert(listener_id, Rc::new(listener));
49 ListenerId(self.id, listener_id)
50 }
51
52 pub fn disconnect(&self, listener_id: ListenerId) {
53 if listener_id.0 == self.id {
54 self.listeners.borrow_mut().remove(&listener_id.1);
55 } else {
56 eprintln!("WARN: Cannot disconnect a listener. Wrong slot id.");
57 }
58 }
59
60 pub fn emit(&self, param: T) {
61 for listener in self.listeners.borrow().values().cloned() {
62 (listener)(&param);
63 }
64 }
65 }
66
67 fn new_id() -> u32 {
68 static LAST_ID: AtomicU32 = AtomicU32::new(1);
69 LAST_ID.fetch_add(1, Ordering::SeqCst)
70 }