1use zu_common::{Result, ZuError};
24
25use crate::bitpack::{CHUNK, packed_bytes};
26use crate::counts;
27use crate::delta::zigzag;
28use crate::{
29 EncodingId, bits_needed, bool_bitpack, delta, delta_patch, dict, for_bitpack, frequency, rle,
30};
31
32pub fn encode_auto(values: &[u64], out: &mut Vec<u8>) -> EncodingId {
34 let id = choose(values);
35 let start = out.len();
36 out.push(id as u8);
37 encode_with(id, values, out);
38 if out.len() - start > 9 + values.len() * 8 {
40 out.truncate(start);
41 out.push(EncodingId::Plain as u8);
42 encode_with(EncodingId::Plain, values, out);
43 return EncodingId::Plain;
44 }
45 id
46}
47
48pub fn decode_any(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
56 let corrupt = |detail: &str| ZuError::Corrupt {
57 what: "segment",
58 detail: detail.to_string(),
59 };
60 let (&id, payload) = bytes.split_first().ok_or_else(|| corrupt("empty"))?;
61 match EncodingId::try_from(id)? {
62 EncodingId::Plain => decode_plain(payload, max_values, out),
63 EncodingId::Constant => decode_constant(payload, max_values, out),
64 EncodingId::Rle => rle::decode(payload, max_values, out),
65 EncodingId::Dict => dict::decode(payload, max_values, out),
66 EncodingId::ForBitPack => for_bitpack::decode(payload, max_values, out),
67 EncodingId::DeltaBitPack => delta::decode(payload, max_values, out),
68 EncodingId::DeltaPatch => delta_patch::decode(payload, max_values, out),
69 EncodingId::BoolBitpack => bool_bitpack::decode(payload, max_values, out),
70 EncodingId::Frequency => frequency::decode(payload, max_values, out),
71 other => Err(ZuError::Unsupported {
72 what: "segment encoding",
73 id: other as u8 as u32,
74 }),
75 }
76}
77
78fn encode_with(id: EncodingId, values: &[u64], out: &mut Vec<u8>) {
79 match id {
80 EncodingId::Plain => encode_plain(values, out),
81 EncodingId::Constant => encode_constant(values, out),
82 EncodingId::Rle => {
83 rle::encode(values, out);
84 }
85 EncodingId::Dict => {
86 dict::encode(values, out);
87 }
88 EncodingId::ForBitPack => {
89 for_bitpack::encode(values, out);
90 }
91 EncodingId::DeltaBitPack => {
92 delta::encode(values, out);
93 }
94 EncodingId::DeltaPatch => {
95 delta_patch::encode(values, out);
96 }
97 EncodingId::BoolBitpack => {
98 bool_bitpack::encode(values, out);
99 }
100 EncodingId::Frequency => {
101 frequency::encode(values, out);
102 }
103 _ => unreachable!("choose never returns other ids"),
104 }
105}
106
107fn choose(values: &[u64]) -> EncodingId {
108 if values.is_empty() {
109 return EncodingId::Plain;
110 }
111 let shape = Shape::read(values);
112 if shape.constant {
113 return EncodingId::Constant;
114 }
115 let mut best = EncodingId::Plain;
120 let mut best_size = 4 + values.len() * 8;
121 let candidates = [
122 EncodingId::BoolBitpack,
123 EncodingId::ForBitPack,
124 EncodingId::DeltaBitPack,
125 EncodingId::DeltaPatch,
126 EncodingId::Rle,
127 EncodingId::Dict,
128 EncodingId::Frequency,
129 ];
130 for id in candidates {
131 let Some(size) = shape.price(id) else {
132 continue;
133 };
134 if size < best_size {
135 best = id;
136 best_size = size;
137 }
138 }
139 best
140}
141
142struct Shape {
153 len: usize,
154 min: u64,
155 max: u64,
156 constant: bool,
158 binary: bool,
160 for_bytes: usize,
162 delta_bytes: usize,
165 patch_bytes: usize,
168 runs: usize,
169 run_len_min: u64,
170 run_len_max: u64,
171 distinct: Option<usize>,
174 top_count: usize,
177}
178
179impl Shape {
180 fn read(values: &[u64]) -> Shape {
181 let mut shape = Shape {
182 len: values.len(),
183 min: u64::MAX,
184 max: 0,
185 constant: true,
186 binary: true,
187 for_bytes: 4,
188 delta_bytes: 4,
189 patch_bytes: 4,
190 runs: 0,
191 run_len_min: u64::MAX,
192 run_len_max: 0,
193 distinct: None,
194 top_count: 0,
195 };
196 let first = values[0];
197 let mut prev = first;
201 let mut run = 0u64;
202 for block in values.chunks(CHUNK) {
203 let (mut bmin, mut bmax) = (u64::MAX, 0u64);
204 let (mut dmin, mut dmax) = (u64::MAX, 0u64);
205 let mut hist = [0usize; 65];
206 let mut wide = 0u32;
207 for &v in block {
208 bmin = bmin.min(v);
209 bmax = bmax.max(v);
210 shape.constant &= v == first;
211 shape.binary &= v <= 1;
212 let zz = zigzag(v.wrapping_sub(prev) as i64);
213 dmin = dmin.min(zz);
214 dmax = dmax.max(zz);
215 let width = bits_needed(zz);
216 hist[width as usize] += 1;
217 wide = wide.max(width);
218 if v == prev && run > 0 {
219 run += 1;
220 } else {
221 shape.close_run(run);
222 run = 1;
223 }
224 prev = v;
225 }
226 shape.min = shape.min.min(bmin);
227 shape.max = shape.max.max(bmax);
228 shape.for_bytes += 9 + packed_bytes(bits_needed(bmax - bmin), block.len());
229 shape.delta_bytes += 9 + packed_bytes(bits_needed(dmax - dmin), block.len());
230 shape.patch_bytes += 2 + patch_body(&hist, wide, block.len());
231 }
232 shape.close_run(run);
233 let counts = counts::count(values, dict::MAX_ENTRIES);
237 shape.distinct = counts.distinct;
238 shape.top_count = counts.top_count;
239 shape
240 }
241
242 fn close_run(&mut self, len: u64) {
243 if len > 0 {
244 self.runs += 1;
245 self.run_len_min = self.run_len_min.min(len);
246 self.run_len_max = self.run_len_max.max(len);
247 }
248 }
249
250 fn price(&self, id: EncodingId) -> Option<usize> {
253 let spread = self.max - self.min;
254 match id {
255 EncodingId::BoolBitpack => self.binary.then(|| 4 + self.len.div_ceil(8)),
256 EncodingId::ForBitPack => Some(self.for_bytes),
257 EncodingId::DeltaBitPack => Some(8 + self.delta_bytes),
258 EncodingId::DeltaPatch => Some(8 + self.patch_bytes),
259 EncodingId::Rle => Some(
260 8 + for_bytes(self.runs, bits_needed(spread))
261 + for_bytes(self.runs, bits_needed(self.run_len_max - self.run_len_min)),
262 ),
263 EncodingId::Dict => self.distinct.map(|d| {
264 4 + for_bytes(d, bits_needed(spread))
265 + for_bytes(self.len, bits_needed(d.saturating_sub(1) as u64))
266 }),
267 EncodingId::Frequency => {
268 let exceptions = self.len - self.top_count;
269 Some(
270 16 + for_bytes(exceptions, bits_needed(self.len as u64))
271 + for_bytes(exceptions, bits_needed(spread)),
272 )
273 }
274 _ => None,
275 }
276 }
277}
278
279fn for_bytes(count: usize, width: u32) -> usize {
282 4 + count.div_ceil(CHUNK) * 9 + packed_bytes(width, count)
283}
284
285fn patch_body(hist: &[usize; 65], wide: u32, take: usize) -> usize {
289 let mut best = packed_bytes(wide, take) + packed_bytes(1, take);
290 let mut exceptions = 0usize;
291 for width in (0..wide).rev() {
292 exceptions += hist[width as usize + 1];
293 let cost =
294 packed_bytes(width, take) + packed_bytes(1, take) + packed_bytes(wide, exceptions);
295 best = best.min(cost);
296 }
297 best
298}
299
300fn encode_plain(values: &[u64], out: &mut Vec<u8>) {
301 out.extend_from_slice(&(values.len() as u32).to_le_bytes());
302 for v in values {
303 out.extend_from_slice(&v.to_le_bytes());
304 }
305}
306
307fn decode_plain(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
308 let corrupt = |detail: &str| ZuError::Corrupt {
309 what: "plain",
310 detail: detail.to_string(),
311 };
312 let count = u32::from_le_bytes(
313 bytes
314 .get(..4)
315 .ok_or_else(|| corrupt("truncated count"))?
316 .try_into()
317 .unwrap(),
318 ) as usize;
319 if count > max_values {
320 return Err(corrupt("count above the caller ceiling"));
321 }
322 let body = bytes
323 .get(4..4 + count * 8)
324 .ok_or_else(|| corrupt("truncated body"))?;
325 out.reserve(count);
326 out.extend(
327 body.as_chunks::<8>()
328 .0
329 .iter()
330 .map(|c| u64::from_le_bytes(*c)),
331 );
332 Ok(())
333}
334
335fn encode_constant(values: &[u64], out: &mut Vec<u8>) {
336 out.extend_from_slice(&(values.len() as u32).to_le_bytes());
337 out.extend_from_slice(&values[0].to_le_bytes());
338}
339
340fn decode_constant(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
341 let corrupt = |detail: &str| ZuError::Corrupt {
342 what: "constant",
343 detail: detail.to_string(),
344 };
345 let body = bytes.get(..12).ok_or_else(|| corrupt("truncated"))?;
346 let count = u32::from_le_bytes(body[..4].try_into().unwrap()) as usize;
347 if count > max_values {
350 return Err(corrupt("count above the caller ceiling"));
351 }
352 let value = u64::from_le_bytes(body[4..12].try_into().unwrap());
353 out.extend(std::iter::repeat_n(value, count));
354 Ok(())
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360
361 fn roundtrip(values: &[u64]) -> EncodingId {
362 let mut buf = Vec::new();
363 let id = encode_auto(values, &mut buf);
364 let mut out = Vec::new();
365 decode_any(&buf, values.len(), &mut out).unwrap();
366 assert_eq!(values, out.as_slice());
367 id
368 }
369
370 #[test]
371 fn picks_constant() {
372 assert_eq!(roundtrip(&vec![9u64; 5000]), EncodingId::Constant);
373 }
374
375 #[test]
376 fn picks_delta_for_sorted() {
377 let values: Vec<u64> = (0..10_000u64).map(|i| 1_000_000 + i * 3).collect();
378 assert_eq!(roundtrip(&values), EncodingId::DeltaBitPack);
379 }
380
381 #[test]
382 fn picks_delta_patch_for_adjacency() {
383 let mut rng = 0x2545F4914F6CDD1Du64;
388 let mut values = Vec::new();
389 for list in 0..2_000u64 {
390 let anchor = (list.wrapping_mul(0x9E3779B97F4A7C15) % 4_000_000).max(1);
391 values.push(anchor % 1000);
392 let mut v = anchor;
393 for _ in 0..13 {
394 rng ^= rng << 13;
395 rng ^= rng >> 7;
396 rng ^= rng << 17;
397 v += 1 + rng % 30;
398 values.push(v);
399 }
400 }
401 assert_eq!(roundtrip(&values), EncodingId::DeltaPatch);
402 }
403
404 #[test]
405 fn picks_for_on_small_range_noise() {
406 let mut rng = 0xABCDEFu64;
407 let values: Vec<u64> = (0..10_000)
408 .map(|_| {
409 rng ^= rng << 13;
410 rng ^= rng >> 7;
411 rng ^= rng << 17;
412 5_000_000 + rng % 1000
413 })
414 .collect();
415 assert_eq!(roundtrip(&values), EncodingId::ForBitPack);
416 }
417
418 #[test]
419 fn picks_rle_for_runs() {
420 let mut values = Vec::new();
421 for run in 0..40u64 {
422 values.extend(std::iter::repeat_n(run * 1_000_000_007, 500));
423 }
424 assert_eq!(roundtrip(&values), EncodingId::Rle);
425 }
426
427 #[test]
428 fn picks_dict_for_scattered_low_cardinality() {
429 let pool: Vec<u64> = (0..16u64)
430 .map(|i| i.wrapping_mul(0x9E3779B97F4A7C15))
431 .collect();
432 let values: Vec<u64> = (0..10_000).map(|i| pool[(i * 7) % pool.len()]).collect();
433 assert_eq!(roundtrip(&values), EncodingId::Dict);
434 }
435
436 #[test]
437 fn picks_bool_for_binary() {
438 let values: Vec<u64> = (0..10_000u64).map(|i| (i * i / 7) & 1).collect();
441 assert_eq!(roundtrip(&values), EncodingId::BoolBitpack);
442 }
443
444 #[test]
445 fn bool_never_picked_when_a_single_value_is_wider() {
446 let mut values: Vec<u64> = (0..10_000u64).map(|i| i & 1).collect();
450 values[9_999] = 2;
451 let id = roundtrip(&values);
452 assert_ne!(id, EncodingId::BoolBitpack);
453 }
454
455 #[test]
456 fn dict_never_offered_past_the_distinct_cap() {
457 let values: Vec<u64> = (0..40_000usize)
464 .map(|i| {
465 let pool = (i / 64 * 16 + (i * 7) % 16) as u64;
466 pool.wrapping_mul(0x9E37_79B9_7F4A_7C15)
467 })
468 .collect();
469 let mut buf = Vec::new();
470 let id = encode_auto(&values, &mut buf);
471 assert_ne!(id, EncodingId::Dict);
472 let mut out = Vec::new();
473 decode_any(&buf, values.len(), &mut out).unwrap();
474 assert_eq!(values, out);
475 }
476
477 #[test]
478 fn picks_frequency_for_dominant_scattered() {
479 let mut rng = 0x9E3779B97F4A7C15u64;
483 let values: Vec<u64> = (0..10_000)
484 .map(|i| {
485 rng ^= rng << 13;
486 rng ^= rng >> 7;
487 rng ^= rng << 17;
488 if i % 10 == 3 { rng } else { 777 }
489 })
490 .collect();
491 assert_eq!(roundtrip(&values), EncodingId::Frequency);
492 }
493
494 #[test]
495 fn random_wide_data_stays_decodable() {
496 let mut rng = 0x123456789u64;
497 let values: Vec<u64> = (0..5000)
498 .map(|_| {
499 rng ^= rng << 13;
500 rng ^= rng >> 7;
501 rng ^= rng << 17;
502 rng
503 })
504 .collect();
505 roundtrip(&values);
506 }
507
508 #[test]
509 fn empty_input() {
510 assert_eq!(roundtrip(&[]), EncodingId::Plain);
511 }
512
513 #[test]
514 fn unknown_id_rejected() {
515 let mut out = Vec::new();
516 assert!(decode_any(&[200, 0, 0], 16, &mut out).is_err());
517 assert!(decode_any(&[], 16, &mut out).is_err());
518 assert!(decode_any(&[8, 1, 2], 16, &mut out).is_err());
521 }
522
523 #[test]
524 fn fuzzer_found_constant_flood_rejected() {
525 let bytes = [1, 208, 7, 246, 255, 88, 42, 0, 0, 0, 0, 16, 0, 0];
530 let mut out = Vec::new();
531 assert!(decode_any(&bytes, 2048, &mut out).is_err());
532 assert!(out.is_empty());
533 }
534}