Skip to main content

cranpose_ui/modifier/
elements.rs

1// The elements a modifier holds, how two modifiers join, and the inspector
2// metadata that travels with them.
3
4use std::rc::Rc;
5
6use cranpose_core::ProvidedValue;
7use cranpose_foundation::DynModifierElement;
8use smallvec::SmallVec;
9
10use super::{InspectorMetadata, Modifier};
11
12fn inspector_slice(inspector: &Option<Rc<Vec<InspectorMetadata>>>) -> &[InspectorMetadata] {
13    inspector_slice_of(inspector.as_ref())
14}
15
16fn inspector_slice_of(inspector: Option<&Rc<Vec<InspectorMetadata>>>) -> &[InspectorMetadata] {
17    inspector.map_or(&[], |list| list.as_slice())
18}
19
20/// The inspector metadata of two modifiers joined, first `first`'s, or
21/// `None` when neither has any.
22// Cold: only a build that records inspector metadata reaches it.
23#[cold]
24#[inline(never)]
25fn merged_inspector(
26    first: &[InspectorMetadata],
27    second: &[InspectorMetadata],
28) -> Option<Rc<Vec<InspectorMetadata>>> {
29    if first.is_empty() && second.is_empty() {
30        return None;
31    }
32    Some(Rc::new(first.iter().chain(second).cloned().collect()))
33}
34
35// A modifier's elements, when it holds several: a chain of up to four
36// lives inline in its one shared allocation.
37pub(super) type ModifierElements = SmallVec<[DynModifierElement; 4]>;
38
39// The elements of a modifier that holds several, or one with inspector
40// metadata, in one shared allocation, which the chain's later links extend
41// in place while it is the only owner.
42#[derive(Default)]
43pub(super) struct ManyElements {
44    elements: ModifierElements,
45    // `None` when no element records inspector metadata, which is always
46    // outside tests and modifier debugging: no allocation.
47    inspector: Option<Rc<Vec<InspectorMetadata>>>,
48    provides_composition_locals: bool,
49}
50
51impl ManyElements {
52    // `first` followed by `more`. Elements move into the joined chain;
53    // only those another modifier also holds are copied.
54    fn joined(first: ModifierKind, more: ModifierKind) -> Rc<Self> {
55        // A new chain starts empty in its allocation, so its elements land
56        // there and the list never moves.
57        let (mut chain, first) = match first {
58            ModifierKind::Many(chain) => (chain, ModifierKind::Empty),
59            first => (Rc::default(), first),
60        };
61        if let Some(owned) = Rc::get_mut(&mut chain) {
62            owned.push(first);
63            owned.push(more);
64            return chain;
65        }
66        // Only a list another modifier holds too comes here, and `first` is
67        // empty then.
68        let mut copy = Self::default();
69        copy.append(&chain);
70        copy.push(more);
71        Rc::new(copy)
72    }
73
74    // Takes in the elements of `more` after its own. Always inline, with the
75    // list case out of line: a join pushes two lone elements mostly, and the
76    // call of each cost more than the push (39 of 50 instructions a push on
77    // the feed when it stayed out of line).
78    #[inline(always)]
79    fn push(&mut self, more: ModifierKind) {
80        match more {
81            ModifierKind::Empty => {}
82            ModifierKind::One(element) => {
83                self.provides_composition_locals |= element.provides_composition_locals();
84                self.elements.push(element);
85            }
86            ModifierKind::Many(shared) => self.append(&shared),
87        }
88    }
89
90    // Takes in the elements of the list `shared` after its own, as copies:
91    // a plain element's copy is its value, and one way to take them in keeps
92    // the code of the join small.
93    #[inline(never)]
94    fn append(&mut self, shared: &Self) {
95        self.provides_composition_locals |= shared.provides_composition_locals;
96        if shared.inspector.is_some() {
97            self.inspector = merged_inspector(
98                inspector_slice(&self.inspector),
99                inspector_slice(&shared.inspector),
100            );
101        }
102        for element in &shared.elements {
103            self.elements.push(element.clone());
104        }
105    }
106}
107
108// What a modifier holds.
109#[derive(Clone)]
110pub(super) enum ModifierKind {
111    Empty,
112    // A lone element without inspector metadata, as each link of a builder
113    // chain starts out: a plain element takes no allocation.
114    One(DynModifierElement),
115    Many(Rc<ManyElements>),
116}
117
118impl ModifierKind {
119    /// Whether both are the same storage, so equal without comparing.
120    pub(super) fn shares_storage(&self, other: &Self) -> bool {
121        match (self, other) {
122            (Self::One(a), Self::One(b)) => a.is(b),
123            (Self::Many(a), Self::Many(b)) => Rc::ptr_eq(a, b),
124            _ => false,
125        }
126    }
127}
128
129// A modifier's elements and its inspector metadata, in order.
130pub(crate) type ModifierElementIterator<'a> = std::slice::Iter<'a, DynModifierElement>;
131pub(crate) type ModifierInspectorIterator<'a> = std::slice::Iter<'a, InspectorMetadata>;
132
133impl Modifier {
134    /// This modifier followed by `next`.
135    ///
136    /// It takes `self`: a modifier built link by link owns its elements
137    /// alone, so each link joins them in place instead of copying the chain.
138    /// Clone a modifier first to keep using it; the join then copies it.
139    // One copy: every builder call of an app's bodies joins through it.
140    #[inline(never)]
141    pub fn then(self, next: Self) -> Self {
142        let kind = match (self.kind, next.kind) {
143            (ModifierKind::Empty, kind) | (kind, ModifierKind::Empty) => kind,
144            (first, more) => ModifierKind::Many(ManyElements::joined(first, more)),
145        };
146        Self { kind }
147    }
148
149    // A modifier of `elements`, with the inspector metadata `inspector`.
150    pub(super) fn of_elements(
151        mut elements: ModifierElements,
152        inspector: Option<Rc<Vec<InspectorMetadata>>>,
153    ) -> Self {
154        let kind = match (elements.len(), inspector) {
155            (0, _) => ModifierKind::Empty,
156            (1, None) => match elements.pop() {
157                Some(element) => ModifierKind::One(element),
158                None => ModifierKind::Empty,
159            },
160            (_, inspector) => ModifierKind::Many(Rc::new(ManyElements {
161                provides_composition_locals: elements
162                    .iter()
163                    .any(DynModifierElement::provides_composition_locals),
164                elements,
165                inspector,
166            })),
167        };
168        Self { kind }
169    }
170
171    /// How many elements the modifier holds.
172    pub(crate) fn element_count(&self) -> usize {
173        self.as_elements().len()
174    }
175
176    pub(crate) fn iter_elements(&self) -> ModifierElementIterator<'_> {
177        self.as_elements().iter()
178    }
179
180    pub(crate) fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
181        let provides = match &self.kind {
182            ModifierKind::Empty => false,
183            ModifierKind::One(element) => element.provides_composition_locals(),
184            ModifierKind::Many(chain) => chain.provides_composition_locals,
185        };
186        if !provides {
187            return Vec::new();
188        }
189        self.iter_elements()
190            .flat_map(|element| element.provided_composition_locals())
191            .collect()
192    }
193
194    // The modifier's inspector metadata, `None` when it carries none.
195    pub(super) fn inspector(&self) -> Option<&Rc<Vec<InspectorMetadata>>> {
196        match &self.kind {
197            ModifierKind::Empty | ModifierKind::One(_) => None,
198            ModifierKind::Many(chain) => chain.inspector.as_ref(),
199        }
200    }
201
202    pub(crate) fn iter_inspector_metadata(&self) -> ModifierInspectorIterator<'_> {
203        inspector_slice_of(self.inspector()).iter()
204    }
205
206    #[cfg(test)]
207    pub(crate) fn elements(&self) -> Vec<DynModifierElement> {
208        self.as_elements().to_vec()
209    }
210
211    pub(crate) fn inspector_metadata(&self) -> Vec<InspectorMetadata> {
212        inspector_slice_of(self.inspector()).to_vec()
213    }
214
215    /// A modifier of the one `element`.
216    pub(crate) fn from_dyn_element(element: DynModifierElement) -> Self {
217        Self {
218            kind: ModifierKind::One(element),
219        }
220    }
221
222    pub(crate) fn with_inspector_metadata(self, metadata: InspectorMetadata) -> Self {
223        if metadata.is_empty() {
224            return self;
225        }
226        let mut chain = match self.kind {
227            ModifierKind::Empty => return self,
228            ModifierKind::One(element) => {
229                let mut chain = ManyElements::default();
230                chain.push(ModifierKind::One(element));
231                chain
232            }
233            ModifierKind::Many(shared) => {
234                let mut chain = ManyElements::default();
235                chain.append(&shared);
236                chain
237            }
238        };
239        let mut list = chain.inspector.as_deref().cloned().unwrap_or_default();
240        list.push(metadata);
241        chain.inspector = Some(Rc::new(list));
242        Self {
243            kind: ModifierKind::Many(Rc::new(chain)),
244        }
245    }
246
247    pub(super) fn as_elements(&self) -> &[DynModifierElement] {
248        match &self.kind {
249            ModifierKind::Empty => &[],
250            ModifierKind::One(element) => std::slice::from_ref(element),
251            ModifierKind::Many(chain) => &chain.elements,
252        }
253    }
254}