flm_core/model/addr.rs
1//! The identifiers of a tree and of a node: [`TreeId`] and [`NodeAddr`], the
2//! keys under which computed data is stored per node.
3//!
4//! A **tree** is one placement of a [fragment](crate::model::doc::Fragment)'s
5//! node tree in a document. The document's tree arena numbers its trees with
6//! [`TreeId`]s in the order they are added, and never renumbers or reuses
7//! them. Adding the same `Arc<Fragment>` twice to a document makes two trees,
8//! each with its own computed data.
9//!
10//! A [`TreeId`] can also identify a [synthesized
11//! value](crate::guide::concepts_overview#synthesized-values): a small tree
12//! that a stage builds while a run is under way, such as the content a `\ref`
13//! displays or a formatted citation entry. A synthesized value is held outside
14//! the document's trees: a consumer lowers it and renders it like document
15//! content, but no stage that scans the document reaches it. Synthesized values
16//! are numbered from zero by the stage invocation that builds them, so two
17//! invocations assign the same identifiers, and the identifier of a synthesized
18//! value means nothing outside the invocation that built it.
19//!
20//! [`TreeId`] holds both kinds of identifier in 4 bytes, told apart by a tag
21//! bit. Code that stores computed data must respect two rules that follow from
22//! the numbering of synthesized values:
23//!
24//! - no table stored in a run's shared store may use as a key a [`NodeAddr`]
25//! inside a synthesized value;
26//! - a table shown for inspection writes a stored synthesized value out in
27//! full, never as its identifier.
28//!
29//! A [`NodeAddr`] pairs a [`TreeId`] with techy's [`NodeId`], 12 bytes in all.
30//! It is `Copy` and ordered, so it can key an ordered map. A [`NodeId`] carries
31//! a tag of the tree layout that assigned it, and that tag takes part in
32//! equality, ordering and hashing. Two addresses in different trees never
33//! compare equal, because their [`TreeId`]s differ. An ordered map keyed by addresses visits them tree by tree,
34//! and within a tree in the tree's storage order. That order is deterministic,
35//! but it is not document order: document order is defined by the walk,
36//! [`DocContent::walk`].
37//!
38//! [`DocContent::walk`]: crate::model::doc::DocContent::walk
39
40use std::fmt;
41
42pub use techy::core::node::NodeId;
43
44/// The identifier of one tree of a document's tree arena, or of one
45/// synthesized value built inside a run.
46///
47/// The two kinds of identifier are numbered separately: a document tree and a
48/// synthesized value with the same number are different identifiers.
49/// [`TreeId::tree`] and [`TreeId::value`] create an identifier of each kind;
50/// [`TreeId::is_document_tree`] and [`TreeId::is_value`] tell which kind an
51/// identifier is, and [`TreeId::index`] returns its number. See the [module
52/// documentation](self) for what each kind identifies.
53///
54/// Every document tree orders before every synthesized value; identifiers of
55/// one kind order by their number. The `Display` form is `tree#3` for a
56/// document tree and `value#3` for a synthesized value.
57///
58/// # Examples
59///
60/// ```
61/// use flm_core::model::addr::TreeId;
62///
63/// let tree = TreeId::tree(3);
64/// let value = TreeId::value(3);
65/// assert_ne!(tree, value);
66/// assert_eq!(tree.index(), value.index());
67/// assert!(tree.is_document_tree());
68/// assert!(value.is_value());
69/// assert!(tree < value);
70/// ```
71#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
72#[repr(transparent)]
73pub struct TreeId(u32);
74
75impl TreeId {
76 const VALUE_TAG: u32 = 1 << 31;
77 const INDEX_MASK: u32 = !Self::VALUE_TAG;
78
79 /// The identifier of the document tree at index `index` of a document's
80 /// tree arena.
81 ///
82 /// A document assigns these identifiers itself as trees are added
83 /// ([`DocContent::place`](crate::model::doc::DocContent::place),
84 /// [`DocContent::add_tree`](crate::model::doc::DocContent::add_tree)); a
85 /// caller creates one to refer to a tree it knows the index of. See
86 /// [`TreeId::value`] for the identifier of a synthesized value.
87 ///
88 /// # Panics
89 ///
90 /// Panics if `index` is 2³¹ or greater: the highest bit is the tag that
91 /// tells the two kinds of identifier apart.
92 /// [`DocContent::add_tree`](crate::model::doc::DocContent::add_tree)
93 /// checks the same bound before it creates an identifier.
94 pub const fn tree(index: u32) -> TreeId {
95 assert!(index & Self::VALUE_TAG == 0, "tree index exceeds the TreeId range");
96 TreeId(index)
97 }
98
99 /// The identifier of the synthesized value numbered `index` within one
100 /// stage invocation.
101 ///
102 /// Each stage invocation numbers its synthesized values from zero, so an
103 /// identifier created here is meaningful only inside the invocation that
104 /// built the synthesized value.
105 ///
106 /// # Panics
107 ///
108 /// Panics if `index` is 2³¹ or greater: the highest bit is the tag that
109 /// tells the two kinds of identifier apart.
110 pub const fn value(index: u32) -> TreeId {
111 assert!(index & Self::VALUE_TAG == 0, "value index exceeds the TreeId range");
112 TreeId(index | Self::VALUE_TAG)
113 }
114
115 /// The identifier's number: the arena index of a document tree, or the
116 /// number a stage invocation gave a synthesized value.
117 ///
118 /// A document tree and a synthesized value may have the same number;
119 /// [`TreeId::is_value`] tells them apart.
120 pub const fn index(self) -> u32 {
121 self.0 & Self::INDEX_MASK
122 }
123
124 /// Returns `true` when this identifies a synthesized value, `false` when it
125 /// identifies a document tree.
126 pub const fn is_value(self) -> bool {
127 self.0 & Self::VALUE_TAG != 0
128 }
129
130 /// Returns `true` when this identifies a document tree, `false` when it
131 /// identifies a synthesized value.
132 pub const fn is_document_tree(self) -> bool {
133 !self.is_value()
134 }
135}
136
137impl fmt::Debug for TreeId {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 if self.is_value() {
140 write!(f, "TreeId::value({})", self.index())
141 } else {
142 write!(f, "TreeId::tree({})", self.index())
143 }
144 }
145}
146
147impl fmt::Display for TreeId {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 if self.is_value() {
150 write!(f, "value#{}", self.index())
151 } else {
152 write!(f, "tree#{}", self.index())
153 }
154 }
155}
156
157/// The address of one node in one tree: the tree's [`TreeId`] and the node's
158/// [`NodeId`] in that tree.
159///
160/// Every computed table that stores data per node uses this as its key, and a
161/// table entry uses it to refer to a node of another tree. It is `Copy` and
162/// ordered; the [module documentation](self) explains that this order is not
163/// document order.
164#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
165pub struct NodeAddr {
166 /// The tree that contains the node.
167 pub tree: TreeId,
168 /// The node within that tree.
169 pub node: NodeId,
170}
171
172impl NodeAddr {
173 /// The address of the node `node` in the tree `tree`.
174 ///
175 /// No check is made here that the node belongs to that tree. A [`NodeId`]
176 /// carries a tag of the tree layout that assigned it, so looking it up in
177 /// any other tree (other than a copy with the same layout) with techy's
178 /// `NodeTree::get` finds no node.
179 pub const fn new(tree: TreeId, node: NodeId) -> NodeAddr {
180 NodeAddr { tree, node }
181 }
182}
183
184impl fmt::Debug for NodeAddr {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 write!(f, "NodeAddr({}, {:?})", self.tree, self.node)
187 }
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193
194 #[test]
195 fn tree_and_value_ids_are_distinct_spaces() {
196 let t = TreeId::tree(3);
197 let v = TreeId::value(3);
198 assert_ne!(t, v);
199 assert_eq!(t.index(), 3);
200 assert_eq!(v.index(), 3);
201 assert!(!t.is_value());
202 assert!(v.is_value());
203 assert!(t.is_document_tree());
204 assert_eq!(format!("{t}"), "tree#3");
205 assert_eq!(format!("{v}"), "value#3");
206 assert_eq!(format!("{t:?}"), "TreeId::tree(3)");
207 }
208
209 #[test]
210 fn document_trees_order_before_values_and_by_index() {
211 let mut ids = vec![TreeId::value(0), TreeId::tree(2), TreeId::tree(0), TreeId::value(1)];
212 ids.sort();
213 assert_eq!(ids, [TreeId::tree(0), TreeId::tree(2), TreeId::value(0), TreeId::value(1)]);
214 assert_eq!(std::mem::size_of::<TreeId>(), 4);
215 }
216}