1use std::cell::RefCell;
46use std::sync::OnceLock;
47
48use rudb_common::{Error, Result};
49
50pub const ESCAPE: u8 = 255;
53
54pub const MAX_SYMBOLS: usize = 255;
56
57pub const MAX_SYMBOL_LEN: usize = 8;
60
61const GENERATIONS: usize = 5;
63
64const HASH_SLOTS: usize = 1024;
67
68const PROBE: usize = 8;
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
74struct Symbol {
75 value: u64,
76 len: u8,
77}
78
79impl Symbol {
80 fn new(bytes: &[u8]) -> Self {
81 let len = bytes.len().min(MAX_SYMBOL_LEN);
82 let mut value = 0u64;
83 for (index, byte) in bytes[..len].iter().enumerate() {
84 value |= u64::from(*byte) << (8 * index);
85 }
86 Self { value, len: len as u8 }
87 }
88
89 fn single(byte: u8) -> Self {
90 Self { value: u64::from(byte), len: 1 }
91 }
92
93 fn len(self) -> usize {
94 self.len as usize
95 }
96
97 fn mask(self) -> u64 {
98 mask_of(self.len())
99 }
100
101 fn bytes(self) -> Vec<u8> {
102 (0..self.len()).map(|index| (self.value >> (8 * index)) as u8).collect()
103 }
104
105 fn concat(self, other: Self) -> Self {
107 if self.len() >= MAX_SYMBOL_LEN {
108 return self;
109 }
110 let len = (self.len() + other.len()).min(MAX_SYMBOL_LEN);
111 let value = self.value | (other.value << (8 * self.len()));
112 Self { value: value & mask_of(len), len: len as u8 }
113 }
114}
115
116fn mask_of(len: usize) -> u64 {
117 if len >= 8 { u64::MAX } else { (1u64 << (8 * len)) - 1 }
118}
119
120pub struct SymbolTable {
122 symbols: Vec<Symbol>,
124 lookup: OnceLock<Lookup>,
131}
132
133struct Lookup {
135 single: Vec<u8>,
137 pair: Vec<u16>,
139 hash: Vec<Option<(Symbol, u8)>>,
141}
142
143impl std::fmt::Debug for SymbolTable {
144 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145 formatter
147 .debug_struct("SymbolTable")
148 .field("symbols", &self.symbols.len())
149 .field("bytes", &self.serialized_len())
150 .finish()
151 }
152}
153
154impl PartialEq for SymbolTable {
161 fn eq(&self, other: &Self) -> bool {
162 self.symbols == other.symbols
163 }
164}
165
166impl Eq for SymbolTable {}
167
168impl SymbolTable {
169 #[must_use]
176 pub fn footprint(&self) -> usize {
177 size_of::<Self>()
178 + self.symbols.capacity() * size_of::<Symbol>()
179 + self.lookup.get().map_or(0, |lookup| {
180 lookup.single.capacity()
181 + lookup.pair.capacity() * size_of::<u16>()
182 + lookup.hash.capacity() * size_of::<Option<(Symbol, u8)>>()
183 })
184 }
185
186 #[must_use]
189 pub fn empty() -> Self {
190 Self::build(Vec::new())
191 }
192
193 #[must_use]
199 pub fn train(samples: &[&[u8]]) -> Self {
200 thread_local! {
204 static COUNTS: RefCell<Option<Counts>> = const { RefCell::new(None) };
205 }
206 COUNTS.with(|held| match held.try_borrow_mut() {
207 Ok(mut held) => Self::train_with(samples, held.get_or_insert_with(Counts::new)),
208 Err(_) => Self::train_with(samples, &mut Counts::new()),
209 })
210 }
211
212 fn train_with(samples: &[&[u8]], counts: &mut Counts) -> Self {
213 let mut table = Self::empty();
214 for _ in 0..GENERATIONS {
215 counts.clear();
216 for sample in samples {
217 table.count(sample, counts);
218 }
219 let next = counts.best(&table);
220 if next.is_empty() {
221 break;
222 }
223 table = Self::build(next);
224 }
225 table
226 }
227
228 #[must_use]
230 pub fn len(&self) -> usize {
231 self.symbols.len()
232 }
233
234 #[must_use]
236 pub fn is_empty(&self) -> bool {
237 self.symbols.is_empty()
238 }
239
240 #[must_use]
244 pub fn serialized_len(&self) -> usize {
245 1 + self.symbols.iter().map(|symbol| 1 + symbol.len()).sum::<usize>()
246 }
247
248 pub fn serialize(&self, out: &mut Vec<u8>) {
250 out.push(self.symbols.len() as u8);
251 for symbol in &self.symbols {
252 out.push(symbol.len);
253 out.extend_from_slice(&symbol.bytes());
254 }
255 }
256
257 pub fn deserialize(bytes: &[u8]) -> Result<(Self, usize)> {
263 let count = *bytes.first().ok_or_else(|| truncated("a symbol table header"))? as usize;
264 let mut at = 1;
265 let mut symbols = Vec::with_capacity(count);
266 for _ in 0..count {
267 let len = *bytes.get(at).ok_or_else(|| truncated("a symbol length"))? as usize;
268 if len == 0 || len > MAX_SYMBOL_LEN {
269 return Err(Error::internal(format!("a symbol of {len} bytes is not a symbol")));
270 }
271 at += 1;
272 let end = at + len;
273 if end > bytes.len() {
274 return Err(truncated("a symbol"));
275 }
276 symbols.push(Symbol::new(&bytes[at..end]));
277 at = end;
278 }
279 Ok((Self::build(symbols), at))
280 }
281
282 pub fn compress(&self, input: &[u8], out: &mut Vec<u8>) {
288 let mut at = 0;
289 while at < input.len() {
290 let (code, len) = self.match_at(input, at);
291 if code == ESCAPE {
292 out.push(ESCAPE);
293 out.push(input[at]);
294 } else {
295 out.push(code);
296 }
297 at += len;
298 }
299 }
300
301 pub fn decompress(&self, input: &[u8], out: &mut Vec<u8>) -> Result<()> {
318 out.reserve(input.len().saturating_mul(2).saturating_add(MAX_SYMBOL_LEN));
322 let mut at = 0;
323 while at < input.len() {
324 let code = input[at];
325 at += 1;
326 if code == ESCAPE {
327 let literal = *input.get(at).ok_or_else(|| truncated("an escaped byte"))?;
328 out.push(literal);
329 at += 1;
330 } else {
331 let symbol = *self
332 .symbols
333 .get(code as usize)
334 .ok_or_else(|| Error::internal(format!("code {code} is not in the table")))?;
335 out.extend_from_slice(&symbol.value.to_le_bytes());
336 out.truncate(out.len() - (MAX_SYMBOL_LEN - symbol.len()));
337 }
338 }
339 Ok(())
340 }
341
342 pub fn decompress_at(&self, input: &[u8], out: &mut [u8], mut at: usize) -> Result<usize> {
354 let mut read = 0;
355 while read < input.len() {
356 let code = input[read];
357 read += 1;
358 if code == ESCAPE {
359 let literal = *input.get(read).ok_or_else(|| truncated("an escaped byte"))?;
360 read += 1;
361 *out.get_mut(at).ok_or_else(out_of_room)? = literal;
362 at += 1;
363 } else {
364 let symbol = *self
365 .symbols
366 .get(code as usize)
367 .ok_or_else(|| Error::internal(format!("code {code} is not in the table")))?;
368 out.get_mut(at..at + MAX_SYMBOL_LEN)
369 .ok_or_else(out_of_room)?
370 .copy_from_slice(&symbol.value.to_le_bytes());
371 at += symbol.len();
372 }
373 }
374 Ok(at)
375 }
376
377 fn match_at(&self, input: &[u8], at: usize) -> (u8, usize) {
379 let remaining = input.len() - at;
380 let word = load(input, at);
381 if remaining >= 3 {
384 if let Some((symbol, code)) = self.probe(word, remaining) {
385 return (code, symbol.len());
386 }
387 }
388 if remaining >= 2 {
389 let code = self.lookup().pair[(word & 0xffff) as usize];
390 if code != u16::MAX {
391 return (code as u8, 2);
392 }
393 }
394 let code = self.lookup().single[(word & 0xff) as usize];
395 if code == ESCAPE { (ESCAPE, 1) } else { (code, 1) }
396 }
397
398 fn probe(&self, word: u64, remaining: usize) -> Option<(Symbol, u8)> {
404 let hash = &self.lookup().hash;
405 let mut slot = hash_of(word);
406 let mut best: Option<(Symbol, u8)> = None;
407 for _ in 0..PROBE {
408 match hash[slot] {
409 None => break,
410 Some((symbol, code)) => {
411 if symbol.len() <= remaining
412 && word & symbol.mask() == symbol.value
413 && best.is_none_or(|(found, _)| symbol.len() > found.len())
414 {
415 best = Some((symbol, code));
416 }
417 }
418 }
419 slot = (slot + 1) & (HASH_SLOTS - 1);
420 }
421 best
422 }
423
424 fn count(&self, input: &[u8], counts: &mut Counts) {
427 let mut at = 0;
428 let mut previous: Option<u16> = None;
429 while at < input.len() {
430 let (code, len) = self.match_at(input, at);
431 let id = if code == ESCAPE { 256 + u16::from(input[at]) } else { u16::from(code) };
432 counts.one(id);
433 if let Some(previous) = previous {
434 counts.two(previous, id);
435 }
436 previous = Some(id);
437 at += len;
438 }
439 }
440
441 fn build(symbols: Vec<Symbol>) -> Self {
442 Self { symbols, lookup: OnceLock::new() }
443 }
444
445 fn lookup(&self) -> &Lookup {
446 self.lookup.get_or_init(|| Lookup::of(&self.symbols))
447 }
448}
449
450impl Lookup {
451 fn of(symbols: &[Symbol]) -> Self {
452 let mut table = Self {
453 single: vec![ESCAPE; 256],
454 pair: vec![u16::MAX; 65536],
455 hash: vec![None; HASH_SLOTS],
456 };
457 let mut order: Vec<(Symbol, u8)> =
460 symbols.iter().enumerate().map(|(code, symbol)| (*symbol, code as u8)).collect();
461 order.sort_by_key(|(symbol, code)| (std::cmp::Reverse(symbol.len()), *code));
462 for (symbol, code) in order {
463 match symbol.len() {
464 1 => {
465 let index = (symbol.value & 0xff) as usize;
466 if table.single[index] == ESCAPE {
467 table.single[index] = code;
468 }
469 }
470 2 => {
471 let index = (symbol.value & 0xffff) as usize;
472 if table.pair[index] == u16::MAX {
473 table.pair[index] = u16::from(code);
474 }
475 }
476 _ => {
477 let mut slot = hash_of(symbol.value);
478 for _ in 0..PROBE {
479 if table.hash[slot].is_none() {
480 table.hash[slot] = Some((symbol, code));
481 break;
482 }
483 slot = (slot + 1) & (HASH_SLOTS - 1);
484 }
485 }
486 }
487 }
488 table
489 }
490}
491
492fn load(input: &[u8], at: usize) -> u64 {
497 if at + 8 <= input.len() {
498 let bytes: [u8; 8] = input[at..at + 8].try_into().expect("eight bytes were checked");
499 u64::from_le_bytes(bytes)
500 } else {
501 let mut word = 0u64;
502 for (index, byte) in input[at..].iter().enumerate() {
503 word |= u64::from(*byte) << (8 * index);
504 }
505 word
506 }
507}
508
509fn hash_of(word: u64) -> usize {
513 let key = word & 0xff_ffff;
514 ((key.wrapping_mul(0x9e37_79b9_7f4a_7c15)) >> (64 - HASH_SLOTS.trailing_zeros())) as usize
515}
516
517struct Counts {
521 single: Vec<u32>,
522 pairs: Vec<u32>,
525 seen: Vec<u32>,
528 gains: Gains,
530}
531
532#[derive(Default)]
534struct Gains {
535 gains: Vec<(Symbol, u64)>,
536 places: Vec<u32>,
538 taken: Vec<u32>,
540}
541
542impl Gains {
543 fn clear(&mut self, most: usize) {
545 for place in self.taken.drain(..) {
546 self.places[place as usize] = u32::MAX;
547 }
548 let wanted = (most * 2).next_power_of_two();
549 if self.places.len() < wanted {
550 self.places = vec![u32::MAX; wanted];
551 }
552 self.gains.clear();
553 }
554
555 fn add(&mut self, symbol: Symbol, count: u64) {
557 let gain = count * symbol.len() as u64;
558 let mask = self.places.len() - 1;
559 let mut place = gain_hash(symbol) & mask;
560 loop {
561 let at = self.places[place];
562 if at == u32::MAX {
563 self.places[place] = self.gains.len() as u32;
564 self.taken.push(place as u32);
565 self.gains.push((symbol, gain));
566 return;
567 }
568 if self.gains[at as usize].0 == symbol {
569 self.gains[at as usize].1 += gain;
570 return;
571 }
572 place = (place + 1) & mask;
573 }
574 }
575}
576
577const IDS: usize = 512;
579
580impl Counts {
581 fn new() -> Self {
582 Self {
583 single: vec![0; IDS],
584 pairs: vec![0; IDS * IDS],
585 seen: Vec::new(),
586 gains: Gains::default(),
587 }
588 }
589
590 fn clear(&mut self) {
591 self.single.fill(0);
592 for slot in self.seen.drain(..) {
593 self.pairs[slot as usize] = 0;
594 }
595 }
596
597 fn one(&mut self, id: u16) {
598 self.single[id as usize] += 1;
599 }
600
601 fn two(&mut self, first: u16, second: u16) {
602 let slot = first as usize * IDS + second as usize;
603 if self.pairs[slot] == 0 {
604 self.seen.push(slot as u32);
605 }
606 self.pairs[slot] += 1;
607 }
608
609 fn best(&mut self, table: &SymbolTable) -> Vec<Symbol> {
616 self.gains.clear(IDS + self.seen.len());
621 for (id, count) in self.single.iter().enumerate() {
622 if *count == 0 {
623 continue;
624 }
625 let symbol = symbol_of(table, id as u16);
626 self.gains.add(symbol, u64::from(*count));
627 }
628 for slot in &self.seen {
629 let slot = *slot as usize;
630 let (first, second) = ((slot / IDS) as u16, (slot % IDS) as u16);
631 let symbol = symbol_of(table, first).concat(symbol_of(table, second));
632 self.gains.add(symbol, u64::from(self.pairs[slot]));
633 }
634 let gains = &mut self.gains.gains;
635 let order = |left: &(Symbol, u64), right: &(Symbol, u64)| {
639 right.1.cmp(&left.1).then(left.0.cmp(&right.0))
640 };
641 if gains.len() > MAX_SYMBOLS {
642 gains.select_nth_unstable_by(MAX_SYMBOLS - 1, order);
643 gains.truncate(MAX_SYMBOLS);
644 }
645 gains.sort_unstable_by(order);
646 gains.iter().map(|(symbol, _)| *symbol).collect()
647 }
648}
649
650fn gain_hash(symbol: Symbol) -> usize {
652 ((symbol.value ^ u64::from(symbol.len)).wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 32) as usize
653}
654
655fn symbol_of(table: &SymbolTable, id: u16) -> Symbol {
656 if (id as usize) < table.symbols.len() {
657 table.symbols[id as usize]
658 } else {
659 Symbol::single((id.saturating_sub(256)) as u8)
660 }
661}
662
663fn out_of_room() -> Error {
664 Error::internal("a string decompresses to more than its length says")
665}
666
667fn truncated(what: &str) -> Error {
668 Error::internal(format!("the input ended in the middle of {what}"))
669}
670
671#[cfg(test)]
672mod tests {
673 use super::*;
674
675 #[test]
676 fn a_table_read_back_to_decompress_builds_no_lookup_tables() {
677 let urls = urls();
678 let samples: Vec<&[u8]> = urls.iter().map(Vec::as_slice).collect();
679 let trained = SymbolTable::train(&samples);
680 let mut compressed = Vec::new();
681 trained.compress(&urls[7], &mut compressed);
682 let mut stored = Vec::new();
683 trained.serialize(&mut stored);
684 let (read, _) = SymbolTable::deserialize(&stored).expect("a table it wrote");
685 let mut out = Vec::new();
686 read.decompress(&compressed, &mut out).expect("a string it compressed");
687 assert_eq!(out, urls[7]);
688 assert!(read.lookup.get().is_none(), "decompressing reads the symbols alone");
689 assert!(read.footprint() < trained.footprint());
690 }
691
692 fn urls() -> Vec<Vec<u8>> {
696 let hosts = ["www.example.com", "shop.example.com", "news.other.example.org"];
697 let paths = ["/index.html", "/catalog/item", "/search", "/user/profile/settings"];
698 let mut out = Vec::new();
699 for index in 0..600 {
700 let host = hosts[index % hosts.len()];
701 let path = paths[(index / 3) % paths.len()];
702 out.push(
703 format!("http://{host}{path}?session={}&ref=google&page={}", index * 7, index % 20)
704 .into_bytes(),
705 );
706 }
707 out
708 }
709
710 fn borrow(strings: &[Vec<u8>]) -> Vec<&[u8]> {
711 strings.iter().map(Vec::as_slice).collect()
712 }
713
714 fn round_trip(table: &SymbolTable, strings: &[Vec<u8>]) -> (usize, usize) {
715 let mut raw = 0;
716 let mut compressed = 0;
717 for string in strings {
718 let mut bytes = Vec::new();
719 table.compress(string, &mut bytes);
720 let mut back = Vec::new();
721 table.decompress(&bytes, &mut back).unwrap();
722 assert_eq!(back, *string, "{}", String::from_utf8_lossy(string));
723 raw += string.len();
724 compressed += bytes.len();
725 }
726 (raw, compressed)
727 }
728
729 #[test]
730 fn urls_compress_by_more_than_half_and_come_back_unchanged() {
731 let strings = urls();
734 let table = SymbolTable::train(&borrow(&strings));
735 let (raw, compressed) = round_trip(&table, &strings);
736 let ratio = raw as f64 / compressed as f64;
737 assert!(ratio > 2.5, "{ratio:.2}x, {raw} to {compressed}");
738 assert!(table.len() > 100, "{} symbols", table.len());
739 }
740
741 #[test]
742 fn the_trainer_finds_the_long_repeated_pieces() {
743 let strings = urls();
744 let table = SymbolTable::train(&borrow(&strings));
745 let found: Vec<String> = (0..table.len())
746 .map(|code| String::from_utf8_lossy(&table.symbols[code].bytes()).into_owned())
747 .collect();
748 let long = found.iter().filter(|symbol| symbol.len() >= 6).count();
751 assert!(long > 60, "only {long} symbols of six bytes or more: {found:?}");
752 }
753
754 #[test]
755 fn english_text_round_trips_and_shrinks() {
756 let text: Vec<Vec<u8>> = "the quick brown fox jumps over the lazy dog while the other dog \
757 watches the fox and the dog and the fox go over the hill together"
758 .split(' ')
759 .map(|word| word.as_bytes().to_vec())
760 .collect();
761 let table = SymbolTable::train(&borrow(&text));
762 let (raw, compressed) = round_trip(&table, &text);
763 assert!(compressed < raw, "{raw} to {compressed}");
764 }
765
766 #[test]
767 fn incompressible_bytes_round_trip_and_cost_what_escaping_costs() {
768 let mut state = 0x1234_5678_9abc_def0u64;
772 let strings: Vec<Vec<u8>> = (0..100)
773 .map(|_| {
774 (0..64)
775 .map(|_| {
776 state ^= state << 13;
777 state ^= state >> 7;
778 state ^= state << 17;
779 state as u8
780 })
781 .collect()
782 })
783 .collect();
784 let table = SymbolTable::train(&borrow(&strings));
785 let (raw, compressed) = round_trip(&table, &strings);
786 assert!(compressed < raw * 2, "{raw} to {compressed}");
787 }
788
789 #[test]
790 fn an_empty_table_escapes_everything_and_still_round_trips() {
791 let table = SymbolTable::empty();
792 let strings = vec![b"hello".to_vec(), Vec::new(), b"x".to_vec()];
793 let (raw, compressed) = round_trip(&table, &strings);
794 assert_eq!(compressed, raw * 2);
795 }
796
797 #[test]
798 fn an_empty_string_compresses_to_nothing() {
799 let table = SymbolTable::train(&[b"abcabcabc"]);
800 let mut out = Vec::new();
801 table.compress(b"", &mut out);
802 assert!(out.is_empty());
803 let mut back = Vec::new();
804 table.decompress(&out, &mut back).unwrap();
805 assert!(back.is_empty());
806 }
807
808 #[test]
809 fn a_string_shorter_than_the_symbols_does_not_read_past_its_end() {
810 let table = SymbolTable::train(&[b"ab\0ab\0ab\0ab\0", b"abcdefgh"]);
813 for string in [b"a".to_vec(), b"ab".to_vec(), b"abc".to_vec()] {
814 let mut bytes = Vec::new();
815 table.compress(&string, &mut bytes);
816 let mut back = Vec::new();
817 table.decompress(&bytes, &mut back).unwrap();
818 assert_eq!(back, string);
819 }
820 }
821
822 #[test]
823 fn a_table_survives_being_written_and_read_back() {
824 let strings = urls();
825 let table = SymbolTable::train(&borrow(&strings));
826 let mut bytes = Vec::new();
827 table.serialize(&mut bytes);
828 assert_eq!(bytes.len(), table.serialized_len());
829 let (read, consumed) = SymbolTable::deserialize(&bytes).unwrap();
830 assert_eq!(consumed, bytes.len());
831 assert_eq!(read.symbols, table.symbols);
832
833 let mut first = Vec::new();
836 let mut second = Vec::new();
837 table.compress(&strings[7], &mut first);
838 read.compress(&strings[7], &mut second);
839 assert_eq!(first, second);
840 }
841
842 #[test]
843 fn a_full_table_is_two_kilobytes_at_the_very_most() {
844 let strings = urls();
845 let table = SymbolTable::train(&borrow(&strings));
846 assert!(table.serialized_len() <= 1 + MAX_SYMBOLS * (1 + MAX_SYMBOL_LEN));
847 assert!(table.serialized_len() <= 2049);
848 }
849
850 #[test]
851 fn a_truncated_symbol_table_is_an_error() {
852 let strings = urls();
853 let table = SymbolTable::train(&borrow(&strings));
854 let mut bytes = Vec::new();
855 table.serialize(&mut bytes);
856 for len in 1..bytes.len().min(40) {
857 let error = SymbolTable::deserialize(&bytes[..len]).unwrap_err();
858 assert!(error.message().contains("ended in the middle"), "{error}");
859 }
860 }
861
862 #[test]
863 fn a_symbol_of_zero_bytes_is_an_error() {
864 let error = SymbolTable::deserialize(&[1, 0]).unwrap_err();
865 assert!(error.message().contains("is not a symbol"), "{error}");
866 }
867
868 #[test]
869 fn a_short_symbol_does_not_drag_the_rest_of_its_word_out_with_it() {
870 let table = SymbolTable::train(&[b"abcdabcdabcdabcd"]);
876 let mut compressed = Vec::new();
877 table.compress(b"abcdabcd", &mut compressed);
878 let mut out = Vec::new();
879 table.decompress(&compressed, &mut out).expect("decompresses");
880 table.decompress(&compressed, &mut out).expect("decompresses");
881 assert_eq!(out, b"abcdabcdabcdabcd");
882 }
883
884 #[test]
885 fn a_dangling_escape_is_an_error_and_not_a_panic() {
886 let table = SymbolTable::train(&[b"abcabcabc"]);
887 let error = table.decompress(&[ESCAPE], &mut Vec::new()).unwrap_err();
888 assert!(error.message().contains("escaped byte"), "{error}");
889 }
890
891 #[test]
892 fn a_code_the_table_does_not_have_is_an_error() {
893 let table = SymbolTable::train(&[b"abcabcabc"]);
894 let code = table.len() as u8;
895 let error = table.decompress(&[code], &mut Vec::new()).unwrap_err();
896 assert!(error.message().contains("not in the table"), "{error}");
897 }
898
899 #[test]
900 fn training_twice_on_the_same_sample_gives_the_same_table() {
901 let strings = urls();
903 let first = SymbolTable::train(&borrow(&strings));
904 let second = SymbolTable::train(&borrow(&strings));
905 assert_eq!(first.symbols, second.symbols);
906 }
907
908 #[test]
909 fn the_longest_match_wins_rather_than_the_first_one_found() {
910 let table = SymbolTable::build(vec![
911 Symbol::new(b"abc"),
912 Symbol::new(b"abcdef"),
913 Symbol::new(b"abcd"),
914 ]);
915 let mut out = Vec::new();
916 table.compress(b"abcdef", &mut out);
917 assert_eq!(out, vec![1]);
918 }
919
920 #[test]
921 fn a_symbol_longer_than_what_is_left_is_not_used() {
922 let table = SymbolTable::build(vec![Symbol::new(b"abcdef"), Symbol::new(b"ab")]);
923 let mut out = Vec::new();
924 table.compress(b"abcd", &mut out);
925 assert_eq!(out, vec![1, ESCAPE, b'c', ESCAPE, b'd']);
927 }
928
929 #[test]
930 fn concatenation_stops_at_eight_bytes() {
931 let long = Symbol::new(b"abcdef");
932 assert_eq!(long.concat(Symbol::new(b"ghijkl")).bytes(), b"abcdefgh");
933 assert_eq!(Symbol::new(b"ab").concat(Symbol::new(b"cd")).bytes(), b"abcd");
934 }
935
936 fn train_with_maps(samples: &[&[u8]]) -> SymbolTable {
939 use std::collections::HashMap;
940 let mut table = SymbolTable::empty();
941 for _ in 0..GENERATIONS {
942 let mut single = [0u32; IDS];
943 let mut pairs: HashMap<(u16, u16), u32> = HashMap::new();
944 for sample in samples {
945 let mut at = 0;
946 let mut previous: Option<u16> = None;
947 while at < sample.len() {
948 let (code, len) = table.match_at(sample, at);
949 let id =
950 if code == ESCAPE { 256 + u16::from(sample[at]) } else { u16::from(code) };
951 single[id as usize] += 1;
952 if let Some(previous) = previous {
953 *pairs.entry((previous, id)).or_insert(0) += 1;
954 }
955 previous = Some(id);
956 at += len;
957 }
958 }
959 let mut gains: HashMap<Symbol, u64> = HashMap::new();
960 for (id, count) in single.iter().enumerate().filter(|(_, count)| **count > 0) {
961 let symbol = symbol_of(&table, id as u16);
962 *gains.entry(symbol).or_insert(0) += u64::from(*count) * symbol.len() as u64;
963 }
964 for ((first, second), count) in &pairs {
965 let symbol = symbol_of(&table, *first).concat(symbol_of(&table, *second));
966 *gains.entry(symbol).or_insert(0) += u64::from(*count) * symbol.len() as u64;
967 }
968 let mut ranked: Vec<(Symbol, u64)> = gains.into_iter().collect();
969 ranked.sort_by(|left, right| right.1.cmp(&left.1).then(left.0.cmp(&right.0)));
970 ranked.truncate(MAX_SYMBOLS);
971 if ranked.is_empty() {
972 break;
973 }
974 table = SymbolTable::build(ranked.into_iter().map(|(symbol, _)| symbol).collect());
975 }
976 table
977 }
978
979 #[test]
980 fn flat_counts_train_the_same_table_as_hash_maps() {
981 let mut state = 0x9e37_79b9_7f4a_7c15u64;
982 let mut next = move || {
983 state ^= state << 13;
984 state ^= state >> 7;
985 state ^= state << 17;
986 state
987 };
988 let mut shapes: Vec<Vec<Vec<u8>>> = vec![urls(), Vec::new(), vec![Vec::new(); 3]];
989 shapes.push(
991 (0..400).map(|_| (0..12).map(|_| b"abc"[(next() % 3) as usize]).collect()).collect(),
992 );
993 shapes.push((0..300).map(|_| (0..40).map(|_| next() as u8).collect()).collect());
995 shapes.push(
997 (0..200)
998 .map(|index| format!("prefix-{}-suffix-{}", index % 7, index % 5).into_bytes())
999 .collect(),
1000 );
1001 for strings in &shapes {
1004 let samples = borrow(strings);
1005 assert_eq!(SymbolTable::train(&samples).symbols, train_with_maps(&samples).symbols);
1006 }
1007 }
1008}