tilo_resource/order/
mod.rs1pub mod bytes;
11
12const DIGITS: &[u8; 36] = b"0123456789abcdefghijklmnopqrstuvwxyz";
13const BASE: u8 = 36;
14
15fn digit(key: &[u8], index: usize) -> u8 {
16 key.get(index)
17 .and_then(|c| DIGITS.iter().position(|d| d == c))
18 .and_then(|value| u8::try_from(value).ok())
19 .unwrap_or(0)
20}
21
22fn char_of(value: u8) -> char {
23 DIGITS
24 .get(usize::from(value))
25 .map_or('0', |d| char::from(*d))
26}
27
28#[must_use]
38pub fn between(low: Option<&str>, high: Option<&str>) -> String {
39 let open_high = high.is_none_or(|high| low.is_some_and(|low| high <= low));
40 match (low, high) {
41 (Some(low), _) if open_high && is_key(low) => return after(low),
42 (None, Some(high)) if is_key(high) => return before(high),
43 _ => {}
44 }
45 let low = low.unwrap_or("").as_bytes();
46 let mut high = high.map(str::as_bytes).filter(|high| *high > low);
47 let mut out = String::new();
48 let mut index = 0usize;
49 loop {
50 let lo = digit(low, index);
51 let hi = high.map_or(BASE, |high| digit(high, index));
52 if lo == hi {
53 out.push(char_of(lo));
54 } else if hi.saturating_sub(lo) > 1 {
55 out.push(char_of(lo.saturating_add(hi) / 2));
56 return out;
57 } else {
58 out.push(char_of(lo));
60 high = None;
61 }
62 index = index.saturating_add(1);
63 }
64}
65
66const TOP: u8 = BASE - 1;
67
68fn spell(prefix: u8, run: usize, body: &[u8]) -> String {
69 std::iter::repeat_n(prefix, run)
70 .chain(body.iter().copied())
71 .map(char_of)
72 .collect()
73}
74
75fn after(low: &str) -> String {
86 let digits: Vec<u8> = (0..low.len())
87 .map(|index| digit(low.as_bytes(), index))
88 .collect();
89 let run = digits.iter().take_while(|&&value| value == TOP).count();
90 let Some(body) = digits.get(run..).filter(|body| !body.is_empty()) else {
91 return spell(TOP, run, &[1]);
93 };
94 let mut body = body.to_vec();
95 loop {
96 let mut carry = true;
97 for value in body.iter_mut().rev() {
98 if !carry {
99 break;
100 }
101 *value = if *value == TOP {
102 0
103 } else {
104 carry = false;
105 value.saturating_add(1)
106 };
107 }
108 if carry || body.first() == Some(&TOP) {
109 let mut next = vec![0; body.len()];
111 next.push(1);
112 return spell(TOP, run.saturating_add(1), &next);
113 }
114 if body.last() != Some(&0) {
116 return spell(TOP, run, &body);
117 }
118 }
119}
120
121fn before(high: &str) -> String {
124 let digits: Vec<u8> = (0..high.len())
125 .map(|index| digit(high.as_bytes(), index))
126 .collect();
127 let run = digits.iter().take_while(|&&value| value == 0).count();
128 let mut body = digits.get(run..).unwrap_or_default().to_vec();
129 loop {
130 let mut borrow = true;
131 for value in body.iter_mut().rev() {
132 if !borrow {
133 break;
134 }
135 *value = if *value == 0 {
136 TOP
137 } else {
138 borrow = false;
139 value.saturating_sub(1)
140 };
141 }
142 if borrow || body.first().is_none_or(|&first| first == 0) {
143 let next = vec![TOP; body.len().saturating_add(1)];
145 return spell(0, run.saturating_add(1), &next);
146 }
147 if body.last() != Some(&0) {
148 return spell(0, run, &body);
149 }
150 }
151}
152
153#[must_use]
156pub fn is_key(key: &str) -> bool {
157 !key.is_empty() && !key.ends_with('0') && key.bytes().all(|c| DIGITS.contains(&c))
158}
159
160#[must_use]
162pub fn sequence(low: Option<&str>, high: Option<&str>, count: usize) -> Vec<String> {
163 let mut keys = Vec::with_capacity(count);
164 let mut previous = low.map(str::to_owned);
165 for _ in 0..count {
166 let key = between(previous.as_deref(), high);
167 previous = Some(key.clone());
168 keys.push(key);
169 }
170 keys
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 tilo_test_env::scenario! {
178 fn fractional_order_keys_stay_ordered_and_short;
179
180 phase between_is_strictly_ordered_and_never_ends_in_zero;
181 {
182 let cases = [
183 (None, None),
184 (Some("a"), None),
185 (None, Some("a")),
186 (Some("a"), Some("b")),
187 (Some("a"), Some("a1")),
188 (Some("zz"), None),
189 (Some("0001"), Some("0002")),
190 ];
191 for (low, high) in cases {
192 let key = between(low, high);
193 assert!(is_key(&key), "{key}");
194 if let Some(low) = low {
195 assert!(key.as_str() > low, "{low:?} < {key}");
196 }
197 if let Some(high) = high {
198 assert!(key.as_str() < high, "{key} < {high:?}");
199 }
200 }
201 }
202
203 phase repeated_insertion_at_one_point_stays_ordered;
204 {
205 let mut low = between(None, None);
206 let high = between(Some(&low), None);
207 for _ in 0..200 {
208 let key = between(Some(&low), Some(&high));
209 assert!(key > low && key < high);
210 low = key;
211 }
212 let keys = sequence(Some("a"), Some("b"), 50);
213 assert!(keys.windows(2).all(|pair| pair[0] < pair[1]));
214 }
215
216 phase only_between_shaped_keys_are_keys;
217 {
218 for bad in ["", "a0", "A", "a-b", " a"] {
219 assert!(!is_key(bad), "{bad:?}");
220 }
221 assert!(is_key("0001") && is_key("i") && is_key("zz"));
222 }
223
224 phase appends_step_and_grow_logarithmically;
225 {
226 assert_eq!(between(Some("i"), None), "j");
227 assert_eq!(between(Some("y"), None), "z01");
228 assert_eq!(between(Some("z0z"), None), "z11");
229 assert_eq!(between(Some("zyz"), None), "zz001");
230 assert_eq!(between(Some("zz"), None), "zz1");
231 let keys = sequence(None, None, 50_000);
232 assert!(keys.windows(2).all(|pair| pair[0] < pair[1]));
233 assert!(keys.iter().all(|key| is_key(key)));
234 let longest = keys.iter().map(String::len).max().unwrap_or_default();
235 assert!(longest <= 7, "{longest}");
236 }
237
238 phase prepends_mirror_appends;
239 {
240 assert_eq!(between(None, Some("i")), "h");
241 assert_eq!(between(None, Some("1")), "0zz");
242 assert_eq!(between(None, Some("i1")), "hz");
243 let mut high = between(None, None);
244 for _ in 0..50_000 {
245 let key = between(None, Some(&high));
246 assert!(is_key(&key) && key < high, "{key} < {high}");
247 high = key;
248 }
249 assert!(high.len() <= 7, "{high}");
250 }
251
252 phase a_key_minted_by_halving_keeps_its_length;
253 {
254 let old = format!("{}r", "z".repeat(500));
255 let next = between(Some(&old), None);
256 assert!(next > old && next.len() == old.len() && is_key(&next));
257 assert_eq!(between(Some("k"), Some("c")), "l");
259 }
260 }
261}