salsa/examples/calc/db.rs

53 lines
1.3 KiB
Rust
Raw Normal View History

use std::sync::{Arc, Mutex};
2022-08-01 05:32:47 +00:00
// ANCHOR: db_struct
2022-08-24 16:43:29 +00:00
#[derive(Default)]
2024-07-15 11:46:23 +00:00
#[salsa::db]
2022-08-01 05:32:47 +00:00
pub(crate) struct Database {
storage: salsa::Storage<Self>,
// The logs are only used for testing and demonstrating reuse:
//
logs: Option<Arc<Mutex<Vec<String>>>>,
2022-08-01 05:32:47 +00:00
}
// ANCHOR_END: db_struct
impl Database {
/// Enable logging of each salsa event.
#[cfg(test)]
pub fn enable_logging(self) -> Self {
assert!(self.logs.is_none());
Self {
storage: self.storage,
logs: Some(Default::default()),
}
}
#[cfg(test)]
pub fn take_logs(&mut self) -> Vec<String> {
if let Some(logs) = &self.logs {
std::mem::take(&mut *logs.lock().unwrap())
} else {
panic!("logs not enabled");
}
}
}
2022-08-01 05:32:47 +00:00
// ANCHOR: db_impl
2024-07-15 11:46:23 +00:00
#[salsa::db]
2022-08-01 05:32:47 +00:00
impl salsa::Database for Database {
fn salsa_event(&self, event: salsa::Event) {
2024-03-16 11:18:52 +00:00
eprintln!("Event: {event:?}");
// Log interesting events, if logging is enabled
if let Some(logs) = &self.logs {
2022-08-24 16:43:29 +00:00
// don't log boring events
if let salsa::EventKind::WillExecute { .. } = event.kind {
logs.lock()
.unwrap()
.push(format!("Event: {:?}", event.debug(self)));
}
}
}
2022-08-01 05:32:47 +00:00
}
// ANCHOR_END: db_impl