1use std::collections::{BTreeMap, BTreeSet, VecDeque};
9use std::fmt;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct DecodeError(pub String);
14
15impl fmt::Display for DecodeError {
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 f.write_str(&self.0)
18 }
19}
20
21impl std::error::Error for DecodeError {}
22
23fn max_height(branch_factor: u32) -> u32 {
25 match branch_factor {
26 2 => 31,
27 4 => 16,
28 8 => 11,
29 _ => 7,
30 }
31}
32
33fn decode_header(byte: u8) -> (u32, u32) {
34 let branch_factor = [2, 4, 8, 32][(byte & 0x03) as usize];
35 (branch_factor, ((byte >> 2) & 0x1F) as u32)
36}
37
38fn encode_header(branch_factor: u32, height: u32) -> u8 {
39 let id = match branch_factor {
40 2 => 0,
41 4 => 1,
42 8 => 2,
43 _ => 3,
44 };
45 ((height << 2) | id) as u8
46}
47
48struct InputBits<'a> {
49 data: &'a [u8],
50 branch_factor: u32,
51 byte_index: usize,
52 sub_index: u32,
53}
54
55impl InputBits<'_> {
56 fn next(&mut self) -> Option<u32> {
57 match self.branch_factor {
58 2 | 4 => {
59 let byte = *self.data.get(self.byte_index)?;
60 let mask = (1u32 << self.branch_factor) - 1;
61 let v = (byte as u32 >> self.sub_index) & mask;
62 self.sub_index += self.branch_factor;
63 if self.sub_index >= 8 {
64 self.sub_index = 0;
65 self.byte_index += 1;
66 }
67 Some(v)
68 }
69 8 => {
70 let byte = *self.data.get(self.byte_index)?;
71 self.byte_index += 1;
72 Some(byte as u32)
73 }
74 _ => {
75 let b = self.data.get(self.byte_index..self.byte_index + 4)?;
76 self.byte_index += 4;
77 Some(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
78 }
79 }
80 }
81
82 fn bytes_consumed(&self) -> usize {
83 self.byte_index + usize::from(self.sub_index > 0)
84 }
85}
86
87pub fn decode(
94 data: &[u8],
95 bias: i64,
96 max_value: i64,
97) -> Result<(BTreeSet<u32>, usize), DecodeError> {
98 let header = *data
99 .first()
100 .ok_or_else(|| DecodeError("Empty data".into()))?;
101 let (branch_factor, height) = decode_header(header);
102 let max = max_height(branch_factor);
103 if height > max {
104 return Err(DecodeError(format!(
105 "Height {height} exceeds max {max} for branch factor {branch_factor}"
106 )));
107 }
108 let mut result = BTreeSet::new();
109 if height == 0 {
110 return Ok((result, 1));
111 }
112 let mut bits_in = InputBits {
113 data,
114 branch_factor,
115 byte_index: 1,
116 sub_index: 0,
117 };
118 let bf = branch_factor as i64;
119 let mut queue: VecDeque<(i64, u32)> = VecDeque::from([(0, 1)]);
120 while let Some((start, depth)) = queue.pop_front() {
121 let mut bits = bits_in
122 .next()
123 .ok_or_else(|| DecodeError("Unexpected end of data".into()))?;
124 if bits == 0 {
125 let node_size = bf.pow(height - depth + 1);
127 let fill_start = start + bias;
128 if fill_start > max_value {
129 continue;
130 }
131 let fill_end = max_value.min(start + node_size - 1 + bias);
132 let fill_start = fill_start.max(0);
133 if fill_start <= fill_end {
134 result.extend((fill_start..=fill_end).map(|v| v as u32));
135 }
136 continue;
137 }
138 let next_node_size = bf.pow(height - depth);
139 while bits != 0 {
140 let bit = bits.trailing_zeros() as i64;
141 if depth == height {
142 let value = start + bit + bias;
143 if value > max_value {
144 queue.clear();
145 break;
146 }
147 if value >= 0 {
148 result.insert(value as u32);
149 }
150 } else {
151 queue.push_back((start + bit * next_node_size, depth + 1));
152 }
153 bits &= !(1 << bit);
154 }
155 }
156 Ok((result, bits_in.bytes_consumed()))
157}
158
159fn tree_height(branch_factor: u64, max_value: u64) -> u32 {
161 let mut height = 1;
162 let mut capacity = branch_factor;
163 while capacity <= max_value {
164 capacity *= branch_factor;
165 height += 1;
166 }
167 height
168}
169
170struct OutputBits {
171 branch_factor: u32,
172 data: Vec<u8>,
173 sub_index: u32,
174}
175
176impl OutputBits {
177 fn write(&mut self, value: u32) {
178 match self.branch_factor {
179 2 | 4 => {
180 let value = value & ((1 << self.branch_factor) - 1);
181 if self.sub_index == 0 {
182 self.data.push(0);
183 }
184 if let Some(last) = self.data.last_mut() {
185 *last |= (value << self.sub_index) as u8;
186 }
187 self.sub_index += self.branch_factor;
188 if self.sub_index >= 8 {
189 self.sub_index = 0;
190 }
191 }
192 8 => self.data.push(value as u8),
193 _ => self.data.extend_from_slice(&value.to_le_bytes()),
194 }
195 }
196}
197
198fn encode_with(values: &[u64], branch_factor: u32, height: u32) -> Vec<u8> {
199 let bf = branch_factor as u64;
200 let mut layers: Vec<BTreeMap<u64, u32>> = vec![BTreeMap::new()];
202 for &v in values {
203 *layers[0].entry(v / bf).or_default() |= 1 << (v % bf);
204 }
205 for _ in 1..height {
206 let mut layer = BTreeMap::new();
207 for &node in layers[layers.len() - 1].keys() {
208 *layer.entry(node / bf).or_default() |= 1 << (node % bf);
209 }
210 layers.push(layer);
211 }
212 let range_count = |lo: u64, hi: u64| {
213 values.partition_point(|&v| v <= hi) - values.partition_point(|&v| v < lo)
214 };
215 let mut out = OutputBits {
216 branch_factor,
217 data: Vec::new(),
218 sub_index: 0,
219 };
220 let mut queue: VecDeque<(u64, u32, u64, u64)> = VecDeque::from([(0, 0, 0, bf.pow(height) - 1)]);
221 while let Some((node, depth, start, end)) = queue.pop_front() {
222 let layer = (height - 1 - depth) as usize;
223 let bitmask = layers
224 .get(layer)
225 .and_then(|l| l.get(&node))
226 .copied()
227 .unwrap_or(0);
228 if depth + 1 < height && range_count(start, end) as u64 == end - start + 1 {
230 out.write(0);
231 continue;
232 }
233 out.write(bitmask);
234 if bitmask != 0 && depth + 1 < height {
235 let child_size = (end - start + 1) / bf;
236 let mut bits = bitmask;
237 while bits != 0 {
238 let bit = bits.trailing_zeros() as u64;
239 let child_start = start + bit * child_size;
240 queue.push_back((
241 node * bf + bit,
242 depth + 1,
243 child_start,
244 child_start + child_size - 1,
245 ));
246 bits &= !(1 << bit);
247 }
248 }
249 }
250 let mut data = vec![encode_header(branch_factor, height)];
251 data.extend(out.data);
252 data
253}
254
255pub fn encode(values: impl IntoIterator<Item = u64>) -> Result<Vec<u8>, String> {
259 let values: Vec<u64> = values
260 .into_iter()
261 .collect::<BTreeSet<_>>()
262 .into_iter()
263 .collect();
264 let Some(&max_value) = values.last() else {
265 return Ok(vec![encode_header(2, 0)]);
266 };
267 let mut best: Option<Vec<u8>> = None;
268 for branch_factor in [2, 4, 8, 32] {
269 let height = tree_height(branch_factor as u64, max_value);
270 if height > max_height(branch_factor) {
271 continue;
272 }
273 let encoded = encode_with(&values, branch_factor, height);
274 if best.as_ref().is_none_or(|b| encoded.len() < b.len()) {
275 best = Some(encoded);
276 }
277 }
278 best.ok_or_else(|| format!("Cannot encode max value {max_value}"))
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 const MAX: i64 = 0xFFFF_FFFF;
286
287 fn round_trip(values: &[u64]) -> Result<(), String> {
288 let encoded = encode(values.iter().copied())?;
289 let (decoded, consumed) = decode(&encoded, 0, MAX).map_err(|e| e.0)?;
290 let expected: BTreeSet<u32> = values.iter().map(|&v| v as u32).collect();
291 assert_eq!(decoded, expected);
292 assert_eq!(consumed, encoded.len());
293 Ok(())
294 }
295
296 #[test]
298 fn round_trips() -> Result<(), String> {
299 round_trip(&[])?;
300 round_trip(&[42])?;
301 round_trip(&[1, 10, 100, 1000])?;
302 round_trip(&[1, 1_000_000])?;
303 round_trip(&(8..16).collect::<Vec<_>>())?;
304 let almost: Vec<u64> = (0..64).filter(|&v| v != 32).collect();
305 round_trip(&almost)?;
306 let range: Vec<u64> = (100..1100).collect();
307 round_trip(&range)?;
308 assert!(encode(range)?.len() < 50);
309 Ok(())
310 }
311
312 #[test]
313 fn encodings_match_fonttools() -> Result<(), String> {
314 let hex = |values: Vec<u64>| -> Result<String, String> {
315 Ok(encode(values)?.iter().map(|b| format!("{b:02x}")).collect())
316 };
317 assert_eq!(hex(vec![0])?, "0401");
318 assert_eq!(hex(vec![5])?, "0c26");
319 assert_eq!(hex(vec![1, 10, 100, 1000])?, "28676e5a9d655956");
320 assert_eq!(hex((100..1100).collect())?, "2cdf34c9d2cd4200");
321 assert_eq!(hex(vec![1, 1_000_000])?, "5067666555555665555519");
322 assert_eq!(hex((0..64).step_by(3).collect())?, "0aff4992244992244992");
323 assert_eq!(hex(vec![0x10FFFF])?, "5456a9aaaaaa02");
324 assert_eq!(hex(vec![7, 8, 9, 31, 32, 33, 1023])?, "1519786818888383");
325 Ok(())
326 }
327
328 #[test]
329 fn decoding() -> Result<(), DecodeError> {
330 assert_eq!(decode(b"\x04\x01", 100, MAX)?, (BTreeSet::from([100]), 2));
331 assert_eq!(decode(b"\x04\x01", -1, MAX)?, (BTreeSet::new(), 2));
332 assert_eq!(decode(b"\x00", 0, MAX)?, (BTreeSet::new(), 1));
333 assert!(decode(b"", 0, MAX).is_err());
334 assert!(decode(b"\x04", 0, MAX).is_err());
335 assert!(decode(&[(8 << 2) | 3], 0, MAX).is_err());
336 assert!(encode([1u64 << 35]).is_err());
337 Ok(())
338 }
339
340 #[test]
341 fn max_value_truncates() -> Result<(), String> {
342 let decode = |values: Vec<u64>, max: i64| -> Result<BTreeSet<u32>, String> {
343 let encoded = encode(values)?;
344 Ok(decode(&encoded, 0, max).map_err(|e| e.0)?.0)
345 };
346 assert_eq!(decode(vec![1, 2, 10, 20], 15)?, BTreeSet::from([1, 2, 10]));
347 assert_eq!(decode((0..100).collect(), 49)?, (0..50).collect());
348 assert_eq!(decode(vec![100, 200, 300], 50)?, BTreeSet::new());
349 Ok(())
350 }
351}