1use serde::{Deserialize, Serialize};
4use thiserror::Error;
5
6#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
9#[serde(transparent)]
10pub struct SiblingOrder(pub Vec<u16>);
11
12#[derive(Debug, Clone, PartialEq, Eq, Error)]
14pub enum OrderError {
15 #[error("sibling order bounds must be valid and strictly increasing")]
17 InvalidBounds,
18 #[error("sibling order exceeds 128 digits")]
20 Exhausted,
21}
22
23impl Default for SiblingOrder {
24 fn default() -> Self {
25 Self(vec![32768])
26 }
27}
28
29impl SiblingOrder {
30 #[must_use]
32 pub fn is_valid(&self) -> bool {
33 !self.0.is_empty() && self.0.len() <= 128 && self.0.last() != Some(&0)
34 }
35
36 pub fn between(left: Option<&Self>, right: Option<&Self>) -> Result<Self, OrderError> {
39 if left.is_some_and(|v| !v.is_valid())
40 || right.is_some_and(|v| !v.is_valid())
41 || left.zip(right).is_some_and(|(a, b)| a >= b)
42 {
43 return Err(OrderError::InvalidBounds);
44 }
45 let mut digits = Vec::new();
46 let mut upper = right;
47 for i in 0..128 {
48 let low = left.and_then(|v| v.0.get(i)).copied().map_or(0, u32::from);
49 let high = upper
50 .and_then(|v| v.0.get(i))
51 .copied()
52 .map_or(65536, u32::from);
53 if high > low + 1 {
54 let digit = if right.is_none() && left.is_some() {
55 low + 1
56 } else {
57 low + (high - low) / 2
58 };
59 digits.push(digit as u16);
60 return Ok(Self(digits));
61 }
62 digits.push(low as u16);
63 if low < high {
64 upper = None;
65 }
66 }
67 Err(OrderError::Exhausted)
68 }
69}
70
71#[cfg(test)]
72mod tests;