flm_core/stdlib/features/numbering/value.rs
1//! Counter values ([`CounterValue`]): the value a counter has at a numbered
2//! reference point, and the text that identifies the point by that value
3//! ([`identifier_text`]).
4
5use super::style::Ancestor;
6
7/// A counter value: the value a counter has at one numbered reference point,
8/// a number with optional **sub-numbers** under it.
9///
10/// A sub-number is a further level of counting under the number: the value
11/// `(3, 2)` is the second sub-numbered item under the number three, shown as
12/// `3b` by a counter style whose first sub-level is written in letters
13/// ([`SubLevelDecl`](super::SubLevelDecl)). A value always has a number, and
14/// it has a sub-number for every deeper level at which the counter was
15/// advanced.
16///
17/// Values are ordered by their components: the number first, then each
18/// sub-number in turn, a value without a given sub-number coming before the
19/// same value with one. The default number writer sorts several values in
20/// this order before it writes them, and collapses values that
21/// [immediately succeed](CounterValue::immediately_succeeds) one another into
22/// a range.
23///
24/// # Examples
25///
26/// ```
27/// use flm_core::stdlib::features::numbering::CounterValue;
28///
29/// let third = CounterValue::new(3);
30/// assert_eq!(third.number(), 3);
31/// assert!(third.sub_numbers().is_empty());
32///
33/// let second_under_third = CounterValue::with_sub_numbers(3, [2]);
34/// assert_eq!(second_under_third.components(), [3, 2]);
35/// assert!(second_under_third.immediately_succeeds(&CounterValue::with_sub_numbers(3, [1])));
36/// ```
37#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
38pub struct CounterValue {
39 /// The number followed by the sub-numbers. Never empty: the first entry is
40 /// the number.
41 components: Vec<i64>,
42}
43
44impl CounterValue {
45 /// Returns the value `number`, with no sub-number.
46 pub fn new(number: i64) -> CounterValue {
47 CounterValue { components: vec![number] }
48 }
49
50 /// Returns the value `number` with the given sub-numbers, outermost first.
51 pub fn with_sub_numbers(number: i64, sub_numbers: impl IntoIterator<Item = i64>) -> CounterValue {
52 let mut components = vec![number];
53 components.extend(sub_numbers);
54 CounterValue { components }
55 }
56
57 /// Returns the number: the value's count at the counter's own level.
58 pub fn number(&self) -> i64 {
59 self.components[0]
60 }
61
62 /// Returns the sub-numbers, outermost first; empty for a value that has
63 /// none.
64 pub fn sub_numbers(&self) -> &[i64] {
65 &self.components[1..]
66 }
67
68 /// Returns the value's components: the number followed by the
69 /// sub-numbers, in the order they are written. Never empty.
70 pub fn components(&self) -> &[i64] {
71 &self.components
72 }
73
74 /// Returns whether this value comes immediately after `other`: the two
75 /// have the same number of components, all components but the last are
76 /// equal, and the last is one more.
77 ///
78 /// The default number writer builds runs of consecutive values with this
79 /// test, so `(3, 4)` immediately succeeds `(3, 3)`, while `4` does not
80 /// immediately succeed `(3, 9)`: values of different depths are never
81 /// consecutive.
82 pub fn immediately_succeeds(&self, other: &CounterValue) -> bool {
83 if self.components.len() != other.components.len() {
84 return false;
85 }
86 let split = self.components.len() - 1;
87 self.components[..split] == other.components[..split]
88 && other.components[split]
89 .checked_add(1)
90 .is_some_and(|next| self.components[split] == next)
91 }
92
93 /// Returns this value advanced at `level`: level 0 is the number, level 1
94 /// the first sub-number, and so on. The advanced level gains one, every
95 /// deeper level returns to zero, and a level the value does not have yet
96 /// is created, together with the levels between, which are created at
97 /// zero.
98 ///
99 /// Advancing is the only operation that moves a counter on, and creating a
100 /// deeper level is part of it: a reference point that starts a
101 /// sub-numbered group advances the number and then the first sub-number,
102 /// which takes `3` to `(3, 1)`.
103 ///
104 /// A level that already has the largest number a value can hold
105 /// (`i64::MAX`) keeps it instead of wrapping round to the smallest. No
106 /// document reaches it, since every level counts points one by one.
107 ///
108 /// The caller is responsible for bounding `level`: a value holds every
109 /// level up to the one advanced, so advancing at a level far deeper than
110 /// the value's own depth takes memory in proportion to that level. A
111 /// counter style declares how many sub-numbers it can write, and the
112 /// numbering stage refuses a point that would advance a level deeper than
113 /// that before it advances anything; this bounds the work in the library.
114 ///
115 /// # Examples
116 ///
117 /// ```
118 /// use flm_core::stdlib::features::numbering::CounterValue;
119 ///
120 /// let value = CounterValue::with_sub_numbers(3, [2, 1]);
121 /// assert_eq!(value.advanced(1).components(), [3, 3, 0]);
122 /// assert_eq!(value.advanced(0).components(), [4, 0, 0]);
123 /// assert_eq!(CounterValue::new(3).advanced(1).components(), [3, 1]);
124 /// ```
125 pub fn advanced(&self, level: usize) -> CounterValue {
126 let mut components = self.components.clone();
127 while components.len() <= level {
128 components.push(0);
129 }
130 components[level] = components[level].saturating_add(1);
131 for deeper in components.iter_mut().skip(level + 1) {
132 *deeper = 0;
133 }
134 CounterValue { components }
135 }
136}
137
138/// Returns the text that identifies a numbered reference point by its
139/// counter value: the values of the ancestors first, outermost first as a
140/// [`Parent`](super::Parent) carries them, then the point's own value, every
141/// component written in decimal and joined by hyphens.
142///
143/// A theorem numbered 3 within section 2 gives `2-3`, and a value with
144/// sub-numbers contributes each of them: `(1, 2, 3)` with no ancestor gives
145/// `1-2-3`. The text holds no counter name and no word; a caller that builds
146/// an identifier from it adds its own prefix. The refs feature builds the
147/// anchor of a point whose anchor is derived from its number in this way
148/// ([`ANCHORS`](crate::stdlib::features::refs::ANCHORS)).
149///
150/// The text is not the number a reader sees: it is written in decimal
151/// regardless of the counter style, so that the identifier of a point does
152/// not change when its counter style does.
153///
154/// # Examples
155///
156/// ```
157/// use flm_core::stdlib::features::numbering::{identifier_text, CounterValue};
158///
159/// assert_eq!(identifier_text(&[], &CounterValue::with_sub_numbers(1, [2, 3])), "1-2-3");
160/// ```
161pub fn identifier_text(ancestors: &[Ancestor], value: &CounterValue) -> String {
162 let mut out = String::new();
163 let components = ancestors
164 .iter()
165 .flat_map(|ancestor| ancestor.value.components())
166 .chain(value.components());
167 for component in components {
168 if !out.is_empty() {
169 out.push('-');
170 }
171 out.push_str(&component.to_string());
172 }
173 out
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179
180 #[test]
181 fn a_value_orders_by_its_components() {
182 let mut values = [
183 CounterValue::with_sub_numbers(1, [2]),
184 CounterValue::new(1),
185 CounterValue::new(0),
186 CounterValue::with_sub_numbers(1, [1]),
187 ];
188 values.sort();
189 let ordered: Vec<&[i64]> = values.iter().map(CounterValue::components).collect();
190 assert_eq!(ordered, [&[0][..], &[1][..], &[1, 1][..], &[1, 2][..]]);
191 }
192
193 #[test]
194 fn advancing_the_deepest_level_of_the_largest_number_does_not_overflow() {
195 let value = CounterValue::new(i64::MAX);
196 assert_eq!(value.advanced(0).number(), i64::MAX);
197 }
198
199 #[test]
200 fn a_value_never_immediately_succeeds_one_of_another_depth() {
201 assert!(!CounterValue::new(2).immediately_succeeds(&CounterValue::with_sub_numbers(1, [9])));
202 assert!(!CounterValue::with_sub_numbers(2, [1]).immediately_succeeds(&CounterValue::new(1)));
203 }
204}