salsa/tests/accumulate-reuse-workaround.rs

76 lines
2 KiB
Rust
Raw Normal View History

2022-08-17 10:55:27 +00:00
//! Demonstrates the workaround of wrapping calls to
//! `accumulated` in a tracked function to get better
//! reuse.
2024-06-18 07:40:21 +00:00
mod common;
use common::{LogDatabase, LoggerDatabase};
2022-08-17 10:55:27 +00:00
use expect_test::expect;
use salsa::{Accumulator, Setter};
2022-08-17 10:55:27 +00:00
use test_log::test;
#[salsa::input]
struct List {
value: u32,
next: Option<List>,
}
#[salsa::accumulator]
2024-07-19 11:08:11 +00:00
#[derive(Copy)]
2022-08-17 10:55:27 +00:00
struct Integers(u32);
#[salsa::tracked]
fn compute(db: &dyn LogDatabase, input: List) -> u32 {
2022-08-17 10:55:27 +00:00
db.push_log(format!("compute({:?})", input,));
// always pushes 0
2024-07-16 10:04:01 +00:00
Integers(0).accumulate(db);
2022-08-17 10:55:27 +00:00
let result = if let Some(next) = input.next(db) {
let next_integers = accumulated(db, next);
let v = input.value(db) + next_integers.iter().sum::<u32>();
v
} else {
input.value(db)
};
// return value changes
result
}
#[salsa::tracked(return_ref)]
fn accumulated(db: &dyn LogDatabase, input: List) -> Vec<u32> {
db.push_log(format!("accumulated({:?})", input));
2022-08-17 10:55:27 +00:00
compute::accumulated::<Integers>(db, input)
2024-07-16 10:04:01 +00:00
.into_iter()
.map(|a| a.0)
.collect()
2022-08-17 10:55:27 +00:00
}
#[test]
fn test1() {
let mut db = LoggerDatabase::default();
2022-08-17 10:55:27 +00:00
let l1 = List::new(&db, 1, None);
let l2 = List::new(&db, 2, Some(l1));
2022-08-17 10:55:27 +00:00
assert_eq!(compute(&db, l2), 2);
db.assert_logs(expect![[r#"
[
"compute(List { [salsa id]: Id(1), value: 2, next: Some(List { [salsa id]: Id(0), value: 1, next: None }) })",
"accumulated(List { [salsa id]: Id(0), value: 1, next: None })",
"compute(List { [salsa id]: Id(0), value: 1, next: None })",
2022-08-17 10:55:27 +00:00
]"#]]);
// When we mutate `l1`, we should re-execute `compute` for `l1`,
// and we re-execute accumulated for `l1`, but we do NOT re-execute
// `compute` for `l2`.
2022-08-22 10:32:04 +00:00
l1.set_value(&mut db).to(2);
2022-08-17 10:55:27 +00:00
assert_eq!(compute(&db, l2), 2);
db.assert_logs(expect![[r#"
[
"accumulated(List { [salsa id]: Id(0), value: 2, next: None })",
"compute(List { [salsa id]: Id(0), value: 2, next: None })",
2022-08-17 10:55:27 +00:00
]"#]]);
}