1use std::cmp::Ordering;
7
8#[inline]
14pub fn cmp(a: &[u8], b: &[u8]) -> Ordering {
15 tilo_automerge::rich_text::key_cmp(a, b)
16}
17
18fn midpoint(lo: &[u8], hi: &[u8]) -> Vec<u8> {
28 let width = lo.len().max(hi.len()).max(1);
29
30 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 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 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
63pub 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
74const APPEND_DIGITS: usize = 3;
78
79fn 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 *last = last.saturating_add(1);
102 }
103 return v;
104 }
105 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
113pub 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
127fn across(lo: &[u8], hi: &[u8], salt: u16) -> Vec<u8> {
130 let width = lo.len().max(hi.len()).max(1);
131 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 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 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 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 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 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
189fn after_salted(l: &[u8], salt: u16) -> Vec<u8> {
191 let [high, low] = salt.to_be_bytes();
192 let salted = |mut head: Vec<u8>| {
193 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 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 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 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 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}