salsa/examples/calc/db.rs

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