Use a helper method for adding notification listeners.

This commit is contained in:
2025-12-08 13:14:12 -05:00
parent d8912c58e6
commit d8057575ce
+21 -25
View File
@@ -1,11 +1,28 @@
use std::{
collections::{hash_map::Entry, HashMap},
ffi::{c_void, CStr},
hash,
hash::{self, Hash},
ptr::{self, NonNull},
sync::{Mutex, OnceLock},
};
// Helper function for adding the entry `(key, (observer, action))` to `map`.
fn register<K: Eq + Hash>(
map: &mut HashMap<K, Vec<(Option<Sendable>, Action)>>,
key: K,
observer: Option<Sendable>,
action: Action,
) {
match map.entry(key) {
Entry::Occupied(mut o) => {
o.get_mut().push((observer, action));
}
Entry::Vacant(v) => {
v.insert(vec![(observer, action)]);
}
}
}
/// Lightweight message from object to another. When a notification is sent,
/// registered [`Action`]s are called.
///
@@ -119,14 +136,7 @@ impl NotificationCenter {
observer: Option<Sendable>,
action: Action,
) {
match self.exact.entry((name, source)) {
Entry::Occupied(mut o) => {
o.get_mut().push((observer, action));
}
Entry::Vacant(v) => {
v.insert(vec![(observer, action)]);
}
}
register(&mut self.exact, (name, source), observer, action);
}
/// Registers `action` to be invoked on `observer` when notifications are
@@ -137,14 +147,7 @@ impl NotificationCenter {
observer: Option<Sendable>,
action: Action,
) {
match self.by_source.entry(source) {
Entry::Occupied(mut o) => {
o.get_mut().push((observer, action));
}
Entry::Vacant(v) => {
v.insert(vec![(observer, action)]);
}
}
register(&mut self.by_source, source, observer, action);
}
/// Registers `action` to be invoked on `observer` for all notifications
@@ -155,14 +158,7 @@ impl NotificationCenter {
observer: Option<Sendable>,
action: Action,
) {
match self.by_name.entry(name) {
Entry::Occupied(mut o) => {
o.get_mut().push((observer, action));
}
Entry::Vacant(v) => {
v.insert(vec![(observer, action)]);
}
}
register(&mut self.by_name, name, observer, action);
}
/// Registers `action` to be invoked on `observer` for all notifications,