Skip to main content

glory_html/
plan.rs

1use crate::{Kind, Property, Shape};
2use glory_render::{Error, Plan, WeakPlan};
3use std::{collections::HashMap, rc::Rc};
4
5#[derive(Clone, Debug, PartialEq)]
6pub struct PlanShape {
7    pub shapes: Vec<Shape>,
8    pub parents: Vec<Option<usize>>,
9}
10impl PlanShape {
11    pub fn validate_instance(
12        &self,
13        plan: &Plan,
14        ids: &[glory_render::NodeId],
15        keys: &[u64],
16    ) -> Result<(), Error> {
17        let count = plan.nodes().len();
18        if self.shapes.len() != count
19            || self.parents.len() != count
20            || ids.len() != count
21            || keys.len() != count
22            || self
23                .parents
24                .iter()
25                .zip(plan.nodes())
26                .any(|(parent, node)| *parent != node.parent)
27        {
28            return Err(Error::InvalidProps("plan shape/identity count or topology"));
29        }
30        Ok(())
31    }
32    /// Charged UTF-8 payload and physical node count, not measured heap bytes.
33    pub fn weight(&self) -> (usize, usize) {
34        let mut nodes = 0;
35        let mut bytes = 0;
36        for shape in &self.shapes {
37            if let Some(options) = &shape.select_options {
38                bytes += options.placeholder.as_ref().map_or(0, String::len);
39                nodes += usize::from(options.placeholder.is_some());
40                for entry in options.entries.iter() {
41                    let opts = match entry {
42                        glory_render::SelectEntry::Divider => {
43                            nodes += 1;
44                            continue;
45                        }
46                        glory_render::SelectEntry::Option(option) => std::slice::from_ref(option),
47                        glory_render::SelectEntry::Group(group) => {
48                            nodes += 1;
49                            bytes += group.label.len();
50                            group.options.as_slice()
51                        }
52                    };
53                    for option in opts {
54                        nodes += 1;
55                        bytes +=
56                            option.key.as_str().len() + option.label.len() + option.value.len();
57                    }
58                }
59            }
60            for piece in &shape.pieces {
61                nodes += 1;
62                match &piece.kind {
63                    Kind::Text(text) => bytes += text.len(),
64                    Kind::Element {
65                        attributes,
66                        properties,
67                        ..
68                    } => {
69                        bytes += attributes.values().map(String::len).sum::<usize>();
70                        bytes += properties
71                            .values()
72                            .map(|v| match v {
73                                Property::Text(v) => v.len(),
74                                Property::Bool(_) => 0,
75                                Property::SelectedKeys(keys) => keys.iter().map(String::len).sum(),
76                                Property::RichDocument(document) => document.charged_bytes(),
77                            })
78                            .sum::<usize>();
79                    }
80                }
81            }
82        }
83        (nodes, bytes)
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90    use glory_render::{Descriptor, PlanNode, Props};
91    fn declaration() -> Plan {
92        Plan::new(vec![PlanNode {
93            parent: None,
94            descriptor: Descriptor::new(Props::View),
95        }])
96        .unwrap()
97    }
98    #[test]
99    fn shape_cache_shares_only_live_declarations_and_bounds_retained_entries() {
100        let mut cache = Plans::default();
101        let plan = declaration();
102        let first = cache.shape(&plan).unwrap();
103        assert!(Rc::ptr_eq(&first, &cache.shape(&plan).unwrap()));
104        let plans: Vec<_> = (0..80).map(|_| declaration()).collect();
105        for plan in &plans {
106            cache.shape(plan).unwrap();
107        }
108        assert_eq!(cache.0.len(), 64);
109        drop(plans);
110        cache.shape(&declaration()).unwrap();
111        assert_eq!(cache.0.len(), 2);
112        drop(plan);
113        cache.shape(&declaration()).unwrap();
114        assert_eq!(cache.0.len(), 1);
115    }
116}
117#[derive(Default)]
118pub(crate) struct Plans(HashMap<usize, (WeakPlan, Rc<PlanShape>)>);
119impl Plans {
120    pub fn shape(&mut self, plan: &Plan) -> Result<Rc<PlanShape>, Error> {
121        if let Some((source, shape)) = self.0.get(&plan.identity())
122            && source.upgrade().is_some_and(|p| p.same(plan))
123        {
124            return Ok(shape.clone());
125        }
126        self.0.retain(|_, (source, _)| source.upgrade().is_some());
127        let shape = Rc::new(PlanShape {
128            shapes: plan
129                .nodes()
130                .iter()
131                .map(|node| crate::shape(&node.descriptor))
132                .collect::<Result<_, _>>()?,
133            parents: plan.nodes().iter().map(|node| node.parent).collect(),
134        });
135        let (nodes, bytes) = self
136            .0
137            .values()
138            .map(|(_, shape)| shape.weight())
139            .fold(shape.weight(), |(an, ab), (n, b)| (an + n, ab + b));
140        if self.0.len() < 64 && nodes <= 4096 && bytes <= 1024 * 1024 {
141            self.0
142                .insert(plan.identity(), (plan.downgrade(), shape.clone()));
143        }
144        Ok(shape)
145    }
146}