1use std::{cell::RefCell, collections::HashSet, sync::Arc};
2
3use crate::{SignalCore, SourceId};
4
5#[derive(Default)]
6struct BatchState {
7 depth: usize,
8 queued: HashSet<SourceId>,
9 pending: Vec<Arc<SignalCore>>,
10}
11
12thread_local! {
13 static BATCH: RefCell<BatchState> = RefCell::new(BatchState::default());
14}
15
16pub fn batch<R>(writes: impl FnOnce() -> R) -> R {
37 BATCH.with(|batch| batch.borrow_mut().depth += 1);
38 let _flush = FlushOnDrop;
39 writes()
40}
41
42struct FlushOnDrop;
43
44impl Drop for FlushOnDrop {
45 fn drop(&mut self) {
46 let pending = BATCH.with(|batch| {
47 let mut batch = batch.borrow_mut();
48 batch.depth -= 1;
49 if batch.depth > 0 {
50 return Vec::new();
51 }
52 batch.queued.clear();
53 std::mem::take(&mut batch.pending)
54 });
55 for core in pending {
57 core.deliver();
58 }
59 }
60}
61
62pub(crate) fn defer(core: &Arc<SignalCore>) -> bool {
65 BATCH
66 .try_with(|batch| {
67 let mut batch = batch.borrow_mut();
68 if batch.depth == 0 {
69 return false;
70 }
71 if batch.queued.insert(core.source_id()) {
72 batch.pending.push(Arc::clone(core));
73 }
74 true
75 })
76 .unwrap_or(false)
77}
78
79#[cfg(test)]
80mod tests {
81 use std::sync::{
82 Arc, Mutex,
83 atomic::{AtomicUsize, Ordering},
84 };
85
86 use crate::{Observable, Observer, Signal, batch};
87
88 #[test]
89 fn batch_notifies_each_signal_once_with_latest_version() {
90 let first = Signal::new(0_u32);
91 let second = Signal::new(0_u32);
92 let log = Arc::new(Mutex::new(Vec::new()));
93 let first_log = Arc::clone(&log);
94 let second_log = Arc::clone(&log);
95 let _first = first.subscribe(Observer::new(move |change| {
96 first_log.lock().unwrap().push(("first", change.version));
97 }));
98 let _second = second.subscribe(Observer::new(move |change| {
99 second_log.lock().unwrap().push(("second", change.version));
100 }));
101
102 batch(|| {
103 first.set(1);
104 second.set(1);
105 first.set(2);
106 batch(|| first.set(3));
107 assert_eq!(first.get(), 3, "reads see writes inside the batch");
108 assert!(log.lock().unwrap().is_empty(), "nested batch did not flush");
109 });
110
111 assert_eq!(*log.lock().unwrap(), vec![("first", 3), ("second", 1)]);
112 }
113
114 #[test]
115 fn selector_over_batched_signal_recomputes_once() {
116 let state = Signal::new((0_u32, 0_u32));
117 let sum = state.select(|(a, b)| a + b);
118 let notifications = Arc::new(AtomicUsize::new(0));
119 let count = Arc::clone(¬ifications);
120 let _subscription = sum.subscribe(Observer::new(move |_| {
121 count.fetch_add(1, Ordering::Relaxed);
122 }));
123
124 batch(|| {
125 state.update(|state| state.0 = 1);
126 state.update(|state| state.1 = 2);
127 });
128 assert_eq!(notifications.load(Ordering::Relaxed), 1);
129 assert_eq!(sum.get(), 3);
130 }
131
132 #[test]
133 fn batch_only_defers_the_calling_thread() {
134 let signal = Signal::new(0_u32);
135 let notifications = Arc::new(AtomicUsize::new(0));
136 let count = Arc::clone(¬ifications);
137 let _subscription = signal.subscribe(Observer::new(move |_| {
138 count.fetch_add(1, Ordering::Relaxed);
139 }));
140 batch(|| {
141 let writer = signal.clone();
142 std::thread::spawn(move || writer.set(1)).join().unwrap();
143 assert_eq!(notifications.load(Ordering::Relaxed), 1);
144 });
145 }
146
147 #[test]
148 fn batch_flushes_after_a_panic() {
149 let signal = Signal::new(0_u32);
150 let notifications = Arc::new(AtomicUsize::new(0));
151 let count = Arc::clone(¬ifications);
152 let _subscription = signal.subscribe(Observer::new(move |_| {
153 count.fetch_add(1, Ordering::Relaxed);
154 }));
155 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
156 batch(|| {
157 signal.set(1);
158 panic!("worker failed");
159 })
160 }));
161 assert!(result.is_err());
162 assert_eq!(notifications.load(Ordering::Relaxed), 1);
163 signal.set(2);
165 assert_eq!(notifications.load(Ordering::Relaxed), 2);
166 }
167}