1use std::collections::BTreeMap;
9use std::panic::Location;
10
11use waft_foundation::App;
12
13type Site = (&'static str, &'static Location<'static>);
15
16#[derive(Debug, Clone)]
19pub struct ObjectSnapshot {
20 counts: BTreeMap<Site, usize>,
21}
22
23pub fn object_snapshot(app: &App) -> ObjectSnapshot {
25 let mut counts = BTreeMap::new();
26 for object in app.debug_live_objects() {
27 *counts
28 .entry((object.type_name, object.created_at))
29 .or_insert(0) += 1;
30 }
31 ObjectSnapshot { counts }
32}
33
34#[track_caller]
42pub fn assert_no_new_objects(app: &App, snapshot: &ObjectSnapshot) {
43 let now = object_snapshot(app);
44 let mut message = String::new();
45 for (&(type_name, created_at), &count) in &now.counts {
46 let before = snapshot
47 .counts
48 .get(&(type_name, created_at))
49 .copied()
50 .unwrap_or(0);
51 if count > before {
52 message.push_str(&format!(
53 "\n +{} `{type_name}` created at {created_at}",
54 count - before
55 ));
56 }
57 }
58 if !message.is_empty() {
59 panic!("objects made since the snapshot are still held:{message}");
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use waft_foundation::AppCell;
66
67 use super::*;
68
69 #[test]
70 fn an_object_made_after_the_snapshot_and_still_held_is_named() {
71 let cell = AppCell::new();
72 let snapshot = object_snapshot(&cell.borrow());
73 let kept = cell.borrow_mut().create(7u32);
74 let dropped = cell.borrow_mut().create(8u64);
75 drop(dropped);
76 cell.checkpoint();
77 let message = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
78 assert_no_new_objects(&cell.borrow(), &snapshot);
79 }))
80 .expect_err("the kept object fails the check");
81 let message = message
82 .downcast_ref::<String>()
83 .expect("a formatted message");
84 assert!(message.contains("+1 `u32`"), "{message}");
85 assert!(!message.contains("`u64`"), "{message}");
86 assert!(message.contains("objects.rs"), "{message}");
87 drop(kept);
88 cell.checkpoint();
89 assert_no_new_objects(&cell.borrow(), &snapshot);
90 }
91
92 #[test]
93 fn an_object_replaced_by_one_made_at_the_same_site_is_no_leak() {
94 let cell = AppCell::new();
95 let make = |cell: &AppCell| cell.borrow_mut().create(1u32);
96 let first = make(&cell);
97 cell.checkpoint();
98 let snapshot = object_snapshot(&cell.borrow());
99 let second = make(&cell);
100 drop(first);
101 cell.checkpoint();
102 assert_no_new_objects(&cell.borrow(), &snapshot);
103 drop(second);
104 }
105}