Skip to main content

tilo_resource/order/
bytes.rs

1//! Fractional order keys as bytes: base-256 fractions where a midpoint
2//! always exists between two distinct keys, compared as fractions (trailing
3//! zeros are insignificant). The compact form rich-text documents store per
4//! paragraph; see the parent module for the string form collections use.
5
6use std::cmp::Ordering;
7
8/// Compare two keys as base-256 fractions (missing/trailing digits are 0).
9///
10/// The comparison itself is kept below this crate ([`tilo_automerge::rich_text::key_cmp`]),
11/// where the reader of a whole document as JSON orders a rich text's paragraphs by it too:
12/// that reader cannot link this crate, and there is one rule.
13#[inline]
14pub fn cmp(a: &[u8], b: &[u8]) -> Ordering {
15    tilo_automerge::rich_text::key_cmp(a, b)
16}
17
18/// `(lo + hi) / 2` as a base-256 fraction (requires `lo < hi`), so the result is
19/// the exact average and therefore strictly between `lo` and `hi`.
20///
21/// Two passes, because a single most-significant-first pass cannot know whether
22/// the digit it is about to emit will be pushed over 255 by a carry arriving
23/// from the digit below it. So: add the two fractions least-significant-first,
24/// where carries travel the way they can be absorbed, then halve the sum
25/// most-significant-first, where the dropped low bit travels down as the 128
26/// that the next digit owes.
27fn midpoint(lo: &[u8], hi: &[u8]) -> Vec<u8> {
28    let width = lo.len().max(hi.len()).max(1);
29
30    // `lo + hi`, least-significant digit first. Both inputs are fractions below
31    // 1, so the carry out of the top digit is the whole integer part: 0 or 1.
32    let mut sum = Vec::with_capacity(width);
33    let mut carry = 0u8;
34    for i in (0..width).rev() {
35        let l = u16::from(lo.get(i).copied().unwrap_or(0));
36        let h = u16::from(hi.get(i).copied().unwrap_or(0));
37        // Two digits plus a carry bit is at most 511, so the widening to u16
38        // makes this addition exact and the saturation unreachable.
39        let total = l.saturating_add(h).saturating_add(u16::from(carry));
40        let [digit, next_carry] = total.to_le_bytes();
41        sum.push(digit);
42        carry = next_carry;
43    }
44
45    // Halve, most-significant digit first: each digit's dropped low bit is worth
46    // half of 256 in the digit below, i.e. 128.
47    let mut out = Vec::with_capacity(sum.len().saturating_add(1));
48    let mut half_owed = carry == 1;
49    for digit in sum.into_iter().rev() {
50        out.push(if half_owed { 128 } else { 0 } | (digit / 2));
51        half_owed = digit % 2 == 1;
52    }
53    if half_owed {
54        out.push(128);
55    }
56
57    while out.len() > 1 && out.last() == Some(&0) {
58        out.pop();
59    }
60    out
61}
62
63/// Produce a key ordered strictly between `lo` and `hi` (either may be `None`
64/// for "before everything" / "after everything").
65pub fn between(lo: Option<&[u8]>, hi: Option<&[u8]>) -> Vec<u8> {
66    match (lo, hi) {
67        (None, None) => vec![128],
68        (Some(l), None) => after(l),
69        (None, Some(h)) => midpoint(&[], h),
70        (Some(l), Some(h)) => midpoint(l, h),
71    }
72}
73
74/// Digits an appended key counts in: appending after a key shorter than this counts in its
75/// last digit, so that many bytes hold about `256^APPEND_DIGITS` appends before one more
76/// group of digits is needed.
77const APPEND_DIGITS: usize = 3;
78
79/// A key strictly greater than `l`, for "append after `l`" (no upper bound).
80///
81/// Counts: `l`, padded to at least [`APPEND_DIGITS`] digits, plus one in its last digit, with
82/// the carry running up through digits already at 255 (dropped, as trailing zeros are
83/// insignificant). Only when every digit is 255 does the key grow, by another
84/// [`APPEND_DIGITS`] digits. A run of `n` appends therefore keeps keys O(log n) bytes long —
85/// incrementing only the existing digits would exhaust a one-byte key after 127 appends and
86/// grow a byte every ~128 more, making keys, every [`cmp`] and the order index O(n).
87/// Concurrent appends after the same `l` still converge (ties broken by block id downstream).
88fn after(l: &[u8]) -> Vec<u8> {
89    let mut v = l.to_vec();
90    while v.len() > 1 && v.last() == Some(&0) {
91        v.pop();
92    }
93    if v.len() < APPEND_DIGITS {
94        v.resize(APPEND_DIGITS, 0);
95    }
96    if let Some(i) = v.iter().rposition(|&b| b < 255) {
97        v.truncate(i.saturating_add(1));
98        if let Some(last) = v.last_mut() {
99            // `rposition` chose this digit because it is below 255, so the
100            // increment is exact and the saturation is unreachable.
101            *last = last.saturating_add(1);
102        }
103        return v;
104    }
105    // Every digit is 255 (≈ 1.0): nothing this long exceeds it, so count in fresh digits.
106    v.resize(v.len().saturating_add(APPEND_DIGITS), 0);
107    if let Some(last) = v.last_mut() {
108        *last = 1;
109    }
110    v
111}
112
113/// A key strictly between `lo` and `hi` that differs with `salt`, so two
114/// replicas inserting into the same gap at once, each with its own salt,
115/// almost always get distinct keys, and a later insert fits between them.
116///
117/// Between two bounds it lies a salted fraction of the way across, within
118/// the middle half of the gap; after the last key it counts one up in the
119/// digit before two salt digits, so a run of appends keeps its length.
120pub fn between_salted(lo: Option<&[u8]>, hi: Option<&[u8]>, salt: u16) -> Vec<u8> {
121    match hi {
122        None => after_salted(lo.unwrap_or(&[]), salt),
123        Some(h) => across(lo.unwrap_or(&[]), h, salt),
124    }
125}
126
127/// `lo + (hi - lo) * f` for `f` in `[1/4, 3/4)` chosen by `salt` (requires
128/// `lo < hi`).
129fn across(lo: &[u8], hi: &[u8], salt: u16) -> Vec<u8> {
130    let width = lo.len().max(hi.len()).max(1);
131    // `hi - lo`, least-significant digit first; `hi > lo`, so nothing is
132    // borrowed out of the top digit.
133    let mut gap = vec![0u8; width];
134    let mut borrow = 0u16;
135    for i in (0..width).rev() {
136        let h = u16::from(hi.get(i).copied().unwrap_or(0));
137        let taken = u16::from(lo.get(i).copied().unwrap_or(0)).saturating_add(borrow);
138        // A digit plus a borrow is at most 256, so the widened sums are exact.
139        let (digit, next) = if h >= taken {
140            (h.saturating_sub(taken), 0)
141        } else {
142            (h.saturating_add(256).saturating_sub(taken), 1)
143        };
144        borrow = next;
145        if let Some(slot) = gap.get_mut(i) {
146            *slot = u8::try_from(digit).unwrap_or(0);
147        }
148    }
149    // `gap * n / 65536`, with `n` in `[16384, 49152)`: two digits longer.
150    let n = 16_384u32.saturating_add(u32::from(salt % 32_768));
151    let mut part = vec![0u8; width.saturating_add(2)];
152    let mut carry = 0u32;
153    for i in (0..width).rev() {
154        // A digit times `n` plus a carry stays far below `u32::MAX`.
155        let value = u32::from(gap.get(i).copied().unwrap_or(0))
156            .saturating_mul(n)
157            .saturating_add(carry);
158        if let Some(slot) = part.get_mut(i.saturating_add(2)) {
159            *slot = u8::try_from(value & 0xff).unwrap_or(0);
160        }
161        carry = value >> 8;
162    }
163    // The product is below 1, so what is carried out is the two top digits.
164    if let Some(slot) = part.get_mut(1) {
165        *slot = u8::try_from(carry & 0xff).unwrap_or(0);
166    }
167    if let Some(slot) = part.first_mut() {
168        *slot = u8::try_from((carry >> 8) & 0xff).unwrap_or(0);
169    }
170    // `lo + part`, below `hi` and so below 1: nothing carries out.
171    let mut out = vec![0u8; part.len()];
172    let mut carry = 0u16;
173    for i in (0..part.len()).rev() {
174        let total = u16::from(lo.get(i).copied().unwrap_or(0))
175            .saturating_add(u16::from(part.get(i).copied().unwrap_or(0)))
176            .saturating_add(carry);
177        let [digit, next] = total.to_le_bytes();
178        if let Some(slot) = out.get_mut(i) {
179            *slot = digit;
180        }
181        carry = u16::from(next);
182    }
183    while out.len() > 1 && out.last() == Some(&0) {
184        out.pop();
185    }
186    out
187}
188
189/// A key after `l` ending in two salt digits.
190fn after_salted(l: &[u8], salt: u16) -> Vec<u8> {
191    let [high, low] = salt.to_be_bytes();
192    let salted = |mut head: Vec<u8>| {
193        // The last digit is never zero, so the key keeps its length.
194        head.extend_from_slice(&[high, low | 1]);
195        head
196    };
197    let mut v = l.to_vec();
198    while v.len() > 1 && v.last() == Some(&0) {
199        v.pop();
200    }
201    if v.len() < APPEND_DIGITS.saturating_add(2) {
202        v.resize(APPEND_DIGITS.saturating_add(2), 0);
203    }
204    let head = v.len().saturating_sub(2);
205    let mut counted = v.get(..head).unwrap_or(&[]).to_vec();
206    if let Some(i) = counted.iter().rposition(|&b| b < 255) {
207        counted.truncate(i.saturating_add(1));
208        if let Some(last) = counted.last_mut() {
209            *last = last.saturating_add(1);
210        }
211        counted.resize(head, 0);
212        return salted(counted);
213    }
214    // Every counted digit is 255: count on past all of `l`.
215    let mut longer = v;
216    longer.extend(std::iter::repeat_n(0, APPEND_DIGITS.saturating_sub(1)));
217    longer.push(1);
218    salted(longer)
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    tilo_test_env::scenario! {
226        fn byte_order_keys_stay_ordered_short_and_within_their_bounds;
227
228        phase salted_keys_stay_within_their_bounds_and_differ_by_salt;
229        {
230            use Ordering::Less;
231            type Bound = Option<Vec<u8>>;
232            let bounds: [(Bound, Bound); 6] = [
233                (None, None),
234                (Some(vec![10]), Some(vec![11])),
235                (Some(vec![10, 255, 255]), Some(vec![11])),
236                (None, Some(vec![0, 0, 1])),
237                (Some(vec![255, 255, 255, 255, 255]), None),
238                (
239                    Some(vec![1, 2, 3, 4, 5, 6, 7]),
240                    Some(vec![1, 2, 3, 4, 5, 6, 8]),
241                ),
242            ];
243            for (lo, hi) in bounds {
244                let mut keys = Vec::new();
245                for salt in [0, 2, 7_000, 20_001, 32_767] {
246                    let key = between_salted(lo.as_deref(), hi.as_deref(), salt);
247                    if let Some(lo) = &lo {
248                        assert_eq!(cmp(lo, &key), Less, "{lo:?} < {key:?}");
249                    }
250                    if let Some(hi) = &hi {
251                        assert_eq!(cmp(&key, hi), Less, "{key:?} < {hi:?}");
252                    }
253                    keys.push(key);
254                }
255                let mut distinct = keys.clone();
256                distinct.sort();
257                distinct.dedup();
258                assert_eq!(distinct.len(), keys.len(), "{keys:?}");
259            }
260        }
261
262        phase a_later_insert_fits_between_two_made_at_once;
263        {
264            let (lo, hi) = (vec![64u8], vec![192u8]);
265            let one = between_salted(Some(&lo), Some(&hi), 11);
266            let other = between_salted(Some(&lo), Some(&hi), 12_345);
267            let (first, second) = if cmp(&one, &other).is_lt() {
268                (one, other)
269            } else {
270                (other, one)
271            };
272            let middle = between_salted(Some(&first), Some(&second), 99);
273            assert!(cmp(&first, &middle).is_lt() && cmp(&middle, &second).is_lt());
274        }
275
276        phase a_run_of_salted_appends_keeps_its_length;
277        {
278            let mut key = between_salted(None, None, 5);
279            let length = key.len();
280            for salt in 0..2_000u16 {
281                let next = between_salted(Some(&key), None, salt.wrapping_mul(7_919));
282                assert!(cmp(&key, &next).is_lt());
283                key = next;
284            }
285            assert_eq!(key.len(), length);
286        }
287
288        phase between_orders_strictly_within_its_bounds;
289        {
290            use Ordering::{Equal, Less};
291            let mid = between(None, None);
292            let after = between(Some(&mid), None);
293            let before = between(None, Some(&mid));
294            let (ten, twenty) = (vec![10u8], vec![20u8]);
295            let midpoint = between(Some(&ten), Some(&twenty));
296            for (name, a, b, want) in [
297                (
298                    "between empty bounds is past the empty key",
299                    &[][..],
300                    &mid[..],
301                    Less,
302                ),
303                ("append after is greater", &mid[..], &after[..], Less),
304                ("prepend before is smaller", &before[..], &mid[..], Less),
305                (
306                    "midpoint is above its lower bound",
307                    &ten[..],
308                    &midpoint[..],
309                    Less,
310                ),
311                (
312                    "midpoint is below its upper bound",
313                    &midpoint[..],
314                    &twenty[..],
315                    Less,
316                ),
317                (
318                    "trailing zeros compare equal",
319                    &[5][..],
320                    &[5, 0, 0][..],
321                    Equal,
322                ),
323            ] {
324                assert_eq!(cmp(a, b), want, "case {name}");
325            }
326
327            // Insert 200 keys always between the first two; each must stay ordered.
328            let mut lo = between(None, None);
329            let hi = between(Some(&lo), None);
330            let mut prev = lo.clone();
331            for _ in 0..200 {
332                let m = between(Some(&lo), Some(&hi));
333                assert_eq!(cmp(&lo, &m), Less, "m must exceed lo");
334                assert_eq!(cmp(&m, &hi), Less, "m must precede hi");
335                assert_eq!(cmp(&prev, &m), Less, "strictly increasing");
336                prev = m.clone();
337                lo = m;
338            }
339        }
340
341        phase sequential_appends_stay_short_and_ordered;
342        {
343            // A long run of appends (the book-length-document case) must NOT grow keys
344            // one byte per insert — that is the O(n²) trap (every cmp is O(len)).
345            let mut key = between(None, None);
346            let mut max_len = key.len();
347            for _ in 0..1_000_000 {
348                let next = between(Some(&key), None);
349                assert_eq!(
350                    cmp(&key, &next),
351                    Ordering::Less,
352                    "each append is strictly greater"
353                );
354                key = next;
355                max_len = max_len.max(key.len());
356            }
357            // Logarithmic: a million appends fit in three digits.
358            assert!(
359                max_len <= APPEND_DIGITS,
360                "append keys must stay short (got {max_len} bytes) or insertion is O(n²)"
361            );
362        }
363
364        phase random_inserts_stay_strictly_ordered;
365        {
366            let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
367            for _ in 0..64 {
368                let mut keys: Vec<Vec<u8>> = vec![between(None, None)];
369                for _ in 0..120 {
370                    seed = seed
371                        .wrapping_mul(6_364_136_223_846_793_005)
372                        .wrapping_add(1_442_695_040_888_963_407);
373                    let slot = usize::try_from(seed >> 40).unwrap_or(0);
374                    let idx = slot.checked_rem(keys.len().saturating_add(1)).unwrap_or(0);
375                    let lo = idx
376                        .checked_sub(1)
377                        .and_then(|i| keys.get(i))
378                        .map(Vec::as_slice);
379                    let hi = keys.get(idx).map(Vec::as_slice);
380                    let k = between(lo, hi);
381                    if let Some(l) = lo {
382                        assert_eq!(cmp(l, &k), Ordering::Less);
383                    }
384                    if let Some(h) = hi {
385                        assert_eq!(cmp(&k, h), Ordering::Less);
386                    }
387                    keys.insert(idx, k);
388                }
389                for w in keys.windows(2) {
390                    assert_eq!(cmp(&w[0], &w[1]), Ordering::Less);
391                }
392            }
393        }
394    }
395}