1use super::*;
3use std::any::TypeId;
4use std::borrow::Cow;
5use std::cell::Cell;
6use std::mem::size_of;
7#[path = "sparse.rs"]
8mod sparse;
9use sparse::SparseMap;
10#[path = "entries.rs"]
11mod entries;
12use entries::{EntryIndex, EntryKey};
13#[path = "collections.rs"]
14mod collections;
15
16thread_local! { static PROJECTING: Cell<bool> = const { Cell::new(false) }; }
17pub(super) fn allow_read() -> Result<(), AccessError> {
18 if PROJECTING.get() {
19 Err(AccessError::InvalidField(
20 "reactive reads inside a field accessor",
21 ))
22 } else {
23 Ok(())
24 }
25}
26pub(super) fn project<R>(f: impl FnOnce() -> Result<R, AccessError>) -> Result<R, AccessError> {
27 struct Guard {
28 previous: bool,
29 mode: usize,
30 }
31 impl Drop for Guard {
32 fn drop(&mut self) {
33 PROJECTING.set(self.previous);
34 EVALUATING.with_borrow_mut(|stack| stack.truncate(self.mode));
35 }
36 }
37 let previous = PROJECTING.replace(true);
38 let mode = EVALUATING.with_borrow_mut(|stack| {
39 let n = stack.len();
40 stack.push(Mode::Pure);
41 n
42 });
43 let _guard = Guard { previous, mode };
44 f()
45}
46
47#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
48struct FieldId(Key);
49#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
50enum Parent {
51 Root(Key),
52 Field(FieldId),
53}
54#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
55enum Segment {
56 Field(Cow<'static, str>),
57 Item(usize),
58 Entry(u64),
59}
60#[derive(Clone, Copy, PartialEq, Eq)]
61struct Layout {
62 offset: usize,
63 size: usize,
64}
65trait Projection {
66 fn read<'a>(&self, value: &'a dyn Any) -> Result<&'a dyn Any, AccessError>;
67 fn write<'a>(&self, value: &'a mut dyn Any) -> Result<&'a mut dyn Any, AccessError>;
68}
69struct Map<T, U, G, M> {
70 parent: Option<Rc<dyn Projection>>,
71 get: G,
72 get_mut: M,
73 offset: usize,
74 types: PhantomData<fn(T) -> U>,
75}
76impl<T: 'static, U: 'static, G, M> Projection for Map<T, U, G, M>
77where
78 G: for<'a> Fn(&'a T) -> &'a U,
79 M: for<'a> Fn(&'a mut T) -> &'a mut U,
80{
81 fn read<'a>(&self, value: &'a dyn Any) -> Result<&'a dyn Any, AccessError> {
82 let value = if let Some(parent) = &self.parent {
83 parent.read(value)?
84 } else {
85 value
86 };
87 let value = value.downcast_ref::<T>().ok_or(AccessError::TypeMismatch)?;
88 let selected = (self.get)(value);
89 if offset(value, selected)? != self.offset {
90 return Err(AccessError::InvalidField(
91 "field accessor changed its location",
92 ));
93 }
94 Ok(selected)
95 }
96 fn write<'a>(&self, value: &'a mut dyn Any) -> Result<&'a mut dyn Any, AccessError> {
97 let value = if let Some(parent) = &self.parent {
98 parent.write(value)?
99 } else {
100 value
101 };
102 let value = value.downcast_mut::<T>().ok_or(AccessError::TypeMismatch)?;
103 let start = std::ptr::from_ref(value) as usize;
104 let selected = (self.get_mut)(value);
105 let actual = (std::ptr::from_ref(selected) as usize).checked_sub(start);
106 if actual != Some(self.offset) {
107 return Err(AccessError::InvalidField(
108 "mutable accessor selects another field",
109 ));
110 }
111 Ok(selected)
112 }
113}
114fn offset<T, U>(parent: &T, child: &U) -> Result<usize, AccessError> {
115 let relative = (std::ptr::from_ref(child) as usize)
116 .checked_sub(std::ptr::from_ref(parent) as usize)
117 .ok_or(AccessError::InvalidField(
118 "field is outside its inline parent",
119 ))?;
120 if relative
121 .checked_add(size_of::<U>())
122 .is_none_or(|end| end > size_of::<T>())
123 {
124 return Err(AccessError::InvalidField(
125 "field is outside its inline parent",
126 ));
127 }
128 Ok(relative)
129}
130pub(super) struct FieldData {
131 parent: Parent,
132 root: Key,
133 segment: Segment,
134 output: TypeId,
135 layout: Option<Layout>,
136 depth: usize,
137 projection: Rc<dyn Projection>,
138 children: SparseMap<Segment, FieldId>,
139 aliases: SparseMap<Key, Key>,
141 _entry: Option<Rc<EntryKey>>,
142}
143#[derive(Default)]
144pub(super) struct Fields {
145 roots: BTreeMap<Key, SparseMap<Segment, FieldId>>,
146 slots: Arena<FieldData>,
147 aliases: BTreeMap<Key, FieldId>,
148 indices: BTreeMap<Parent, Rc<EntryIndex>>,
149 targets: BTreeMap<Key, Box<CachedTarget>>,
150}
151#[derive(Default)]
152pub(super) struct Removal {
153 pub aliases: Vec<Key>,
154 pub fields: Vec<FieldData>,
155}
156pub(super) struct ValuePath {
157 pub value: Value,
158 root: Key,
159 projection: Option<Rc<dyn Projection>>,
160}
161impl ValuePath {
162 pub fn read<'a>(&self, value: &'a dyn Any) -> Result<&'a dyn Any, AccessError> {
163 self.projection
164 .as_ref()
165 .map_or(Ok(value), |p| project(|| p.read(value)))
166 }
167 pub fn write<'a>(&self, value: &'a mut dyn Any) -> Result<&'a mut dyn Any, AccessError> {
168 if let Some(p) = &self.projection {
169 project(|| p.write(value))
170 } else {
171 Ok(value)
172 }
173 }
174}
175struct WriteTarget {
176 root: Key,
177 at: Target,
178 nodes: Vec<Key>,
179 pending: Vec<FieldId>,
180}
181#[derive(Clone, Copy, PartialEq, Eq)]
182enum Target {
183 Root,
184 Field(FieldId),
185 Collection,
186}
187#[derive(Clone, Copy, PartialEq, Eq)]
188struct CollectionTarget {
189 parent: Parent,
190 selection: Selection,
191}
192#[derive(Clone, Copy, PartialEq, Eq)]
195enum Selection {
196 Entry(Option<u64>),
197 Items { start: usize, end: usize },
198}
199#[derive(Default)]
200struct CachedTarget {
201 buffer: Option<WriteTarget>,
202 keys: usize,
203 collection: Option<Box<CollectionTarget>>,
206}
207impl Fields {
208 pub fn target_stats(&self) -> (usize, usize) {
209 (
210 self.targets.len(),
211 self.targets.values().map(|target| target.keys).sum(),
212 )
213 }
214 fn invalidate_target(&mut self, root: Key) {
215 self.targets.remove(&root);
219 }
220 pub fn entry_stats(&self) -> (usize, usize) {
221 self.indices
222 .values()
223 .map(|index| index.stats())
224 .fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1))
225 }
226 pub fn has_root(&self, key: Key) -> bool {
227 self.roots.contains_key(&key)
228 }
229 pub fn len(&self) -> usize {
230 self.slots.len()
231 }
232 pub fn capacity(&self) -> usize {
233 self.slots.capacity()
234 }
235 fn children(&self, parent: Parent) -> Option<&SparseMap<Segment, FieldId>> {
236 match parent {
237 Parent::Root(root) => self.roots.get(&root),
238 Parent::Field(id) => self.slots.get(id.0).map(|f| &f.children),
239 }
240 }
241 fn selected(
242 &self,
243 parent: Parent,
244 selection: Selection,
245 ) -> Option<sparse::Range<'_, Segment, FieldId>> {
246 use std::ops::Bound::{Excluded, Included};
247 let bounds = match selection {
248 Selection::Entry(Some(id)) => {
249 (Included(Segment::Entry(id)), Included(Segment::Entry(id)))
250 }
251 Selection::Entry(None) => return None,
252 Selection::Items { start, end } => {
253 (Included(Segment::Item(start)), Excluded(Segment::Item(end)))
254 }
255 };
256 self.children(parent).map(|children| children.range(bounds))
257 }
258 fn unlink(&mut self, parent: Parent, segment: &Segment) {
259 let empty = match parent {
260 Parent::Root(root) => self.roots.get_mut(&root).is_some_and(|children| {
261 children.remove(segment);
262 children.is_empty()
263 }),
264 Parent::Field(id) => self.slots.get_mut(id.0).is_some_and(|field| {
265 field.children.remove(segment);
266 field.children.is_empty()
267 }),
268 };
269 if empty {
270 self.indices.remove(&parent);
271 if let Parent::Root(root) = parent {
272 self.roots.remove(&root);
273 }
274 }
275 }
276 pub fn detach(&mut self, node: Key, owner: Key) -> Removal {
277 let mut removal = Removal::default();
278 if let Some(mut id) = self.aliases.remove(&node) {
279 if let Some(field) = self.slots.get(id.0) {
280 self.invalidate_target(field.root);
281 }
282 if let Some(field) = self.slots.get_mut(id.0) {
283 field.aliases.remove(&owner);
284 }
285 while let Some(field) = self.slots.get(id.0) {
286 if !field.aliases.is_empty() || !field.children.is_empty() {
287 break;
288 }
289 let field = self.slots.remove(id.0).expect("live field");
290 self.indices.remove(&Parent::Field(id));
291 self.unlink(field.parent, &field.segment);
292 match field.parent {
293 Parent::Root(_) => {
294 removal.fields.push(field);
295 break;
296 }
297 Parent::Field(parent) => {
298 removal.fields.push(field);
299 id = parent;
300 }
301 }
302 }
303 }
304 self.indices.remove(&Parent::Root(node));
305 if let Some(roots) = self.roots.remove(&node) {
306 self.invalidate_target(node);
307 let mut pending: Vec<_> = roots.into_values().collect();
308 while let Some(id) = pending.pop() {
309 if let Some(field) = self.slots.remove(id.0) {
310 self.indices.remove(&Parent::Field(id));
311 pending.extend(field.children.values().copied());
312 for alias in field.aliases.values() {
313 self.aliases.remove(alias);
314 removal.aliases.push(*alias);
315 }
316 removal.fields.push(field);
317 }
318 }
319 }
320 removal
321 }
322}
323impl State {
324 pub(super) fn value_path(&self, key: Key, node: &Node) -> Result<ValuePath, AccessError> {
325 if let Some(value) = &node.value {
326 return Ok(ValuePath {
327 value: value.clone(),
328 root: key,
329 projection: None,
330 });
331 }
332 let id = *self
333 .fields
334 .aliases
335 .get(&key)
336 .ok_or(AccessError::TypeMismatch)?;
337 self.field_path(id)
338 }
339 fn field_path(&self, id: FieldId) -> Result<ValuePath, AccessError> {
340 let field = self.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
341 let value = self
342 .nodes
343 .get(field.root)
344 .and_then(|n| n.value.clone())
345 .ok_or(AccessError::Disposed)?;
346 Ok(ValuePath {
347 value,
348 root: field.root,
349 projection: Some(field.projection.clone()),
350 })
351 }
352 pub(super) fn advance_source(&mut self, key: Key) {
353 let Some(node) = self.nodes.get_mut(key) else {
354 return;
355 };
356 node.version = node
357 .version
358 .checked_add(1)
359 .expect("source version exhausted");
360 if node.propagated {
361 return;
362 }
363 node.propagated = true;
364 let subscribers: Vec<_> = node.subscribers.iter().copied().collect();
365 self.invalidate(subscribers);
366 }
367 fn write_target(&mut self, root: Key, at: Target) -> Result<WriteTarget, AccessError> {
368 debug_assert!(!matches!(at, Target::Collection));
369 let cached = self
370 .fields
371 .targets
372 .get(&root)
373 .and_then(|slot| slot.buffer.as_ref());
374 let hit = cached.is_some_and(|target| target.at == at);
375 let mut check = |key| {
378 if let Some(node) = self.nodes.get(key) {
379 node.version
380 .checked_add(1)
381 .expect("source version exhausted");
382 }
383 };
384 if let Some(target) = cached.filter(|_| hit) {
385 for key in &target.nodes {
386 check(*key);
387 }
388 } else {
389 check(root);
390 if let Target::Field(id) = at {
391 let field = self.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
392 let mut parent = field.parent;
393 while let Parent::Field(id) = parent {
394 let field = self.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
395 for key in field.aliases.values() {
396 check(*key);
397 }
398 parent = field.parent;
399 }
400 self.visit_target(id, &mut check)?;
401 } else {
402 let children = self
403 .fields
404 .roots
405 .get(&root)
406 .ok_or(AccessError::InvalidField("source has no registered field"))?;
407 for id in children.values() {
408 self.visit_target(*id, &mut check)?;
409 }
410 }
411 }
412 let mut target = self
413 .fields
414 .targets
415 .get_mut(&root)
416 .and_then(|slot| slot.buffer.take())
417 .unwrap_or_else(|| WriteTarget {
418 root,
419 at,
420 nodes: Vec::new(),
421 pending: Vec::new(),
422 });
423 if hit {
424 self.stats.field_target_hits += 1;
425 } else {
426 self.collect_target(root, at, &mut target);
427 self.stats.field_target_builds += 1;
428 self.stats.field_target_visits += target.nodes.len() as u64;
429 }
430 self.fields.targets.entry(root).or_default().keys = target.nodes.len();
433 Ok(target)
434 }
435 fn write_collection_target(
436 &mut self,
437 root: Key,
438 parent: Parent,
439 selection: Selection,
440 ) -> Result<WriteTarget, AccessError> {
441 let selector = CollectionTarget { parent, selection };
442 let slot = self.fields.targets.get(&root);
443 let cached = slot.and_then(|slot| slot.buffer.as_ref());
444 let hit = cached.is_some_and(|target| target.at == Target::Collection)
445 && slot.and_then(|slot| slot.collection.as_deref()) == Some(&selector);
446 let mut check = |key| {
449 if let Some(node) = self.nodes.get(key) {
450 node.version
451 .checked_add(1)
452 .expect("source version exhausted");
453 }
454 };
455 if let Some(target) = cached.filter(|_| hit) {
456 for key in &target.nodes {
457 check(*key);
458 }
459 } else {
460 check(root);
461 let mut ancestor = parent;
462 while let Parent::Field(id) = ancestor {
463 let field = self.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
464 for key in field.aliases.values() {
465 check(*key);
466 }
467 ancestor = field.parent;
468 }
469 for (_, id) in self
470 .fields
471 .selected(parent, selection)
472 .into_iter()
473 .flatten()
474 {
475 self.visit_target(*id, &mut check)?;
476 }
477 }
478 let mut target = self
479 .fields
480 .targets
481 .get_mut(&root)
482 .and_then(|slot| slot.buffer.take())
483 .unwrap_or_else(|| WriteTarget {
484 root,
485 at: Target::Collection,
486 nodes: Vec::new(),
487 pending: Vec::new(),
488 });
489 if hit {
490 self.stats.field_target_hits += 1;
491 } else {
492 target.root = root;
493 target.at = Target::Collection;
494 target.nodes.clear();
495 target.pending.clear();
496 target.nodes.push(root);
497 let mut ancestor = parent;
498 while let Parent::Field(id) = ancestor {
499 let field = self.fields.slots.get(id.0).expect("prechecked ancestor");
500 target.nodes.extend(field.aliases.values().copied());
501 ancestor = field.parent;
502 }
503 target.pending.extend(
504 self.fields
505 .selected(parent, selection)
506 .into_iter()
507 .flatten()
508 .map(|(_, id)| *id),
509 );
510 while let Some(id) = target.pending.pop() {
511 let field = self.fields.slots.get(id.0).expect("prechecked descendant");
512 target.nodes.extend(field.aliases.values().copied());
513 target.pending.extend(field.children.values().copied());
514 }
515 self.stats.field_target_builds += 1;
516 self.stats.field_target_visits += target.nodes.len() as u64;
517 }
518 let slot = self.fields.targets.entry(root).or_default();
519 slot.keys = target.nodes.len();
520 if !hit {
521 if let Some(previous) = &mut slot.collection {
522 **previous = selector;
523 } else {
524 slot.collection = Some(Box::new(selector));
525 }
526 }
527 Ok(target)
528 }
529 fn visit_target(&self, id: FieldId, visit: &mut impl FnMut(Key)) -> Result<(), AccessError> {
530 let field = self.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
531 for key in field.aliases.values() {
532 visit(*key);
533 }
534 for child in field.children.values() {
536 self.visit_target(*child, visit)?;
537 }
538 Ok(())
539 }
540 fn collect_target(&self, root: Key, at: Target, target: &mut WriteTarget) {
541 target.root = root;
542 target.at = at;
543 target.nodes.clear();
544 target.pending.clear();
545 target.nodes.push(root);
546 if let Target::Field(id) = at {
547 let field = self.fields.slots.get(id.0).expect("prechecked field");
548 let mut parent = field.parent;
549 while let Parent::Field(id) = parent {
550 let field = self.fields.slots.get(id.0).expect("prechecked ancestor");
551 target.nodes.extend(field.aliases.values().copied());
552 parent = field.parent;
553 }
554 target.pending.push(id);
555 } else {
556 target.pending.extend(
557 self.fields
558 .roots
559 .get(&root)
560 .expect("prechecked root")
561 .values()
562 .copied(),
563 );
564 }
565 while let Some(id) = target.pending.pop() {
566 let field = self.fields.slots.get(id.0).expect("prechecked descendant");
567 target.nodes.extend(field.aliases.values().copied());
568 target.pending.extend(field.children.values().copied());
569 }
570 }
571}
572
573struct Write {
574 state: Shared,
575 target: Option<WriteTarget>,
576}
577impl Drop for Write {
578 fn drop(&mut self) {
579 let target = self.target.take().expect("one write guard");
580 let host = {
581 let mut state = self.state.borrow_mut();
582 if state.nodes.get(target.root).is_some() {
583 state.stats.source_writes += 1;
584 for key in &target.nodes {
585 state.advance_source(*key);
586 }
587 }
588 let host = state.host.clone();
589 if let Some(slot) = state.fields.targets.get_mut(&target.root) {
590 slot.buffer = Some(target);
591 }
592 host
593 };
594 if let Some(host) = host {
595 host.wake();
596 }
597 }
598}
599pub(super) fn revise<T: 'static, R>(
602 state: Shared,
603 key: Key,
604 f: impl FnOnce(&mut T) -> R,
605) -> Result<R, AccessError> {
606 let (path, at) = {
607 let state = state.borrow();
608 let node = state.nodes.get(key).ok_or(AccessError::Disposed)?;
609 let (path, at) = if node.value.is_some() {
610 (state.value_path(key, node)?, Target::Root)
611 } else {
612 let id = *state
613 .fields
614 .aliases
615 .get(&key)
616 .ok_or(AccessError::TypeMismatch)?;
617 (state.field_path(id)?, Target::Field(id))
618 };
619 (path, at)
620 };
621 let mut borrowed = path
622 .value
623 .try_borrow_mut()
624 .map_err(|_| AccessError::Borrowed)?;
625 let value = path
626 .write(borrowed.as_mut())?
627 .downcast_mut()
628 .ok_or(AccessError::TypeMismatch)?;
629 let target = state.borrow_mut().write_target(path.root, at)?;
630 let write = Write {
631 state,
632 target: Some(target),
633 };
634 let result = f(value);
635 drop(borrowed);
636 drop(write);
637 Ok(result)
638}
639
640impl<T> Cage<T> {
641 pub fn field<U: 'static>(
662 self,
663 name: impl Into<Cow<'static, str>>,
664 get: impl for<'a> Fn(&'a T) -> &'a U + 'static,
665 get_mut: impl for<'a> Fn(&'a mut T) -> &'a mut U + 'static,
666 ) -> Cage<U> {
667 self.try_field(name, get, get_mut)
668 .expect("create a pure, disjoint inline field on a live Cage")
669 }
670 pub fn try_field<U: 'static>(
671 self,
672 name: impl Into<Cow<'static, str>>,
673 get: impl for<'a> Fn(&'a T) -> &'a U + 'static,
674 get_mut: impl for<'a> Fn(&'a mut T) -> &'a mut U + 'static,
675 ) -> Result<Cage<U>, AccessError> {
676 allow_creation()?;
677 let name = name.into();
678 if name.is_empty() {
679 return Err(AccessError::InvalidField("empty field name"));
680 }
681 let context = Context::new(self.handle.runtime, self.handle.key)?;
682 inline(context, name, get, get_mut)
683 }
684}
685
686fn inline<T: 'static, U: 'static>(
687 context: Context,
688 name: Cow<'static, str>,
689 get: impl for<'a> Fn(&'a T) -> &'a U + 'static,
690 get_mut: impl for<'a> Fn(&'a mut T) -> &'a mut U + 'static,
691) -> Result<Cage<U>, AccessError> {
692 if name.is_empty() {
693 return Err(AccessError::InvalidField("empty field name"));
694 }
695 let selected_offset = {
696 let borrowed = context
697 .path
698 .value
699 .try_borrow()
700 .map_err(|_| AccessError::Borrowed)?;
701 project(|| {
702 let parent = context
703 .path
704 .read(borrowed.as_ref())?
705 .downcast_ref::<T>()
706 .ok_or(AccessError::TypeMismatch)?;
707 offset(parent, get(parent))
708 })?
709 };
710 let parent = context.path.projection.clone();
711 context.register(
712 Segment::Field(name),
713 Some(Layout {
714 offset: selected_offset,
715 size: size_of::<U>(),
716 }),
717 move || {
718 Rc::new(Map::<T, U, _, _> {
719 parent,
720 get,
721 get_mut,
722 offset: selected_offset,
723 types: PhantomData,
724 }) as Rc<dyn Projection>
725 },
726 None,
727 )
728}
729struct PathGuard {
730 state: Shared,
731 id: FieldId,
732}
733impl Drop for PathGuard {
734 fn drop(&mut self) {
735 let removed = {
736 let mut graph = self.state.borrow_mut();
737 let mut removed = Vec::new();
738 let mut id = self.id;
739 while let Some(field) = graph.fields.slots.get(id.0) {
740 if !field.aliases.is_empty() || !field.children.is_empty() {
741 break;
742 }
743 let field = graph.fields.slots.remove(id.0).expect("live path");
744 graph.fields.invalidate_target(field.root);
745 graph.fields.indices.remove(&Parent::Field(id));
746 graph.fields.unlink(field.parent, &field.segment);
747 let parent = field.parent;
748 removed.push(field);
749 match parent {
750 Parent::Field(next) => id = next,
751 Parent::Root(_) => break,
752 }
753 }
754 removed
755 };
756 drop(removed);
757 }
758}
759pub(super) fn keyed_field<T: 'static, U: 'static>(
760 source: Cage<Arena<T>>,
761 key: u64,
762 name: impl Into<Cow<'static, str>>,
763 get: impl for<'a> Fn(&'a T) -> &'a U + 'static,
764 get_mut: impl for<'a> Fn(&'a mut T) -> &'a mut U + 'static,
765) -> Result<Cage<U>, AccessError> {
766 let (context, _guard) = entries::keyed_context(source, key)?;
767 inline(context, name.into(), get, get_mut)
768}
769pub(super) fn update_member<T: 'static, R>(
770 source: Cage<Arena<T>>,
771 id: u64,
772 edit: impl FnOnce(&mut T) -> R,
773) -> Result<R, AccessError> {
774 collections::update_member(source, id, edit)
775}
776pub(super) fn append_members<T: 'static, R>(
777 source: Cage<Arena<T>>,
778 edit: impl FnOnce(&mut Arena<T>) -> R,
779) -> Result<R, AccessError> {
780 collections::append_members(source, edit)
781}
782pub(super) fn remove_member<T: 'static>(
783 source: Cage<Arena<T>>,
784 id: u64,
785) -> Result<Option<T>, AccessError> {
786 collections::remove_member(source, id)
787}
788
789struct Context {
790 state: Shared,
791 runtime: RuntimeId,
792 source: Key,
793 owner: Key,
794 parent: Parent,
795 depth: usize,
796 path: ValuePath,
797}
798impl Context {
799 fn new(runtime: RuntimeId, key: Key) -> Result<Self, AccessError> {
800 allow_creation()?;
801 let state = lookup(runtime)?;
802 let (path, source_owner, parent, depth) = {
803 let graph = state.borrow();
804 let source = graph.nodes.get(key).ok_or(AccessError::Disposed)?;
805 let field = graph.fields.aliases.get(&key).copied();
806 let depth = field
807 .and_then(|id| graph.fields.slots.get(id.0))
808 .map_or(1, |f| f.depth + 1);
809 (
810 graph.value_path(key, source)?,
811 source.owner,
812 field.map_or(Parent::Root(key), Parent::Field),
813 depth,
814 )
815 };
816 if depth > 128 {
817 return Err(AccessError::InvalidField("field nesting exceeds 128"));
818 }
819 drop(path.value.try_borrow().map_err(|_| AccessError::Borrowed)?);
822 let owner = CONSTRUCTING.with_borrow(|stack| {
823 stack
824 .last()
825 .filter(|(r, _)| *r == runtime)
826 .map(|(_, owner)| *owner)
827 .unwrap_or(source_owner)
828 });
829 Ok(Self {
830 state,
831 runtime,
832 source: key,
833 owner,
834 parent,
835 depth,
836 path,
837 })
838 }
839 fn register<U: 'static>(
840 self,
841 segment: Segment,
842 layout: Option<Layout>,
843 projection: impl FnOnce() -> Rc<dyn Projection>,
844 entry: Option<(Rc<EntryKey>, Rc<EntryIndex>)>,
845 ) -> Result<Cage<U>, AccessError> {
846 let id = self.canonical::<U>(segment, layout, projection, entry)?;
847 self.alias(id)
848 }
849 fn canonical<U: 'static>(
850 &self,
851 segment: Segment,
852 layout: Option<Layout>,
853 projection: impl FnOnce() -> Rc<dyn Projection>,
854 entry: Option<(Rc<EntryKey>, Rc<EntryIndex>)>,
855 ) -> Result<FieldId, AccessError> {
856 let mut graph = self.state.borrow_mut();
857 let (owner, parent) = (self.owner, self.parent);
858 if graph.owners.get(owner).is_none() || graph.nodes.get(self.source).is_none() {
859 return Err(AccessError::Disposed);
860 }
861 if let Some((_, index)) = &entry
862 && graph
863 .fields
864 .indices
865 .get(&parent)
866 .is_some_and(|existing| !Rc::ptr_eq(existing, index))
867 {
868 return Err(AccessError::InvalidField(
869 "collection path changed during key comparison",
870 ));
871 }
872 let existing = graph
873 .fields
874 .children(parent)
875 .and_then(|children| children.get(&segment))
876 .copied();
877 let id = if let Some(id) = existing {
878 let field = graph.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
879 if field.output != TypeId::of::<U>() {
880 return Err(AccessError::TypeMismatch);
881 }
882 if field.layout != layout {
883 return Err(AccessError::InvalidField("same name selects another field"));
884 }
885 id
886 } else {
887 if let Some(siblings) = graph.fields.children(parent) {
888 if let Some(first) = siblings.values().next() {
892 let first = graph
893 .fields
894 .slots
895 .get(first.0)
896 .ok_or(AccessError::Disposed)?;
897 if first.layout.is_some() != layout.is_some() {
898 return Err(AccessError::InvalidField(
899 "inline and collection siblings overlap; use a common parent",
900 ));
901 }
902 }
903 if let Some(b) = layout {
904 for id in siblings.values() {
905 let a = graph
906 .fields
907 .slots
908 .get(id.0)
909 .ok_or(AccessError::Disposed)?
910 .layout
911 .expect("inline siblings");
912 if a.size != 0
913 && b.size != 0
914 && b.offset < a.offset + a.size
915 && a.offset < b.offset + b.size
916 {
917 return Err(AccessError::InvalidField("overlapping sibling fields"));
918 }
919 }
920 }
921 }
922 let id = FieldId(graph.fields.slots.insert(FieldData {
923 parent,
924 root: self.path.root,
925 segment: segment.clone(),
926 output: TypeId::of::<U>(),
927 layout,
928 depth: self.depth,
929 projection: projection(),
932 children: SparseMap::default(),
933 aliases: SparseMap::default(),
934 _entry: entry.as_ref().map(|(key, _)| key.clone()),
935 }));
936 if let Some((_, index)) = &entry {
937 graph
938 .fields
939 .indices
940 .entry(parent)
941 .or_insert_with(|| index.clone());
942 }
943 match parent {
944 Parent::Root(root) => {
945 graph
946 .fields
947 .roots
948 .entry(root)
949 .or_default()
950 .insert(segment, id);
951 }
952 Parent::Field(parent) => {
953 graph
954 .fields
955 .slots
956 .get_mut(parent.0)
957 .expect("live parent")
958 .children
959 .insert(segment, id);
960 }
961 }
962 id
963 };
964 Ok(id)
965 }
966 fn alias<U: 'static>(&self, id: FieldId) -> Result<Cage<U>, AccessError> {
967 let mut graph = self.state.borrow_mut();
968 let owner = self.owner;
969 if graph.owners.get(owner).is_none() || graph.nodes.get(self.source).is_none() {
970 return Err(AccessError::Disposed);
971 }
972 if let Some(key) = graph
973 .fields
974 .slots
975 .get(id.0)
976 .ok_or(AccessError::Disposed)?
977 .aliases
978 .get(&owner)
979 {
980 return Ok(Cage {
981 handle: Handle::new(self.runtime, *key),
982 });
983 }
984 let node = Node {
985 owner,
986 compute: Compute::Source,
987 value: None,
988 version: 1,
989 status: Status::Clean,
990 rerun: false,
991 propagated: false,
992 queued: false,
993 last_flush: 0,
994 flush_runs: 0,
995 dependencies: Dependencies::new(),
996 subscribers: Subscribers::new(),
997 };
998 let key = graph.insert_node(owner, node)?;
999 graph.fields.aliases.insert(key, id);
1000 graph
1001 .fields
1002 .slots
1003 .get_mut(id.0)
1004 .expect("live field")
1005 .aliases
1006 .insert(owner, key);
1007 graph.fields.invalidate_target(self.path.root);
1008 drop(graph);
1009 Ok(Cage {
1010 handle: Handle::new(self.runtime, key),
1011 })
1012 }
1013}
1014
1015#[cfg(test)]
1016mod cache_tests {
1017 use super::*;
1018 #[test]
1019 fn collection_targets_precheck_selected_versions_and_ignore_unchanged_positions() {
1020 let runtime = Runtime::new();
1021 let owner = runtime.owner();
1022 let rows = owner.cage(vec![0usize]);
1023 let first = rows.item(0);
1024 let last = rows.item(1);
1025 runtime
1026 .state
1027 .borrow_mut()
1028 .nodes
1029 .get_mut(first.handle.key)
1030 .unwrap()
1031 .version = u64::MAX;
1032 rows.push(1); assert_eq!(rows.with(Vec::len), 2);
1034 runtime
1035 .state
1036 .borrow_mut()
1037 .nodes
1038 .get_mut(last.handle.key)
1039 .unwrap()
1040 .version = u64::MAX;
1041 let before = runtime.stats();
1042 assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rows.pop())).is_err());
1043 assert_eq!(rows.with(Vec::len), 2);
1044 assert_eq!(runtime.stats(), before);
1045 runtime
1046 .state
1047 .borrow_mut()
1048 .nodes
1049 .get_mut(last.handle.key)
1050 .unwrap()
1051 .version = 1;
1052 rows.pop();
1053 runtime
1054 .state
1055 .borrow_mut()
1056 .nodes
1057 .get_mut(rows.handle.key)
1058 .unwrap()
1059 .version = u64::MAX;
1060 let before = runtime.stats();
1061 assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rows.push(2))).is_err());
1062 assert_eq!(rows.with(Vec::len), 1);
1063 assert_eq!(runtime.stats(), before);
1064 }
1065 #[test]
1066 fn cached_targets_still_precheck_every_source_version() {
1067 let runtime = Runtime::new();
1068 let owner = runtime.owner();
1069 let source = owner.cage((0usize,));
1070 let field = source.field("value", |m| &m.0, |m| &mut m.0);
1071 field.revise(|v| *v = 1);
1072 runtime
1073 .state
1074 .borrow_mut()
1075 .nodes
1076 .get_mut(source.handle.key)
1077 .unwrap()
1078 .version = u64::MAX;
1079 let before = runtime.stats();
1080 let called = Cell::new(false);
1081 assert!(
1082 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| field.revise(|v| {
1083 called.set(true);
1084 *v = 2;
1085 })))
1086 .is_err()
1087 );
1088 assert!(!called.get());
1089 assert_eq!(field.get(), 1);
1090 assert_eq!(runtime.stats(), before);
1091 runtime
1092 .state
1093 .borrow_mut()
1094 .nodes
1095 .get_mut(source.handle.key)
1096 .unwrap()
1097 .version = 1;
1098 field.revise(|v| *v = 2);
1099 assert_eq!(
1100 runtime.stats().field_target_hits,
1101 before.field_target_hits + 1
1102 );
1103 }
1104 #[test]
1105 fn borrowed_buffers_return_only_while_their_root_slot_survives() {
1106 let runtime = Runtime::new();
1107 let owner = runtime.owner();
1108 let source = owner.cage((0usize,));
1109 let field = source.field("value", |m| &m.0, |m| &mut m.0);
1110 let row = runtime.owner();
1111 let second = row.enter(|| source.field("value", |m| &m.0, |m| &mut m.0));
1112 let other = owner.cage((0usize,));
1113 second.revise(|v| {
1114 assert!(
1115 runtime.state.borrow().fields.targets[&source.handle.key]
1116 .buffer
1117 .is_none()
1118 );
1119 other
1120 .field("other", |m| &m.0, |m| &mut m.0)
1121 .revise(|n| *n = 1);
1122 assert!(
1123 runtime.state.borrow().fields.targets[&source.handle.key]
1124 .buffer
1125 .is_none()
1126 );
1127 *v = 1;
1128 });
1129 assert_eq!(runtime.stats().field_target_caches, 2);
1130 second.revise(|v| {
1131 drop(row);
1132 *v = 2;
1133 });
1134 assert_eq!(field.get(), 2);
1135 assert!(
1136 !runtime
1137 .state
1138 .borrow()
1139 .fields
1140 .targets
1141 .contains_key(&source.handle.key)
1142 );
1143 assert_eq!(runtime.stats().field_target_caches, 1);
1144 field.revise(|v| *v = 3);
1145 assert_eq!(runtime.stats().field_target_caches, 2);
1146 }
1147 #[test]
1148 fn alternating_selections_reuse_buffers_with_space_bounded_by_live_schema() {
1149 let runtime = Runtime::new();
1150 let owner = runtime.owner();
1151 let source = owner.cage([0usize; 64]);
1152 let mut owners: Vec<_> = (0..64).map(|_| Some(runtime.owner())).collect();
1153 let fields: Vec<_> = (0..64)
1154 .map(|i| {
1155 owners[i]
1156 .as_ref()
1157 .unwrap()
1158 .enter(|| source.field(format!("{i}"), move |m| &m[i], move |m| &mut m[i]))
1159 })
1160 .collect();
1161 source.revise(|m| m.fill(0));
1162 let buffers = || {
1163 let state = runtime.state.borrow();
1164 let buffer = state.fields.targets[&source.handle.key]
1165 .buffer
1166 .as_ref()
1167 .unwrap();
1168 assert!(buffer.pending.is_empty());
1169 assert!(buffer.nodes.capacity() <= 2 * (state.fields.aliases.len() + 1));
1170 assert!(buffer.pending.capacity() <= 2 * state.fields.len());
1171 (buffer.nodes.as_ptr(), buffer.pending.as_ptr())
1172 };
1173 let initial = buffers();
1174 for i in 0..1000 {
1175 fields[i % 64].revise(|v| *v += 1);
1176 assert_eq!(buffers(), initial);
1177 assert_eq!(
1178 (
1179 runtime.stats().field_target_caches,
1180 runtime.stats().field_target_keys
1181 ),
1182 (1, 2)
1183 );
1184 }
1185 assert_eq!(source.with(|m| m.iter().sum::<usize>()), 1000);
1186 drop(owners[0].take());
1187 assert_eq!(
1188 (
1189 runtime.stats().field_target_caches,
1190 runtime.stats().field_target_keys
1191 ),
1192 (0, 0)
1193 );
1194 }
1195}