1use rudb_common::{Error, Result};
45
46use crate::chooser::{Chooser, EXHAUSTIVE};
47use crate::reader::Reader;
48
49use crate::bitpack::{self, VALUES};
50
51const MAX_DEPTH: u8 = 3;
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum Kind {
63 Constant = 0,
65 Packed = 1,
68 Delta = 2,
71 Rle = 3,
73 Dict = 4,
76 Sparse = 5,
78 Strided = 6,
81}
82
83impl Kind {
84 fn tag(self) -> u8 {
85 self as u8
86 }
87
88 fn from_tag(tag: u8) -> Result<Self> {
89 match tag {
90 0 => Ok(Self::Constant),
91 1 => Ok(Self::Packed),
92 2 => Ok(Self::Delta),
93 3 => Ok(Self::Rle),
94 4 => Ok(Self::Dict),
95 5 => Ok(Self::Sparse),
96 6 => Ok(Self::Strided),
97 other => Err(Error::internal(format!("unknown encoding tag {other}"))),
98 }
99 }
100
101 #[must_use]
103 pub fn name(self) -> &'static str {
104 match self {
105 Self::Constant => "CONSTANT",
106 Self::Packed => "FOR+BITPACK",
107 Self::Delta => "DELTA",
108 Self::Rle => "RLE",
109 Self::Dict => "DICT",
110 Self::Sparse => "SPARSE",
111 Self::Strided => "STRIDE",
112 }
113 }
114}
115
116pub fn encode(values: &[i64]) -> Result<Vec<u8>> {
123 encode_with(values, &EXHAUSTIVE)
124}
125
126pub fn encode_with(values: &[i64], chooser: &dyn Chooser) -> Result<Vec<u8>> {
136 encode_at(values, 0, chooser)
137}
138
139pub fn decode(bytes: &[u8]) -> Result<Vec<i64>> {
146 let mut reader = Reader::new(bytes);
147 let values = with_decoding(|scratch| decode_chunk(&mut reader, scratch))?;
148 if reader.remaining() != 0 {
149 return Err(Error::internal(format!(
150 "{} bytes left over after decoding a chunk",
151 reader.remaining()
152 )));
153 }
154 Ok(values)
155}
156
157pub fn decode_prefix(bytes: &[u8]) -> Result<(Vec<i64>, usize)> {
167 let mut reader = Reader::new(bytes);
168 let values = with_decoding(|scratch| decode_chunk(&mut reader, scratch))?;
169 Ok((values, reader.used()))
170}
171
172pub fn describe_prefix(bytes: &[u8]) -> Result<(String, usize)> {
178 let mut reader = Reader::new(bytes);
179 let text = describe_chunk(&mut reader)?;
180 Ok((text, reader.used()))
181}
182
183pub fn candidate_sizes(values: &[i64]) -> Result<Vec<(Kind, usize)>> {
190 let mut sizes = Vec::new();
191 for kind in candidates(values, 0) {
192 if let Some(bytes) = encode_as(kind, values, 0, &EXHAUSTIVE)? {
193 sizes.push((kind, bytes.len()));
194 }
195 }
196 Ok(sizes)
197}
198
199#[must_use]
206pub fn offered(values: &[i64]) -> Vec<Kind> {
207 candidates(values, 0)
208}
209
210pub fn encode_only(kind: Kind, values: &[i64]) -> Result<Option<Vec<u8>>> {
221 encode_as(kind, values, 0, &EXHAUSTIVE)
222}
223
224pub(crate) fn size_as(kind: Kind, values: &[i64], depth: u8) -> Result<Option<usize>> {
229 Ok(encode_as(kind, values, depth, &EXHAUSTIVE)?.map(|bytes| bytes.len()))
230}
231
232pub fn describe(bytes: &[u8]) -> Result<String> {
238 let mut reader = Reader::new(bytes);
239 describe_chunk(&mut reader)
240}
241
242fn encode_at(values: &[i64], depth: u8, chooser: &dyn Chooser) -> Result<Vec<u8>> {
243 let offered = candidates(values, depth);
244 let mut best: Option<Vec<u8>> = None;
245 for kind in chooser.narrow_integers(values, &offered, depth) {
246 let Some(bytes) = encode_as(kind, values, depth, chooser)? else {
247 continue;
248 };
249 if best.as_ref().is_none_or(|current| bytes.len() < current.len()) {
250 best = Some(bytes);
251 }
252 }
253 best.ok_or_else(|| Error::internal("no encoding applied to the chunk"))
256}
257
258fn candidates(values: &[i64], depth: u8) -> Vec<Kind> {
265 let mut kinds = vec![Kind::Packed];
266 if depth >= MAX_DEPTH || values.is_empty() {
267 return kinds;
268 }
269 if values.iter().all(|value| *value == values[0]) {
270 return vec![Kind::Constant];
272 }
273 if values.len() >= 2 && deltas_fit(values) {
274 kinds.push(Kind::Delta);
275 }
276 if run_count(values) * 4 <= values.len() * 3 {
277 kinds.push(Kind::Rle);
278 }
279 let (distinct, dominant) = spread_of(values);
283 if distinct * 2 <= values.len() {
284 kinds.push(Kind::Dict);
285 }
286 match dominant {
289 Some((_, count)) if count * 10 >= values.len() * 8 => kinds.push(Kind::Sparse),
290 _ => {}
291 }
292 if stride_of(values).is_some() {
293 kinds.push(Kind::Strided);
294 }
295 kinds
296}
297
298fn encode_as(
301 kind: Kind,
302 values: &[i64],
303 depth: u8,
304 chooser: &dyn Chooser,
305) -> Result<Option<Vec<u8>>> {
306 let mut out = Vec::new();
307 put_u8(&mut out, kind.tag());
308 put_u32(&mut out, u32::try_from(values.len()).map_err(|_| too_long(values.len()))?);
309 match kind {
310 Kind::Constant => {
311 let Some(first) = values.first() else {
312 return Ok(None);
313 };
314 if values.iter().any(|value| value != first) {
315 return Ok(None);
316 }
317 put_i64(&mut out, *first);
318 }
319 Kind::Packed => encode_packed(values, &mut out)?,
320 Kind::Delta => {
321 let (Some(first), Some(deltas)) = (values.first(), deltas(values)) else {
325 return Ok(None);
326 };
327 put_i64(&mut out, *first);
328 out.extend_from_slice(&encode_at(&deltas, depth + 1, chooser)?);
329 }
330 Kind::Rle => {
331 let (run_values, run_lengths) = runs(values);
332 if run_values.is_empty() {
333 return Ok(None);
334 }
335 out.extend_from_slice(&encode_at(&run_values, depth + 1, chooser)?);
336 out.extend_from_slice(&encode_at(&run_lengths, depth + 1, chooser)?);
337 }
338 Kind::Dict => {
339 let dictionary = distinct_values(values);
340 if dictionary.is_empty() {
341 return Ok(None);
342 }
343 let codes = codes_over(values, &dictionary);
344 out.extend_from_slice(&encode_at(&dictionary, depth + 1, chooser)?);
345 out.extend_from_slice(&encode_at(&codes, depth + 1, chooser)?);
346 }
347 Kind::Sparse => {
348 let Some((value, _)) = spread_of(values).1 else {
349 return Ok(None);
350 };
351 let mut positions = Vec::new();
352 let mut exceptions = Vec::new();
353 for (index, other) in values.iter().enumerate() {
354 if *other != value {
355 positions.push(index as i64);
356 exceptions.push(*other);
357 }
358 }
359 put_i64(&mut out, value);
360 put_u32(
361 &mut out,
362 u32::try_from(positions.len()).map_err(|_| too_long(positions.len()))?,
363 );
364 out.extend_from_slice(&encode_at(&positions, depth + 1, chooser)?);
365 out.extend_from_slice(&encode_at(&exceptions, depth + 1, chooser)?);
366 }
367 Kind::Strided => {
368 let (Some(base), Some(stride)) = (values.iter().min().copied(), stride_of(values))
369 else {
370 return Ok(None);
371 };
372 let mut steps = Vec::with_capacity(values.len());
373 for value in values {
374 let step = offset_from(*value, base) / stride;
375 let Ok(step) = i64::try_from(step) else {
380 return Ok(None);
381 };
382 steps.push(step);
383 }
384 put_i64(&mut out, base);
385 put_u64(&mut out, stride);
386 out.extend_from_slice(&encode_at(&steps, depth + 1, chooser)?);
387 }
388 }
389 Ok(Some(out))
390}
391
392fn encode_packed(values: &[i64], out: &mut Vec<u8>) -> Result<()> {
404 let mut offsets: Vec<u64> = Vec::with_capacity(VALUES);
408 let mut packed: Vec<u64> = vec![0; bitpack::packed_len::<u64>(64)];
411 let mut transposed = bitpack::Scratch::<u64>::new();
412 for unit in values.chunks(VALUES) {
413 let base = unit.iter().copied().min().unwrap_or(0);
414 offsets.clear();
415 offsets.extend(unit.iter().map(|value| offset_from(*value, base)));
416 let width = bitpack::required_width(&offsets);
417 put_i64(out, base);
418 put_u8(out, u8::try_from(width).map_err(|_| Error::internal("impossible width"))?);
419 if unit.len() == VALUES {
420 let words = bitpack::packed_len::<u64>(width);
421 bitpack::pack_with(&offsets, width, &mut packed[..words], &mut transposed)?;
422 for word in &packed[..words] {
423 put_u64(out, *word);
424 }
425 } else {
426 bitpack::pack_tail(&offsets, width, out)?;
427 }
428 }
429 Ok(())
430}
431
432struct Decoding {
455 packed: Vec<u64>,
458 unit: Vec<u64>,
460}
461
462thread_local! {
463 static DECODING: std::cell::RefCell<Decoding> =
465 const { std::cell::RefCell::new(Decoding::new()) };
466}
467
468fn with_decoding<T>(run: impl FnOnce(&mut Decoding) -> T) -> T {
475 DECODING.with(|cell| match cell.try_borrow_mut() {
476 Ok(mut scratch) => run(&mut scratch),
477 Err(_) => run(&mut Decoding::new()),
478 })
479}
480
481impl Decoding {
482 const fn new() -> Self {
484 Self { packed: Vec::new(), unit: Vec::new() }
485 }
486
487 fn ready(&mut self) {
489 if self.unit.len() != VALUES {
490 self.unit.resize(VALUES, 0);
491 self.packed.resize(bitpack::packed_len::<u64>(64), 0);
492 }
493 }
494}
495
496fn decode_chunk(reader: &mut Reader<'_>, scratch: &mut Decoding) -> Result<Vec<i64>> {
497 let kind = Kind::from_tag(reader.u8()?)?;
498 let count = reader.u32()? as usize;
499 match kind {
500 Kind::Constant => Ok(vec![reader.i64()?; count]),
501 Kind::Packed => {
502 let mut values = Vec::with_capacity(count);
503 scratch.ready();
504 while values.len() < count {
505 let base = reader.i64()?;
506 let width = reader.u8()? as usize;
507 let wanted = (count - values.len()).min(VALUES);
508 if wanted == VALUES {
509 let words = bitpack::packed_len::<u64>(width);
510 for word in &mut scratch.packed[..words] {
511 *word = reader.u64()?;
512 }
513 bitpack::unpack(&scratch.packed[..words], width, &mut scratch.unit)?;
514 values.extend(scratch.unit.iter().map(|offset| value_from(*offset, base)));
515 } else {
516 let bytes = reader.bytes(bitpack::tail_len(wanted, width))?;
517 let unit = bitpack::unpack_tail(bytes, width, wanted)?;
518 values.extend(unit.iter().map(|offset| value_from(*offset, base)));
519 }
520 }
521 Ok(values)
522 }
523 Kind::Delta => {
524 let first = reader.i64()?;
525 let deltas = decode_chunk(reader, scratch)?;
526 let mut values = Vec::with_capacity(count);
527 values.push(first);
528 let mut current = first;
529 for delta in deltas {
530 current = current.wrapping_add(unzigzag(delta as u64));
531 values.push(current);
532 }
533 check_count(values.len(), count)?;
534 Ok(values)
535 }
536 Kind::Rle => {
537 let run_values = decode_chunk(reader, scratch)?;
538 let run_lengths = decode_chunk(reader, scratch)?;
539 if run_values.len() != run_lengths.len() {
540 return Err(Error::internal("an RLE chunk has more runs than run lengths"));
541 }
542 let mut values = Vec::with_capacity(count);
543 for (value, length) in run_values.into_iter().zip(run_lengths) {
544 let length = usize::try_from(length)
545 .map_err(|_| Error::internal("a negative RLE run length"))?;
546 values.extend(std::iter::repeat_n(value, length));
547 }
548 check_count(values.len(), count)?;
549 Ok(values)
550 }
551 Kind::Dict => {
552 let dictionary = decode_chunk(reader, scratch)?;
553 let codes = decode_chunk(reader, scratch)?;
554 let mut values = Vec::with_capacity(count);
555 for code in codes {
556 let index =
557 usize::try_from(code).ok().and_then(|index| dictionary.get(index)).ok_or_else(
558 || Error::internal(format!("code {code} is not in the dictionary")),
559 )?;
560 values.push(*index);
561 }
562 check_count(values.len(), count)?;
563 Ok(values)
564 }
565 Kind::Sparse => {
566 let value = reader.i64()?;
567 let exception_count = reader.u32()? as usize;
568 let positions = decode_chunk(reader, scratch)?;
569 let exceptions = decode_chunk(reader, scratch)?;
570 if positions.len() != exception_count || exceptions.len() != exception_count {
571 return Err(Error::internal("a sparse chunk disagrees about its exception count"));
572 }
573 let mut values = vec![value; count];
574 for (position, exception) in positions.into_iter().zip(exceptions) {
575 let position = usize::try_from(position)
576 .ok()
577 .filter(|position| *position < count)
578 .ok_or_else(|| {
579 Error::internal(format!("exception at {position} is outside the chunk"))
580 })?;
581 values[position] = exception;
582 }
583 Ok(values)
584 }
585 Kind::Strided => {
586 let base = reader.i64()?;
587 let stride = reader.u64()?;
588 let steps = decode_chunk(reader, scratch)?;
589 check_count(steps.len(), count)?;
590 let mut values = Vec::with_capacity(count);
591 for step in steps {
592 let step = u64::try_from(step)
593 .map_err(|_| Error::internal("a negative number of strides"))?;
594 values.push(value_from(step.wrapping_mul(stride), base));
595 }
596 Ok(values)
597 }
598 }
599}
600
601fn describe_chunk(reader: &mut Reader<'_>) -> Result<String> {
602 let kind = Kind::from_tag(reader.u8()?)?;
603 let count = reader.u32()? as usize;
604 Ok(match kind {
605 Kind::Constant => {
606 reader.i64()?;
607 "CONSTANT".to_string()
608 }
609 Kind::Packed => {
610 let mut widths = Vec::new();
611 let mut seen = 0;
612 while seen < count {
613 reader.i64()?;
614 let width = reader.u8()? as usize;
615 let wanted = (count - seen).min(VALUES);
616 if wanted == VALUES {
617 for _ in 0..bitpack::packed_len::<u64>(width) {
618 reader.u64()?;
619 }
620 } else {
621 reader.bytes(bitpack::tail_len(wanted, width))?;
622 }
623 widths.push(width);
624 seen += wanted;
625 }
626 let low = widths.iter().copied().min().unwrap_or(0);
627 let high = widths.iter().copied().max().unwrap_or(0);
628 if low == high {
631 format!("FOR+BITPACK[{low}]")
632 } else {
633 format!("FOR+BITPACK[{low}..{high}]")
634 }
635 }
636 Kind::Delta => {
637 reader.i64()?;
638 format!("DELTA({})", describe_chunk(reader)?)
639 }
640 Kind::Rle => {
641 let values = describe_chunk(reader)?;
642 let lengths = describe_chunk(reader)?;
643 format!("RLE({values}, {lengths})")
644 }
645 Kind::Dict => {
646 let dictionary = describe_chunk(reader)?;
647 let codes = describe_chunk(reader)?;
648 format!("DICT({dictionary}, {codes})")
649 }
650 Kind::Sparse => {
651 reader.i64()?;
652 reader.u32()?;
653 let positions = describe_chunk(reader)?;
654 let exceptions = describe_chunk(reader)?;
655 format!("SPARSE({positions}, {exceptions})")
656 }
657 Kind::Strided => {
658 reader.i64()?;
659 let stride = reader.u64()?;
660 format!("STRIDE[{stride}]({})", describe_chunk(reader)?)
661 }
662 })
663}
664
665fn stride_of(values: &[i64]) -> Option<u64> {
677 let base = values.iter().min().copied()?;
678 let mut divisor = 0u64;
679 for value in values {
680 divisor = gcd(divisor, offset_from(*value, base));
681 if divisor == 1 {
682 return None;
683 }
684 }
685 (divisor > 1).then_some(divisor)
688}
689
690fn gcd(mut left: u64, mut right: u64) -> u64 {
692 if left == 0 {
693 return right;
694 }
695 if right == 0 {
696 return left;
697 }
698 let shift = (left | right).trailing_zeros();
699 left >>= left.trailing_zeros();
700 loop {
701 right >>= right.trailing_zeros();
702 if left > right {
703 std::mem::swap(&mut left, &mut right);
704 }
705 right -= left;
706 if right == 0 {
707 return left << shift;
708 }
709 }
710}
711
712fn offset_from(value: i64, base: i64) -> u64 {
715 (i128::from(value) - i128::from(base)) as u64
716}
717
718fn value_from(offset: u64, base: i64) -> i64 {
719 (i128::from(base) + i128::from(offset)) as i64
720}
721
722fn zigzag(value: i64) -> u64 {
725 ((value << 1) ^ (value >> 63)) as u64
726}
727
728fn unzigzag(value: u64) -> i64 {
729 ((value >> 1) as i64) ^ -((value & 1) as i64)
730}
731
732fn deltas_fit(values: &[i64]) -> bool {
744 values.windows(2).all(|pair| i64::try_from(i128::from(pair[1]) - i128::from(pair[0])).is_ok())
745}
746
747fn deltas(values: &[i64]) -> Option<Vec<i64>> {
748 let mut deltas = Vec::with_capacity(values.len().saturating_sub(1));
749 for pair in values.windows(2) {
750 let difference = i128::from(pair[1]) - i128::from(pair[0]);
751 let difference = i64::try_from(difference).ok()?;
752 deltas.push(zigzag(difference) as i64);
753 }
754 Some(deltas)
755}
756
757fn run_count(values: &[i64]) -> usize {
758 let mut runs = 0;
759 let mut previous = None;
760 for value in values {
761 if previous != Some(value) {
762 runs += 1;
763 previous = Some(value);
764 }
765 }
766 runs
767}
768
769fn runs(values: &[i64]) -> (Vec<i64>, Vec<i64>) {
770 let mut run_values: Vec<i64> = Vec::new();
771 let mut run_lengths: Vec<i64> = Vec::new();
772 for value in values {
773 if run_values.last() == Some(value) {
774 *run_lengths.last_mut().expect("a run length exists beside every run value") += 1;
775 } else {
776 run_values.push(*value);
777 run_lengths.push(1);
778 }
779 }
780 (run_values, run_lengths)
781}
782
783fn spread_of(values: &[i64]) -> (usize, Option<(i64, usize)>) {
798 let mut sorted = values.to_vec();
799 sorted.sort_unstable();
800 let mut distinct = 0;
801 let mut best: Option<(i64, usize)> = None;
802 let mut index = 0;
803 while index < sorted.len() {
804 let value = sorted[index];
805 let mut end = index;
806 while end < sorted.len() && sorted[end] == value {
807 end += 1;
808 }
809 distinct += 1;
810 let count = end - index;
811 if best.is_none_or(|(_, seen)| count > seen) {
812 best = Some((value, count));
813 }
814 index = end;
815 }
816 (distinct, best)
817}
818
819fn distinct_values(values: &[i64]) -> Vec<i64> {
822 let mut distinct = values.to_vec();
823 distinct.sort_unstable();
824 distinct.dedup();
825 distinct
826}
827
828fn codes_over(values: &[i64], dictionary: &[i64]) -> Vec<i64> {
838 values
839 .iter()
840 .map(|value| {
841 dictionary
842 .binary_search(value)
843 .expect("the dictionary is the distinct values of this chunk") as i64
844 })
845 .collect()
846}
847
848fn check_count(actual: usize, expected: usize) -> Result<()> {
849 if actual == expected {
850 Ok(())
851 } else {
852 Err(Error::internal(format!(
853 "a chunk says it holds {expected} values and decoded to {actual}"
854 )))
855 }
856}
857
858fn too_long(len: usize) -> Error {
859 Error::internal(format!("a chunk of {len} values is longer than the format allows"))
860}
861
862fn put_u8(out: &mut Vec<u8>, value: u8) {
863 out.push(value);
864}
865
866fn put_u32(out: &mut Vec<u8>, value: u32) {
867 out.extend_from_slice(&value.to_le_bytes());
868}
869
870fn put_u64(out: &mut Vec<u8>, value: u64) {
871 out.extend_from_slice(&value.to_le_bytes());
872}
873
874fn put_i64(out: &mut Vec<u8>, value: i64) {
875 out.extend_from_slice(&value.to_le_bytes());
876}
877
878#[cfg(test)]
879mod tests {
880 use super::*;
881
882 fn round_trip(values: &[i64]) -> Vec<u8> {
883 let bytes = encode(values).unwrap();
884 assert_eq!(decode(&bytes).unwrap(), values, "{}", describe(&bytes).unwrap());
885 bytes
886 }
887
888 fn kind_of(bytes: &[u8]) -> Kind {
889 Kind::from_tag(bytes[0]).unwrap()
890 }
891
892 struct Random(u64);
894
895 impl Random {
896 fn new() -> Self {
897 Self(0x9e37_79b9_7f4a_7c15)
898 }
899
900 fn next(&mut self) -> u64 {
901 self.0 ^= self.0 << 13;
902 self.0 ^= self.0 >> 7;
903 self.0 ^= self.0 << 17;
904 self.0
905 }
906 }
907
908 #[test]
909 fn the_dictionary_is_sorted_and_the_codes_point_back_at_the_values() {
910 let values = vec![30i64, 10, 30, 20, 10, -5];
911 let dictionary = distinct_values(&values);
912 let codes = codes_over(&values, &dictionary);
913 assert_eq!(dictionary, vec![-5, 10, 20, 30]);
914 assert_eq!(codes, vec![3, 1, 3, 2, 1, 0]);
915 for (code, value) in codes.iter().zip(&values) {
916 assert_eq!(dictionary[*code as usize], *value);
917 }
918 }
919
920 #[test]
921 fn one_sort_gives_the_distinct_count_and_the_most_frequent_value() {
922 let values = vec![7i64, 7, 7, 1, 2, 2];
923 assert_eq!(spread_of(&values), (3, Some((7, 3))));
924 assert_eq!(spread_of(&[]), (0, None));
925 assert_eq!(spread_of(&[9]), (1, Some((9, 1))));
926
927 assert_eq!(spread_of(&[4i64, 4, 8, 8]), (2, Some((4, 2))));
930 }
931
932 #[test]
933 fn deltas_that_do_not_fit_are_refused_before_they_are_built() {
934 assert!(deltas_fit(&[1i64, 2, 3]));
935 assert!(deltas_fit(&[i64::MAX, i64::MAX]));
936 assert!(!deltas_fit(&[i64::MIN, i64::MAX]));
937 assert_eq!(deltas_fit(&[i64::MIN, i64::MAX]), deltas(&[i64::MIN, i64::MAX]).is_some());
938 assert_eq!(deltas_fit(&[1i64, 2, 3]), deltas(&[1i64, 2, 3]).is_some());
939 }
940
941 #[test]
942 fn what_the_chooser_returns_is_the_smallest_of_what_it_was_offered() {
943 let mut random = Random::new();
947 let noise: Vec<i64> = (0..2000).map(|_| (random.next() % 5000) as i64).collect();
948 let runs: Vec<i64> = (0..2000).map(|index: i64| index / 100).collect();
949 let climbing: Vec<i64> = (0..2000).map(|index| 1_700_000_000 + index).collect();
950 for values in [noise, runs, climbing, vec![7; 300], Vec::new()] {
951 let chosen = encode(&values).unwrap();
952 let mut smallest: Option<Vec<u8>> = None;
953 for kind in offered(&values) {
954 let Some(bytes) = encode_only(kind, &values).unwrap() else {
955 continue;
956 };
957 if smallest.as_ref().is_none_or(|best| bytes.len() < best.len()) {
958 smallest = Some(bytes);
959 }
960 }
961 assert_eq!(smallest.as_deref(), Some(chosen.as_slice()), "{}", values.len());
962 }
963 }
964
965 #[test]
966 fn a_column_of_whole_seconds_in_microseconds_pays_nothing_for_the_zeroes() {
967 let mut random = Random::new();
971 let day = 1_374_000_000_000_000i64;
972 let values: Vec<i64> =
973 (0..100_000).map(|_| day + (random.next() % 68_400) as i64 * 1_000_000).collect();
974 let bytes = round_trip(&values);
975 assert_eq!(kind_of(&bytes), Kind::Strided);
976 assert!(describe(&bytes).unwrap().starts_with("STRIDE[1000000]"), "{:?}", describe(&bytes));
977 let strided = 100_000 * 17 / 8;
979 assert!(bytes.len() < strided + 2000, "{} bytes for {strided} of payload", bytes.len());
980
981 let plain = encode_only(Kind::Packed, &values).unwrap().expect("packing always applies");
982 assert!(
983 bytes.len() * 2 < plain.len(),
984 "{} strided against {} packed",
985 bytes.len(),
986 plain.len()
987 );
988 }
989
990 #[test]
991 fn a_stride_is_the_common_factor_of_the_distances_from_the_smallest_value() {
992 assert_eq!(stride_of(&[10i64, 20, 40]), Some(10));
993 assert_eq!(stride_of(&[7i64, 17, 37]), Some(10));
996 assert_eq!(stride_of(&[10i64, 20, 23]), None);
997 assert_eq!(stride_of(&[5i64; 100]), None);
1000 assert_eq!(stride_of(&[]), None);
1001 assert_eq!(stride_of(&[i64::MIN, i64::MAX]), Some(u64::MAX));
1003 }
1004
1005 #[test]
1006 fn a_stride_across_the_whole_of_the_type_round_trips() {
1007 for values in [vec![i64::MIN, i64::MAX], vec![i64::MIN, 0, i64::MAX]] {
1010 let bytes = round_trip(&values);
1011 assert_eq!(decode(&bytes).unwrap(), values);
1012 }
1013 }
1014
1015 #[test]
1016 fn a_column_with_no_common_factor_is_not_offered_a_stride() {
1017 let mut random = Random::new();
1018 let values: Vec<i64> = (0..2000).map(|_| (random.next() % 1_000_000) as i64).collect();
1019 assert!(!offered(&values).contains(&Kind::Strided));
1020 assert!(encode_only(Kind::Strided, &values).unwrap().is_none());
1021 }
1022
1023 #[test]
1024 fn an_empty_chunk_round_trips() {
1025 let bytes = round_trip(&[]);
1026 assert_eq!(bytes.len(), 5);
1027 }
1028
1029 #[test]
1030 fn a_constant_column_costs_thirteen_bytes_however_long_it_is() {
1031 let bytes = round_trip(&vec![42; 1_000_000]);
1032 assert_eq!(kind_of(&bytes), Kind::Constant);
1033 assert_eq!(bytes.len(), 13);
1034 }
1035
1036 #[test]
1037 fn a_narrow_range_is_packed_at_the_width_of_the_range_and_not_of_the_type() {
1038 let mut random = Random::new();
1040 let values: Vec<i64> = (0..100_000).map(|_| 1000 + (random.next() % 64) as i64).collect();
1041 let bytes = round_trip(&values);
1042 assert_eq!(kind_of(&bytes), Kind::Packed);
1043 let packed = 100_000 * 6 / 8;
1044 assert!(bytes.len() < packed + 2000, "{} bytes for {packed} of payload", bytes.len());
1045 assert!(bytes.len() > packed, "{} bytes cannot hold {packed}", bytes.len());
1046 }
1047
1048 #[test]
1049 fn a_counter_becomes_deltas_and_then_a_constant() {
1050 let values: Vec<i64> = (0..1_000_000).collect();
1053 let bytes = round_trip(&values);
1054 assert_eq!(kind_of(&bytes), Kind::Delta);
1055 assert_eq!(describe(&bytes).unwrap(), "DELTA(CONSTANT)");
1056 assert!(bytes.len() < 40, "{} bytes for a counter", bytes.len());
1057 }
1058
1059 #[test]
1060 fn a_column_that_counts_down_is_as_cheap_as_one_that_counts_up() {
1061 let up: Vec<i64> = (0..100_000).collect();
1063 let down: Vec<i64> = (0..100_000).rev().collect();
1064 assert_eq!(round_trip(&up).len(), round_trip(&down).len());
1065 }
1066
1067 #[test]
1068 fn long_runs_become_rle() {
1069 let mut values = Vec::new();
1070 for run in 0..1000 {
1071 values.extend(std::iter::repeat_n(run % 7, 200));
1072 }
1073 let bytes = round_trip(&values);
1074 assert_eq!(kind_of(&bytes), Kind::Rle);
1075 assert!(bytes.len() < 2000, "{} bytes for 1000 runs", bytes.len());
1076 }
1077
1078 #[test]
1079 fn a_low_cardinality_column_becomes_a_dictionary() {
1080 let mut random = Random::new();
1086 let dictionary: Vec<i64> =
1087 (0..40).map(|_| 1_000_000_000 + (random.next() % (1 << 30)) as i64).collect();
1088 let values: Vec<i64> =
1089 (0..100_000).map(|_| dictionary[(random.next() % 40) as usize]).collect();
1090 let bytes = round_trip(&values);
1091 assert_eq!(kind_of(&bytes), Kind::Dict);
1092 assert!(bytes.len() < 100_000, "{} bytes", bytes.len());
1093 }
1094
1095 #[test]
1096 fn a_nearly_constant_column_becomes_sparse() {
1097 let mut values = vec![0i64; 100_000];
1098 for index in 0..300 {
1099 values[index * 331] = 1 << 40;
1100 }
1101 let bytes = round_trip(&values);
1102 assert_eq!(kind_of(&bytes), Kind::Sparse);
1103 assert!(bytes.len() < 3000, "{} bytes for 300 exceptions", bytes.len());
1104 }
1105
1106 #[test]
1107 fn the_cascade_goes_more_than_one_level_deep() {
1108 let mut values = Vec::new();
1111 for index in 0..2000i64 {
1112 values.extend(std::iter::repeat_n(1_000_000 + (index % 5) * 104_729, 100));
1113 }
1114 let bytes = round_trip(&values);
1115 let shape = describe(&bytes).unwrap();
1116 assert!(shape.contains('('), "{shape} is not a cascade");
1117 assert!(bytes.len() < 4000, "{} bytes: {shape}", bytes.len());
1118 }
1119
1120 #[test]
1121 fn random_data_is_packed_at_full_width_and_costs_what_it_costs() {
1122 let mut random = Random::new();
1125 let values: Vec<i64> = (0..10_000).map(|_| random.next() as i64).collect();
1126 let bytes = round_trip(&values);
1127 assert_eq!(kind_of(&bytes), Kind::Packed);
1128 assert!(bytes.len() < 10_000 * 8 + 1000, "{} bytes", bytes.len());
1129 }
1130
1131 #[test]
1132 fn the_extremes_of_the_type_survive() {
1133 let values = vec![i64::MIN, i64::MAX, 0, -1, i64::MIN, i64::MAX];
1136 round_trip(&values);
1137 round_trip(&[i64::MIN; 3]);
1138 round_trip(&[i64::MIN, i64::MIN + 1]);
1139 }
1140
1141 #[test]
1142 fn a_chunk_that_is_not_a_multiple_of_the_unit_round_trips() {
1143 for len in [1, 2, 1023, 1024, 1025, 2047, 2049] {
1144 let values: Vec<i64> = (0..len).map(|index| (index * 31 % 97) as i64).collect();
1145 round_trip(&values);
1146 }
1147 }
1148
1149 #[test]
1150 fn units_of_different_widths_in_one_chunk_do_not_read_each_others_leftovers() {
1151 let mut random = Random::new();
1163 let mut values = Vec::new();
1164 for width in [40u32, 3, 61, 1, 17, 40] {
1165 for _ in 0..1024 {
1166 values.push((random.next() & ((1u64 << width) - 1)) as i64);
1167 }
1168 }
1169 let bytes = encode(&values).unwrap();
1170 let described = describe(&bytes).unwrap();
1171 assert!(described.starts_with("FOR+BITPACK"), "expected one packed chunk, got {described}");
1172 assert_eq!(decode(&bytes).unwrap(), values, "{described}");
1173 }
1174
1175 #[test]
1176 fn a_cascade_decodes_the_same_through_a_shared_scratch_as_through_its_own() {
1177 let mut values = Vec::new();
1182 for index in 0..8192i64 {
1183 values.push(1_600_000_000 + index / 4 + (index % 7) * 1_000);
1184 }
1185 let bytes = encode(&values).unwrap();
1186 let described = describe(&bytes).unwrap();
1187 assert!(described.contains('('), "expected a cascade, got {described}");
1188 assert_eq!(decode(&bytes).unwrap(), values, "{described}");
1189 }
1190
1191 #[test]
1192 fn a_partial_unit_costs_its_own_values_and_not_a_whole_unit() {
1193 let values = vec![1i64 << 39, (1 << 39) + 7, 1 << 38];
1197 let bytes = encode_only(Kind::Packed, &values).unwrap().unwrap();
1198 assert_eq!(bytes.len(), 5 + 9 + 15);
1199 assert_eq!(decode(&bytes).unwrap(), values);
1200 }
1201
1202 #[test]
1203 fn the_frame_of_reference_is_per_unit_and_not_per_chunk() {
1204 let values: Vec<i64> =
1208 (0..4096i64).map(|index| (index / 1024) * 1_000_000 + (index % 1024)).collect();
1209 let bytes = encode_only(Kind::Packed, &values).unwrap().unwrap();
1210 assert_eq!(describe(&bytes).unwrap(), "FOR+BITPACK[10]");
1211 assert_eq!(decode(&bytes).unwrap(), values);
1212 }
1213
1214 #[test]
1215 fn every_candidate_that_applies_decodes_to_the_input() {
1216 let mut values = vec![5i64; 3000];
1220 for (index, value) in values.iter_mut().enumerate() {
1221 if index % 500 == 0 {
1222 *value = index as i64;
1223 }
1224 }
1225 let applicable = candidates(&values, 0);
1226 assert!(applicable.len() >= 4, "{applicable:?}");
1227 for kind in applicable {
1228 let bytes = encode_only(kind, &values).unwrap().unwrap();
1229 assert_eq!(decode(&bytes).unwrap(), values, "{}", kind.name());
1230 }
1231 }
1232
1233 #[test]
1238 fn every_kind_that_applies_decodes_to_what_it_was_given() {
1239 let shapes: Vec<Vec<i64>> = vec![
1240 Vec::new(),
1241 vec![5; 1024],
1242 vec![i64::MIN, i64::MAX, 0, -1],
1243 (0..1024).map(|at| at * 7).collect(),
1244 (0..1024).map(|at| at % 17).collect(),
1245 (0..1024).map(|at| if at % 100 == 0 { at } else { 3 }).collect(),
1246 (0..1024).map(|at| -at * 1_000_003).collect(),
1247 (0..1024_i64)
1248 .map(|at| {
1249 at.wrapping_mul(6_364_136_223_846_793_005)
1250 .wrapping_add(1_442_695_040_888_963_407)
1251 })
1252 .collect(),
1253 ];
1254 let kinds =
1255 [Kind::Constant, Kind::Packed, Kind::Delta, Kind::Rle, Kind::Dict, Kind::Sparse];
1256 for values in &shapes {
1257 for kind in kinds {
1258 let Some(bytes) = encode_only(kind, values).unwrap() else {
1259 continue;
1260 };
1261 assert_eq!(
1262 &decode(&bytes).unwrap(),
1263 values,
1264 "{} over {} values",
1265 kind.name(),
1266 values.len()
1267 );
1268 }
1269 }
1270 }
1271
1272 #[test]
1273 fn the_chooser_picks_the_smallest_candidate_rather_than_the_first_that_applies() {
1274 let mut values = vec![5i64; 3000];
1275 values[1500] = 9;
1276 let chosen = encode(&values).unwrap();
1277 for (_, size) in candidate_sizes(&values).unwrap() {
1278 assert!(chosen.len() <= size);
1279 }
1280 }
1281
1282 #[test]
1283 fn a_truncated_chunk_is_an_error_and_not_a_panic() {
1284 let bytes = encode(&[1, 2, 3, 4, 5]).unwrap();
1285 for len in 0..bytes.len() {
1286 let error = decode(&bytes[..len]).unwrap_err();
1287 assert!(error.message().contains("chunk"), "{error}");
1288 }
1289 }
1290
1291 #[test]
1292 fn trailing_bytes_are_an_error() {
1293 let mut bytes = encode(&[1, 2, 3]).unwrap();
1294 bytes.push(0);
1295 let error = decode(&bytes).unwrap_err();
1296 assert!(error.message().contains("left over"), "{error}");
1297 }
1298
1299 #[test]
1300 fn an_unknown_tag_is_an_error() {
1301 let error = decode(&[99, 0, 0, 0, 0]).unwrap_err();
1302 assert!(error.message().contains("unknown encoding tag"), "{error}");
1303 }
1304
1305 #[test]
1306 fn a_dictionary_code_outside_the_dictionary_is_an_error() {
1307 let mut bytes = vec![Kind::Dict.tag()];
1312 put_u32(&mut bytes, 1);
1313 bytes.extend_from_slice(&encode(&[10]).unwrap());
1314 bytes.extend_from_slice(&encode(&[5]).unwrap());
1315 let error = decode(&bytes).unwrap_err();
1316 assert!(error.message().contains("not in the dictionary"), "{error}");
1317 }
1318
1319 #[test]
1320 fn a_negative_run_length_is_an_error() {
1321 let mut bytes = vec![Kind::Rle.tag()];
1324 put_u32(&mut bytes, 4);
1325 bytes.extend_from_slice(&encode(&[7]).unwrap());
1326 bytes.extend_from_slice(&encode(&[-4]).unwrap());
1327 let error = decode(&bytes).unwrap_err();
1328 assert!(error.message().contains("negative"), "{error}");
1329 }
1330
1331 #[test]
1332 fn the_cascade_depth_is_bounded() {
1333 let values: Vec<i64> = (0..50_000).map(|index| (index / 100) % 250).collect();
1337 let bytes = round_trip(&values);
1338 let shape = describe(&bytes).unwrap();
1339 let depth = shape.matches('(').count();
1340 assert!(depth <= MAX_DEPTH as usize, "{shape} is {depth} deep");
1341 }
1342
1343 #[test]
1344 fn candidate_sizes_reports_what_the_chooser_looked_at() {
1345 let values: Vec<i64> = (0..5000).map(|index| index % 17).collect();
1346 let sizes = candidate_sizes(&values).unwrap();
1347 assert!(sizes.iter().any(|(kind, _)| *kind == Kind::Dict));
1348 assert!(sizes.iter().any(|(kind, _)| *kind == Kind::Packed));
1349 assert!(sizes.iter().all(|(_, size)| *size > 0));
1350 }
1351
1352 #[test]
1353 fn a_chunk_can_be_read_from_the_front_of_a_longer_buffer() {
1354 let first = encode(&[1, 2, 3]).unwrap();
1357 let second: Vec<i64> = (0..3000).map(|index| index % 11).collect();
1358 let second_bytes = encode(&second).unwrap();
1359 let mut joined = first.clone();
1360 joined.extend_from_slice(&second_bytes);
1361 joined.extend_from_slice(b"and then something else");
1362
1363 let (values, used) = decode_prefix(&joined).unwrap();
1364 assert_eq!(values, vec![1, 2, 3]);
1365 assert_eq!(used, first.len());
1366 let (more, used_again) = decode_prefix(&joined[used..]).unwrap();
1367 assert_eq!(more, second);
1368 assert_eq!(used_again, second_bytes.len());
1369
1370 let (text, described) = describe_prefix(&joined).unwrap();
1371 assert_eq!(described, first.len());
1372 assert_eq!(text, describe(&first).unwrap());
1373 }
1374
1375 #[test]
1376 fn a_truncated_chunk_is_still_an_error_when_read_as_a_prefix() {
1377 let bytes = encode(&(0..2000).collect::<Vec<i64>>()).unwrap();
1378 for len in 0..bytes.len() {
1379 assert!(decode_prefix(&bytes[..len]).is_err(), "{len} bytes decoded");
1380 }
1381 }
1382}