use std::cmp::Ordering;
#[inline]
pub fn cmp(a: &[u8], b: &[u8]) -> Ordering {
tilo_automerge::rich_text::key_cmp(a, b)
}
fn midpoint(lo: &[u8], hi: &[u8]) -> Vec<u8> {
let width = lo.len().max(hi.len()).max(1);
let mut sum = Vec::with_capacity(width);
let mut carry = 0u8;
for i in (0..width).rev() {
let l = u16::from(lo.get(i).copied().unwrap_or(0));
let h = u16::from(hi.get(i).copied().unwrap_or(0));
let total = l.saturating_add(h).saturating_add(u16::from(carry));
let [digit, next_carry] = total.to_le_bytes();
sum.push(digit);
carry = next_carry;
}
let mut out = Vec::with_capacity(sum.len().saturating_add(1));
let mut half_owed = carry == 1;
for digit in sum.into_iter().rev() {
out.push(if half_owed { 128 } else { 0 } | (digit / 2));
half_owed = digit % 2 == 1;
}
if half_owed {
out.push(128);
}
while out.len() > 1 && out.last() == Some(&0) {
out.pop();
}
out
}
pub fn between(lo: Option<&[u8]>, hi: Option<&[u8]>) -> Vec<u8> {
match (lo, hi) {
(None, None) => vec![128],
(Some(l), None) => after(l),
(None, Some(h)) => midpoint(&[], h),
(Some(l), Some(h)) => midpoint(l, h),
}
}
const APPEND_DIGITS: usize = 3;
fn after(l: &[u8]) -> Vec<u8> {
let mut v = l.to_vec();
while v.len() > 1 && v.last() == Some(&0) {
v.pop();
}
if v.len() < APPEND_DIGITS {
v.resize(APPEND_DIGITS, 0);
}
if let Some(i) = v.iter().rposition(|&b| b < 255) {
v.truncate(i.saturating_add(1));
if let Some(last) = v.last_mut() {
*last = last.saturating_add(1);
}
return v;
}
v.resize(v.len().saturating_add(APPEND_DIGITS), 0);
if let Some(last) = v.last_mut() {
*last = 1;
}
v
}
pub fn between_salted(lo: Option<&[u8]>, hi: Option<&[u8]>, salt: u16) -> Vec<u8> {
match hi {
None => after_salted(lo.unwrap_or(&[]), salt),
Some(h) => across(lo.unwrap_or(&[]), h, salt),
}
}
fn across(lo: &[u8], hi: &[u8], salt: u16) -> Vec<u8> {
let width = lo.len().max(hi.len()).max(1);
let mut gap = vec![0u8; width];
let mut borrow = 0u16;
for i in (0..width).rev() {
let h = u16::from(hi.get(i).copied().unwrap_or(0));
let taken = u16::from(lo.get(i).copied().unwrap_or(0)).saturating_add(borrow);
let (digit, next) = if h >= taken {
(h.saturating_sub(taken), 0)
} else {
(h.saturating_add(256).saturating_sub(taken), 1)
};
borrow = next;
if let Some(slot) = gap.get_mut(i) {
*slot = u8::try_from(digit).unwrap_or(0);
}
}
let n = 16_384u32.saturating_add(u32::from(salt % 32_768));
let mut part = vec![0u8; width.saturating_add(2)];
let mut carry = 0u32;
for i in (0..width).rev() {
let value = u32::from(gap.get(i).copied().unwrap_or(0))
.saturating_mul(n)
.saturating_add(carry);
if let Some(slot) = part.get_mut(i.saturating_add(2)) {
*slot = u8::try_from(value & 0xff).unwrap_or(0);
}
carry = value >> 8;
}
if let Some(slot) = part.get_mut(1) {
*slot = u8::try_from(carry & 0xff).unwrap_or(0);
}
if let Some(slot) = part.first_mut() {
*slot = u8::try_from((carry >> 8) & 0xff).unwrap_or(0);
}
let mut out = vec![0u8; part.len()];
let mut carry = 0u16;
for i in (0..part.len()).rev() {
let total = u16::from(lo.get(i).copied().unwrap_or(0))
.saturating_add(u16::from(part.get(i).copied().unwrap_or(0)))
.saturating_add(carry);
let [digit, next] = total.to_le_bytes();
if let Some(slot) = out.get_mut(i) {
*slot = digit;
}
carry = u16::from(next);
}
while out.len() > 1 && out.last() == Some(&0) {
out.pop();
}
out
}
fn after_salted(l: &[u8], salt: u16) -> Vec<u8> {
let [high, low] = salt.to_be_bytes();
let salted = |mut head: Vec<u8>| {
head.extend_from_slice(&[high, low | 1]);
head
};
let mut v = l.to_vec();
while v.len() > 1 && v.last() == Some(&0) {
v.pop();
}
if v.len() < APPEND_DIGITS.saturating_add(2) {
v.resize(APPEND_DIGITS.saturating_add(2), 0);
}
let head = v.len().saturating_sub(2);
let mut counted = v.get(..head).unwrap_or(&[]).to_vec();
if let Some(i) = counted.iter().rposition(|&b| b < 255) {
counted.truncate(i.saturating_add(1));
if let Some(last) = counted.last_mut() {
*last = last.saturating_add(1);
}
counted.resize(head, 0);
return salted(counted);
}
let mut longer = v;
longer.extend(std::iter::repeat_n(0, APPEND_DIGITS.saturating_sub(1)));
longer.push(1);
salted(longer)
}
#[cfg(test)]
mod tests {
use super::*;
tilo_test_env::scenario! {
fn byte_order_keys_stay_ordered_short_and_within_their_bounds;
phase salted_keys_stay_within_their_bounds_and_differ_by_salt;
{
use Ordering::Less;
type Bound = Option<Vec<u8>>;
let bounds: [(Bound, Bound); 6] = [
(None, None),
(Some(vec![10]), Some(vec![11])),
(Some(vec![10, 255, 255]), Some(vec![11])),
(None, Some(vec![0, 0, 1])),
(Some(vec![255, 255, 255, 255, 255]), None),
(
Some(vec![1, 2, 3, 4, 5, 6, 7]),
Some(vec![1, 2, 3, 4, 5, 6, 8]),
),
];
for (lo, hi) in bounds {
let mut keys = Vec::new();
for salt in [0, 2, 7_000, 20_001, 32_767] {
let key = between_salted(lo.as_deref(), hi.as_deref(), salt);
if let Some(lo) = &lo {
assert_eq!(cmp(lo, &key), Less, "{lo:?} < {key:?}");
}
if let Some(hi) = &hi {
assert_eq!(cmp(&key, hi), Less, "{key:?} < {hi:?}");
}
keys.push(key);
}
let mut distinct = keys.clone();
distinct.sort();
distinct.dedup();
assert_eq!(distinct.len(), keys.len(), "{keys:?}");
}
}
phase a_later_insert_fits_between_two_made_at_once;
{
let (lo, hi) = (vec![64u8], vec![192u8]);
let one = between_salted(Some(&lo), Some(&hi), 11);
let other = between_salted(Some(&lo), Some(&hi), 12_345);
let (first, second) = if cmp(&one, &other).is_lt() {
(one, other)
} else {
(other, one)
};
let middle = between_salted(Some(&first), Some(&second), 99);
assert!(cmp(&first, &middle).is_lt() && cmp(&middle, &second).is_lt());
}
phase a_run_of_salted_appends_keeps_its_length;
{
let mut key = between_salted(None, None, 5);
let length = key.len();
for salt in 0..2_000u16 {
let next = between_salted(Some(&key), None, salt.wrapping_mul(7_919));
assert!(cmp(&key, &next).is_lt());
key = next;
}
assert_eq!(key.len(), length);
}
phase between_orders_strictly_within_its_bounds;
{
use Ordering::{Equal, Less};
let mid = between(None, None);
let after = between(Some(&mid), None);
let before = between(None, Some(&mid));
let (ten, twenty) = (vec![10u8], vec![20u8]);
let midpoint = between(Some(&ten), Some(&twenty));
for (name, a, b, want) in [
(
"between empty bounds is past the empty key",
&[][..],
&mid[..],
Less,
),
("append after is greater", &mid[..], &after[..], Less),
("prepend before is smaller", &before[..], &mid[..], Less),
(
"midpoint is above its lower bound",
&ten[..],
&midpoint[..],
Less,
),
(
"midpoint is below its upper bound",
&midpoint[..],
&twenty[..],
Less,
),
(
"trailing zeros compare equal",
&[5][..],
&[5, 0, 0][..],
Equal,
),
] {
assert_eq!(cmp(a, b), want, "case {name}");
}
let mut lo = between(None, None);
let hi = between(Some(&lo), None);
let mut prev = lo.clone();
for _ in 0..200 {
let m = between(Some(&lo), Some(&hi));
assert_eq!(cmp(&lo, &m), Less, "m must exceed lo");
assert_eq!(cmp(&m, &hi), Less, "m must precede hi");
assert_eq!(cmp(&prev, &m), Less, "strictly increasing");
prev = m.clone();
lo = m;
}
}
phase sequential_appends_stay_short_and_ordered;
{
let mut key = between(None, None);
let mut max_len = key.len();
for _ in 0..1_000_000 {
let next = between(Some(&key), None);
assert_eq!(
cmp(&key, &next),
Ordering::Less,
"each append is strictly greater"
);
key = next;
max_len = max_len.max(key.len());
}
assert!(
max_len <= APPEND_DIGITS,
"append keys must stay short (got {max_len} bytes) or insertion is O(n²)"
);
}
phase random_inserts_stay_strictly_ordered;
{
let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
for _ in 0..64 {
let mut keys: Vec<Vec<u8>> = vec![between(None, None)];
for _ in 0..120 {
seed = seed
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
let slot = usize::try_from(seed >> 40).unwrap_or(0);
let idx = slot.checked_rem(keys.len().saturating_add(1)).unwrap_or(0);
let lo = idx
.checked_sub(1)
.and_then(|i| keys.get(i))
.map(Vec::as_slice);
let hi = keys.get(idx).map(Vec::as_slice);
let k = between(lo, hi);
if let Some(l) = lo {
assert_eq!(cmp(l, &k), Ordering::Less);
}
if let Some(h) = hi {
assert_eq!(cmp(&k, h), Ordering::Less);
}
keys.insert(idx, k);
}
for w in keys.windows(2) {
assert_eq!(cmp(&w[0], &w[1]), Ordering::Less);
}
}
}
}
}