vertigo/computed/
context.rs1use std::any::Any;
2use std::collections::BTreeSet;
3use std::rc::Rc;
4
5use super::{struct_mut::VecMut, GraphId};
6
7pub enum Context {
8 Computed {
9 parent_ids: VecMut<(GraphId, Rc<dyn Any>)>,
10 },
11 Transaction,
12}
13
14impl Context {
15 pub(crate) fn computed() -> Context {
16 Context::Computed {
17 parent_ids: VecMut::new(),
18 }
19 }
20
21 pub(crate) fn transaction() -> Context {
22 Context::Transaction
23 }
24
25 pub(crate) fn add_parent(&self, parent_id: GraphId, parent_rc: Rc<dyn Any>) {
26 if let Context::Computed { parent_ids } = self {
27 parent_ids.push((parent_id, parent_rc));
28 }
29 }
30
31 pub(crate) fn get_parents(self) -> (BTreeSet<GraphId>, Vec<Rc<dyn Any>>) {
32 if let Context::Computed { parent_ids } = self {
33 parent_ids.into_inner().into_iter().unzip()
34 } else {
35 (BTreeSet::new(), Vec::new())
36 }
37 }
38
39 pub(crate) fn is_transaction(&self) -> bool {
40 match self {
41 Context::Computed { parent_ids: _ } => false,
42 Context::Transaction => true,
43 }
44 }
45}
46
47#[test]
48fn test_context() {
49 use crate::computed::graph_id::GraphIdKind;
50
51 let context = Context::computed();
52
53 let id1 = GraphId::new_for_test(GraphIdKind::Computed, 14);
54 let id2 = GraphId::new_for_test(GraphIdKind::Computed, 15);
55 let id3 = GraphId::new_for_test(GraphIdKind::Computed, 16);
56
57 context.add_parent(id1, Rc::new(1));
58 context.add_parent(id1, Rc::new(1));
59 context.add_parent(id2, Rc::new(1));
60 context.add_parent(id3, Rc::new(1));
61 context.add_parent(id3, Rc::new(1));
62
63 let (list, rcs) = context.get_parents();
64 assert_eq!(list.len(), 3);
65 assert_eq!(rcs.len(), 5);
66}