1use std::{
2 any::Any,
3 cell::RefCell,
4 rc::{Rc, Weak},
5};
6
7use super::{RuntimeHandle, StateHandleLease};
8use crate::{
9 MutableStateInner, RecomposeScope, ScopeId,
10 collections::map::HashMap,
11 state::{MutationPolicy, NeverEqual},
12};
13
14struct TypedStateCell<T: Clone + 'static> {
15 inner: MutableStateInner<T>,
16}
17
18trait ScopeWatchCell {
19 fn unregister_scope(&self, scope_id: ScopeId);
20 fn forget_scope(&self, scope_id: ScopeId);
21 fn invalidate_watchers(&self);
22}
23
24impl<T: Clone + 'static> ScopeWatchCell for TypedStateCell<T> {
25 fn unregister_scope(&self, scope_id: ScopeId) {
26 self.inner.unregister_scope(scope_id);
27 }
28
29 fn forget_scope(&self, scope_id: ScopeId) {
30 self.inner.forget_scope(scope_id);
31 }
32
33 fn invalidate_watchers(&self) {
34 self.inner.invalidate_watchers();
35 }
36}
37
38struct StateArenaSlot {
39 generation: u32,
40 cell: Option<Rc<dyn Any>>,
41 watcher_cell: Option<Rc<dyn ScopeWatchCell>>,
42 lease: Option<Weak<StateHandleLease>>,
43}
44
45#[derive(Default)]
46struct StateArenaInner {
47 cells: Vec<StateArenaSlot>,
48 free: Vec<u32>,
49 derived: HashMap<u32, Weak<dyn DerivedRefresh>>,
51}
52
53pub(crate) trait DerivedRefresh {
55 fn refresh(&self);
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
63pub struct StateArenaDebugStats {
64 pub cells_len: usize,
66 pub cells_cap: usize,
68 pub free_len: usize,
70 pub free_cap: usize,
72}
73
74#[derive(Default)]
75pub(crate) struct StateArena {
76 inner: RefCell<StateArenaInner>,
77 spare_readers: RefCell<Vec<RecomposeScope>>,
80}
81
82impl StateArena {
83 pub(crate) fn take_reader_list(&self) -> Vec<RecomposeScope> {
85 std::mem::take(&mut *self.spare_readers.borrow_mut())
86 }
87
88 pub(crate) fn recycle_reader_list(&self, mut readers: Vec<RecomposeScope>) {
90 readers.clear();
92 let mut spare = self.spare_readers.borrow_mut();
93 if spare.capacity() < readers.capacity() {
94 *spare = readers;
95 }
96 }
97
98 pub(crate) fn alloc<T: Clone + 'static>(&self, value: T, runtime: RuntimeHandle) -> StateId {
99 self.alloc_with_policy(value, runtime, Rc::new(NeverEqual))
100 }
101
102 fn claim_slot(&self) -> StateId {
104 let mut inner = self.inner.borrow_mut();
105 loop {
106 let Some(slot) = inner.free.pop() else {
107 let slot = inner.cells.len() as u32;
108 inner.cells.push(StateArenaSlot {
109 generation: 0,
110 cell: None,
111 watcher_cell: None,
112 lease: None,
113 });
114 return StateId::new(slot, 0);
115 };
116
117 let Some(entry) = inner.cells.get_mut(slot as usize) else {
118 continue;
119 };
120 if entry.cell.is_some() {
121 continue;
122 }
123
124 entry.watcher_cell = None;
125 entry.lease = None;
126 entry.generation = entry.generation.wrapping_add(1);
127 return StateId::new(slot, entry.generation);
128 }
129 }
130
131 pub(crate) fn alloc_with_policy<T: Clone + 'static>(
132 &self,
133 value: T,
134 runtime: RuntimeHandle,
135 policy: Rc<dyn MutationPolicy<T>>,
136 ) -> StateId {
137 let id = self.claim_slot();
138 let slot = id.slot();
139 let inner = MutableStateInner::new_with_policy(value, runtime, policy);
140 inner.install_snapshot_observer(id);
141 let typed_cell = Rc::new(TypedStateCell { inner });
142 let cell: Rc<dyn Any> = Rc::<TypedStateCell<T>>::clone(&typed_cell);
143 let watcher_cell: Rc<dyn ScopeWatchCell> = typed_cell;
144 let mut arena = self.inner.borrow_mut();
145 let slot_entry = &mut arena.cells[slot as usize];
146 slot_entry.cell = Some(cell);
147 slot_entry.watcher_cell = Some(watcher_cell);
148 id
149 }
150
151 pub(crate) fn alloc_plain<T: 'static>(&self, value: T) -> StateId {
154 let id = self.claim_slot();
155 let cell: Rc<dyn Any> = Rc::new(value);
156 self.inner.borrow_mut().cells[id.slot_index()].cell = Some(cell);
157 id
158 }
159
160 pub(crate) fn plain<T: 'static>(&self, id: StateId) -> Option<Rc<T>> {
162 Rc::downcast::<T>(self.get_cell_opt(id)?).ok()
163 }
164
165 fn get_cell_opt(&self, id: StateId) -> Option<Rc<dyn Any>> {
166 self.inner
167 .borrow()
168 .cells
169 .get(id.slot_index())
170 .filter(|cell| cell.generation == id.generation())
171 .and_then(|cell| cell.cell.as_ref())
172 .cloned()
173 }
174
175 fn get_typed<T: Clone + 'static>(&self, id: StateId) -> Rc<TypedStateCell<T>> {
176 match self.get_cell_opt(id) {
177 None => panic!(
178 "state cell missing: slot={}, gen={}, expected={}",
179 id.slot(),
180 id.generation(),
181 std::any::type_name::<T>(),
182 ),
183 Some(cell) => Rc::downcast::<TypedStateCell<T>>(cell).unwrap_or_else(|_| {
184 panic!(
185 "state cell type mismatch: slot={}, gen={}, expected={}",
186 id.slot(),
187 id.generation(),
188 std::any::type_name::<T>(),
189 )
190 }),
191 }
192 }
193
194 fn get_typed_opt<T: Clone + 'static>(&self, id: StateId) -> Option<Rc<TypedStateCell<T>>> {
195 Rc::downcast::<TypedStateCell<T>>(self.get_cell_opt(id)?).ok()
196 }
197
198 pub(crate) fn with_typed<T: Clone + 'static, R>(
199 &self,
200 id: StateId,
201 f: impl FnOnce(&MutableStateInner<T>) -> R,
202 ) -> R {
203 let cell = self.get_typed::<T>(id);
204 f(&cell.inner)
205 }
206
207 pub(crate) fn with_typed_opt<T: Clone + 'static, R>(
208 &self,
209 id: StateId,
210 f: impl FnOnce(&MutableStateInner<T>) -> R,
211 ) -> Option<R> {
212 let cell = self.get_typed_opt::<T>(id)?;
213 Some(f(&cell.inner))
214 }
215
216 pub(crate) fn release(&self, id: StateId) {
217 let cell = {
218 let mut inner = self.inner.borrow_mut();
219 let Some(slot) = inner.cells.get_mut(id.slot_index()) else {
220 return;
221 };
222 if slot.generation != id.generation() {
223 return;
224 }
225 slot.lease = None;
226 slot.watcher_cell = None;
227 let cell = slot.cell.take();
228 if cell.is_some() {
229 inner.free.push(id.slot());
230 if !inner.derived.is_empty() {
231 inner.derived.remove(&id.slot());
232 }
233 }
234 cell
235 };
236 drop(cell);
237 }
238
239 pub(crate) fn register_derived(&self, id: StateId, refresh: Weak<dyn DerivedRefresh>) {
242 self.inner.borrow_mut().derived.insert(id.slot(), refresh);
243 }
244
245 #[cold]
248 pub(crate) fn refresh_derived(&self, id: StateId) {
249 let refresh = {
250 let inner = self.inner.borrow();
251 inner
252 .cells
253 .get(id.slot_index())
254 .filter(|cell| cell.generation == id.generation())
255 .and_then(|_| inner.derived.get(&id.slot()))
256 .and_then(Weak::upgrade)
257 };
258 if let Some(refresh) = refresh {
259 refresh.refresh();
260 }
261 }
262
263 pub(crate) fn stats(&self) -> (usize, usize) {
264 let inner = self.inner.borrow();
265 (inner.cells.len(), inner.free.len())
266 }
267
268 pub(crate) fn debug_stats(&self) -> StateArenaDebugStats {
269 let inner = self.inner.borrow();
270 StateArenaDebugStats {
271 cells_len: inner.cells.len(),
272 cells_cap: inner.cells.capacity(),
273 free_len: inner.free.len(),
274 free_cap: inner.free.capacity(),
275 }
276 }
277
278 pub(crate) fn unregister_scope(&self, id: StateId, scope_id: ScopeId) {
279 if let Some(watcher_cell) = self.watcher_cell(id) {
280 watcher_cell.unregister_scope(scope_id);
281 }
282 }
283
284 pub(crate) fn forget_scope(&self, id: StateId, scope_id: ScopeId) {
286 if let Some(watcher_cell) = self.watcher_cell(id) {
287 watcher_cell.forget_scope(scope_id);
288 }
289 }
290
291 pub(crate) fn invalidate_watchers(&self, id: StateId) {
293 if let Some(watcher_cell) = self.watcher_cell(id) {
294 watcher_cell.invalidate_watchers();
295 }
296 }
297
298 fn watcher_cell(&self, id: StateId) -> Option<Rc<dyn ScopeWatchCell>> {
299 let inner = self.inner.borrow();
300 inner
301 .cells
302 .get(id.slot_index())
303 .filter(|slot| slot.generation == id.generation())
304 .and_then(|slot| slot.watcher_cell.as_ref())
305 .cloned()
306 }
307
308 pub(crate) fn register_lease(&self, id: StateId, lease: &Rc<StateHandleLease>) {
309 let mut inner = self.inner.borrow_mut();
310 let Some(slot) = inner.cells.get_mut(id.slot_index()) else {
311 return;
312 };
313 if slot.generation != id.generation() {
314 return;
315 }
316 slot.lease = Some(Rc::downgrade(lease));
317 }
318
319 pub(crate) fn retain_lease(&self, id: StateId) -> Option<Rc<StateHandleLease>> {
320 let inner = self.inner.borrow();
321 let slot = inner.cells.get(id.slot_index())?;
322 if slot.generation != id.generation() {
323 return None;
324 }
325 slot.lease.as_ref()?.upgrade()
326 }
327}
328
329#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
331pub struct StateId {
332 slot: u32,
333 generation: u32,
334}
335
336impl StateId {
337 const fn new(slot: u32, generation: u32) -> Self {
338 Self { slot, generation }
339 }
340
341 pub(crate) const fn slot(self) -> u32 {
342 self.slot
343 }
344
345 pub(crate) const fn slot_index(self) -> usize {
346 self.slot as usize
347 }
348
349 pub(crate) const fn generation(self) -> u32 {
350 self.generation
351 }
352}
353
354#[cfg(test)]
355#[path = "tests/state_arena_tests.rs"]
356mod tests;