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::Option(option) => std::slice::from_ref(option),
43                        glory_render::SelectEntry::Group(group) => {
44                            nodes += 1;
45                            bytes += group.label.len();
46                            group.options.as_slice()
47                        }
48                    };
49                    for option in opts {
50                        nodes += 1;
51                        bytes +=
52                            option.key.as_str().len() + option.label.len() + option.value.len();
53                    }
54                }
55            }
56            for piece in &shape.pieces {
57                nodes += 1;
58                match &piece.kind {
59                    Kind::Text(text) => bytes += text.len(),
60                    Kind::Element {
61                        attributes,
62                        properties,
63                        ..
64                    } => {
65                        bytes += attributes.values().map(String::len).sum::<usize>();
66                        bytes += properties
67                            .values()
68                            .map(|v| match v {
69                                Property::Text(v) => v.len(),
70                                Property::Bool(_) => 0,
71                                Property::SelectedKeys(keys) => keys.iter().map(String::len).sum(),
72                                Property::RichDocument(document) => document.charged_bytes(),
73                            })
74                            .sum::<usize>();
75                    }
76                }
77            }
78        }
79        (nodes, bytes)
80    }
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use glory_render::{Descriptor, PlanNode, Props};
87    fn declaration() -> Plan {
88        Plan::new(vec![PlanNode {
89            parent: None,
90            descriptor: Descriptor::new(Props::View),
91        }])
92        .unwrap()
93    }
94    #[test]
95    fn shape_cache_shares_only_live_declarations_and_bounds_retained_entries() {
96        let mut cache = Plans::default();
97        let plan = declaration();
98        let first = cache.shape(&plan).unwrap();
99        assert!(Rc::ptr_eq(&first, &cache.shape(&plan).unwrap()));
100        let plans: Vec<_> = (0..80).map(|_| declaration()).collect();
101        for plan in &plans {
102            cache.shape(plan).unwrap();
103        }
104        assert_eq!(cache.0.len(), 64);
105        drop(plans);
106        cache.shape(&declaration()).unwrap();
107        assert_eq!(cache.0.len(), 2);
108        drop(plan);
109        cache.shape(&declaration()).unwrap();
110        assert_eq!(cache.0.len(), 1);
111    }
112}
113#[derive(Default)]
114pub(crate) struct Plans(HashMap<usize, (WeakPlan, Rc<PlanShape>)>);
115impl Plans {
116    pub fn shape(&mut self, plan: &Plan) -> Result<Rc<PlanShape>, Error> {
117        if let Some((source, shape)) = self.0.get(&plan.identity())
118            && source.upgrade().is_some_and(|p| p.same(plan))
119        {
120            return Ok(shape.clone());
121        }
122        self.0.retain(|_, (source, _)| source.upgrade().is_some());
123        let shape = Rc::new(PlanShape {
124            shapes: plan
125                .nodes()
126                .iter()
127                .map(|node| crate::shape(&node.descriptor))
128                .collect::<Result<_, _>>()?,
129            parents: plan.nodes().iter().map(|node| node.parent).collect(),
130        });
131        let (nodes, bytes) = self
132            .0
133            .values()
134            .map(|(_, shape)| shape.weight())
135            .fold(shape.weight(), |(an, ab), (n, b)| (an + n, ab + b));
136        if self.0.len() < 64 && nodes <= 4096 && bytes <= 1024 * 1024 {
137            self.0
138                .insert(plan.identity(), (plan.downgrade(), shape.clone()));
139        }
140        Ok(shape)
141    }
142}