refactor: random cleanups and efficiency improvements

This commit is contained in:
2025-02-23 17:19:26 -05:00
parent 2ea7ec9e7e
commit 36054ced03
5 changed files with 69 additions and 58 deletions

View File

@@ -1,17 +1,24 @@
use crate::State;
use futures::executor::block_on;
use crate::ListenerMap;
use futures::{executor::block_on, lock::Mutex};
use mlua::{Function, Lua, Result, Table};
use std::time::{SystemTime, UNIX_EPOCH};
use std::{
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
pub async fn register_functions(lua: &Lua, globals: &Table, state: State) -> Result<()> {
let l = state.event_listeners.clone();
pub fn register_functions(
lua: &Lua,
globals: &Table,
event_listeners: Arc<Mutex<ListenerMap>>,
) -> Result<()> {
let m = event_listeners.clone();
globals.set(
"add_listener",
lua.create_function(
move |_, (event_type, callback, id): (String, Function, Option<String>)| {
let l = l.clone();
let m = m.clone();
tokio::spawn(async move {
l.lock().await.entry(event_type).or_default().push((
m.lock().await.entry(event_type).or_default().push((
id.unwrap_or(callback.info().name.unwrap_or(format!(
"anonymous @ {}",
SystemTime::now()
@@ -27,21 +34,21 @@ pub async fn register_functions(lua: &Lua, globals: &Table, state: State) -> Res
)?,
)?;
let l = state.event_listeners.clone();
let m = event_listeners.clone();
globals.set(
"remove_listener",
lua.create_function(move |_, (event_type, target_id): (String, String)| {
let l = l.clone();
let m = m.clone();
tokio::spawn(async move {
let mut l = l.lock().await;
let empty = if let Some(listeners) = l.get_mut(&event_type) {
let mut m = m.lock().await;
let empty = if let Some(listeners) = m.get_mut(&event_type) {
listeners.retain(|(id, _)| target_id != *id);
listeners.is_empty()
} else {
false
};
if empty {
l.remove(&event_type);
m.remove(&event_type);
}
});
Ok(())
@@ -51,10 +58,10 @@ pub async fn register_functions(lua: &Lua, globals: &Table, state: State) -> Res
globals.set(
"get_listeners",
lua.create_function(move |lua, (): ()| {
let l = block_on(state.event_listeners.lock());
let m = block_on(event_listeners.lock());
let listeners = lua.create_table()?;
for (event_type, callbacks) in l.iter() {
for (event_type, callbacks) in m.iter() {
let type_listeners = lua.create_table()?;
for (id, callback) in callbacks {
let listener = lua.create_table()?;