Skip to main content

grafeo_core/storage/
runlength.rs

1//! Run-length encoding for highly repetitive data.
2//!
3//! Run-length encoding (RLE) compresses sequences with consecutive repeated
4//! values by storing each unique value once along with its run length.
5//!
6//! | Data pattern | Compression ratio |
7//! | ------------ | ----------------- |
8//! | Constant value | ~100x |
9//! | Few distinct values, long runs | 10-50x |
10//! | Many short runs | 2-5x |
11//! | Random data | < 1x (expansion) |
12//!
13//! # Example
14//!
15//! ```no_run
16//! use grafeo_core::storage::RunLengthEncoding;
17//!
18//! // Compress data with many repeated values
19//! let values = vec![1, 1, 1, 2, 2, 3, 3, 3, 3, 3];
20//! let encoded = RunLengthEncoding::encode(&values);
21//!
22//! println!("Runs: {}", encoded.run_count()); // 3 runs
23//! println!("Compression: {:.1}x", encoded.compression_ratio()); // ~3.3x
24//!
25//! // Decode back to original
26//! let decoded = encoded.decode();
27//! assert_eq!(values, decoded);
28//! ```
29
30use std::io::{self, Read};
31
32/// A run in run-length encoding: a value and how many times it repeats.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct Run<T> {
35    /// The value for this run.
36    pub value: T,
37    /// Number of consecutive occurrences.
38    pub length: u64,
39}
40
41impl<T> Run<T> {
42    /// Creates a new run.
43    #[must_use]
44    pub fn new(value: T, length: u64) -> Self {
45        Self { value, length }
46    }
47}
48
49/// Run-length encoded data for u64 values.
50///
51/// Stores sequences of (value, count) pairs. Achieves excellent compression
52/// when data has long runs of repeated values.
53#[derive(Debug, Clone)]
54pub struct RunLengthEncoding {
55    /// The runs: each is (value, count).
56    runs: Vec<Run<u64>>,
57    /// Total number of values (sum of all run lengths).
58    total_count: usize,
59}
60
61impl<'a> IntoIterator for &'a RunLengthEncoding {
62    type Item = u64;
63    type IntoIter = RunLengthIterator<'a>;
64
65    fn into_iter(self) -> Self::IntoIter {
66        self.iter()
67    }
68}
69
70impl RunLengthEncoding {
71    /// Encodes a slice of u64 values using run-length encoding.
72    ///
73    /// # Example
74    /// ```no_run
75    /// # use grafeo_core::storage::runlength::RunLengthEncoding;
76    /// let values = vec![1, 1, 1, 2, 2, 3];
77    /// let encoded = RunLengthEncoding::encode(&values);
78    /// // Results in 3 runs: (1, 3), (2, 2), (3, 1)
79    /// ```
80    #[must_use]
81    pub fn encode(values: &[u64]) -> Self {
82        if values.is_empty() {
83            return Self {
84                runs: Vec::new(),
85                total_count: 0,
86            };
87        }
88
89        let mut runs = Vec::new();
90        let mut current_value = values[0];
91        let mut current_length = 1u64;
92
93        for &value in &values[1..] {
94            if value == current_value {
95                current_length += 1;
96            } else {
97                runs.push(Run::new(current_value, current_length));
98                current_value = value;
99                current_length = 1;
100            }
101        }
102
103        // Don't forget the last run
104        runs.push(Run::new(current_value, current_length));
105
106        Self {
107            runs,
108            total_count: values.len(),
109        }
110    }
111
112    /// Creates a run-length encoding from pre-built runs.
113    #[must_use]
114    pub fn from_runs(runs: Vec<Run<u64>>) -> Self {
115        let total_count = runs.iter().map(|r| r.length as usize).sum();
116        Self { runs, total_count }
117    }
118
119    /// Decodes back to the original values.
120    #[must_use]
121    pub fn decode(&self) -> Vec<u64> {
122        let mut values = Vec::with_capacity(self.total_count);
123
124        for run in &self.runs {
125            for _ in 0..run.length {
126                values.push(run.value);
127            }
128        }
129
130        values
131    }
132
133    /// Returns the number of runs.
134    #[must_use]
135    pub fn run_count(&self) -> usize {
136        self.runs.len()
137    }
138
139    /// Returns the total number of values represented.
140    #[must_use]
141    pub fn total_count(&self) -> usize {
142        self.total_count
143    }
144
145    /// Returns the runs.
146    #[must_use]
147    pub fn runs(&self) -> &[Run<u64>] {
148        &self.runs
149    }
150
151    /// Returns true if there are no values.
152    #[must_use]
153    pub fn is_empty(&self) -> bool {
154        self.total_count == 0
155    }
156
157    /// Returns the compression ratio (original size / encoded size).
158    ///
159    /// Values > 1.0 indicate compression, < 1.0 indicate expansion.
160    #[must_use]
161    pub fn compression_ratio(&self) -> f64 {
162        if self.runs.is_empty() {
163            return 1.0;
164        }
165
166        // Original: total_count * 8 bytes
167        // Encoded: runs.len() * 16 bytes (8 for value, 8 for length)
168        let original_size = self.total_count * 8;
169        let encoded_size = self.runs.len() * 16;
170
171        if encoded_size == 0 {
172            return 1.0;
173        }
174
175        original_size as f64 / encoded_size as f64
176    }
177
178    /// Returns true if run-length encoding is beneficial for this data.
179    ///
180    /// Returns true when compression ratio > 1.0 (actual compression achieved).
181    #[must_use]
182    pub fn is_beneficial(&self) -> bool {
183        self.compression_ratio() > 1.0
184    }
185
186    /// Returns the memory size in bytes of the encoded representation.
187    #[must_use]
188    pub fn encoded_size(&self) -> usize {
189        // Each run: 8 bytes value + 8 bytes length
190        self.runs.len() * 16
191    }
192
193    /// Serializes the run-length encoding to bytes.
194    pub fn to_bytes(&self) -> Vec<u8> {
195        let mut bytes = Vec::with_capacity(8 + self.runs.len() * 16);
196
197        // Write run count
198        bytes.extend_from_slice(&(self.runs.len() as u64).to_le_bytes());
199
200        // Write each run
201        for run in &self.runs {
202            bytes.extend_from_slice(&run.value.to_le_bytes());
203            bytes.extend_from_slice(&run.length.to_le_bytes());
204        }
205
206        bytes
207    }
208
209    /// Deserializes run-length encoding from bytes.
210    pub fn from_bytes(bytes: &[u8]) -> io::Result<Self> {
211        let mut cursor = io::Cursor::new(bytes);
212
213        // Read run count
214        let mut buf = [0u8; 8];
215        cursor.read_exact(&mut buf)?;
216        let run_count = u64::from_le_bytes(buf) as usize;
217
218        // Read runs
219        let mut runs = Vec::with_capacity(run_count);
220        for _ in 0..run_count {
221            cursor.read_exact(&mut buf)?;
222            let value = u64::from_le_bytes(buf);
223
224            cursor.read_exact(&mut buf)?;
225            let length = u64::from_le_bytes(buf);
226
227            runs.push(Run::new(value, length));
228        }
229
230        Ok(Self::from_runs(runs))
231    }
232
233    /// Gets the value at a specific index without full decompression.
234    ///
235    /// Returns None if index is out of bounds.
236    #[must_use]
237    pub fn get(&self, index: usize) -> Option<u64> {
238        if index >= self.total_count {
239            return None;
240        }
241
242        let mut offset = 0usize;
243        for run in &self.runs {
244            let run_end = offset + run.length as usize;
245            if index < run_end {
246                return Some(run.value);
247            }
248            offset = run_end;
249        }
250
251        None
252    }
253
254    /// Returns an iterator over the decoded values.
255    pub fn iter(&self) -> RunLengthIterator<'_> {
256        RunLengthIterator {
257            runs: &self.runs,
258            run_index: 0,
259            within_run: 0,
260        }
261    }
262}
263
264/// Iterator over run-length encoded values.
265pub struct RunLengthIterator<'a> {
266    runs: &'a [Run<u64>],
267    run_index: usize,
268    within_run: u64,
269}
270
271impl Iterator for RunLengthIterator<'_> {
272    type Item = u64;
273
274    fn next(&mut self) -> Option<Self::Item> {
275        while self.run_index < self.runs.len() {
276            let run = &self.runs[self.run_index];
277            if self.within_run < run.length {
278                self.within_run += 1;
279                return Some(run.value);
280            }
281            self.run_index += 1;
282            self.within_run = 0;
283        }
284        None
285    }
286
287    fn size_hint(&self) -> (usize, Option<usize>) {
288        let remaining: u64 = self.runs[self.run_index..]
289            .iter()
290            .map(|r| r.length)
291            .sum::<u64>()
292            - self.within_run;
293        (remaining as usize, Some(remaining as usize))
294    }
295}
296
297impl ExactSizeIterator for RunLengthIterator<'_> {}
298
299/// Run-length encoding for signed integers.
300///
301/// Uses zigzag encoding internally for efficient storage.
302#[derive(Debug, Clone)]
303pub struct SignedRunLengthEncoding {
304    inner: RunLengthEncoding,
305}
306
307impl SignedRunLengthEncoding {
308    /// Encodes signed integers using run-length encoding.
309    #[must_use]
310    pub fn encode(values: &[i64]) -> Self {
311        let unsigned: Vec<u64> = values.iter().map(|&v| zigzag_encode(v)).collect();
312        Self {
313            inner: RunLengthEncoding::encode(&unsigned),
314        }
315    }
316
317    /// Decodes back to signed integers.
318    #[must_use]
319    pub fn decode(&self) -> Vec<i64> {
320        self.inner.decode().into_iter().map(zigzag_decode).collect()
321    }
322
323    /// Returns the compression ratio.
324    #[must_use]
325    pub fn compression_ratio(&self) -> f64 {
326        self.inner.compression_ratio()
327    }
328
329    /// Returns the number of runs.
330    #[must_use]
331    pub fn run_count(&self) -> usize {
332        self.inner.run_count()
333    }
334
335    /// Serializes to bytes.
336    pub fn to_bytes(&self) -> Vec<u8> {
337        self.inner.to_bytes()
338    }
339
340    /// Deserializes from bytes.
341    pub fn from_bytes(bytes: &[u8]) -> io::Result<Self> {
342        Ok(Self {
343            inner: RunLengthEncoding::from_bytes(bytes)?,
344        })
345    }
346}
347
348/// Zigzag encodes a signed integer to unsigned.
349#[inline]
350#[must_use]
351pub fn zigzag_encode(n: i64) -> u64 {
352    ((n << 1) ^ (n >> 63)) as u64
353}
354
355/// Zigzag decodes an unsigned integer to signed.
356#[inline]
357#[must_use]
358pub fn zigzag_decode(n: u64) -> i64 {
359    ((n >> 1) as i64) ^ -((n & 1) as i64)
360}
361
362/// Analyzes data to determine if run-length encoding is beneficial.
363pub struct RunLengthAnalyzer;
364
365impl RunLengthAnalyzer {
366    /// Estimates the compression ratio without actually encoding.
367    ///
368    /// This is faster than encoding for decision-making.
369    #[must_use]
370    pub fn estimate_ratio(values: &[u64]) -> f64 {
371        if values.is_empty() {
372            return 1.0;
373        }
374
375        // Count runs
376        let mut run_count = 1usize;
377        for i in 1..values.len() {
378            if values[i] != values[i - 1] {
379                run_count += 1;
380            }
381        }
382
383        // Original: values.len() * 8 bytes
384        // Encoded: run_count * 16 bytes
385        let original = values.len() * 8;
386        let encoded = run_count * 16;
387
388        if encoded == 0 {
389            return 1.0;
390        }
391
392        original as f64 / encoded as f64
393    }
394
395    /// Returns true if run-length encoding would be beneficial.
396    #[must_use]
397    pub fn is_beneficial(values: &[u64]) -> bool {
398        Self::estimate_ratio(values) > 1.0
399    }
400
401    /// Returns the average run length in the data.
402    #[must_use]
403    pub fn average_run_length(values: &[u64]) -> f64 {
404        if values.is_empty() {
405            return 0.0;
406        }
407
408        let mut run_count = 1usize;
409        for i in 1..values.len() {
410            if values[i] != values[i - 1] {
411                run_count += 1;
412            }
413        }
414
415        values.len() as f64 / run_count as f64
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422
423    #[test]
424    fn test_encode_decode_basic() {
425        let values = vec![1, 1, 1, 2, 2, 3, 3, 3, 3, 3];
426        let encoded = RunLengthEncoding::encode(&values);
427
428        assert_eq!(encoded.run_count(), 3);
429        assert_eq!(encoded.total_count(), 10);
430
431        let decoded = encoded.decode();
432        assert_eq!(values, decoded);
433    }
434
435    #[test]
436    fn test_encode_empty() {
437        let values: Vec<u64> = vec![];
438        let encoded = RunLengthEncoding::encode(&values);
439
440        assert_eq!(encoded.run_count(), 0);
441        assert_eq!(encoded.total_count(), 0);
442        assert!(encoded.is_empty());
443
444        let decoded = encoded.decode();
445        assert!(decoded.is_empty());
446    }
447
448    #[test]
449    fn test_encode_single() {
450        let values = vec![42];
451        let encoded = RunLengthEncoding::encode(&values);
452
453        assert_eq!(encoded.run_count(), 1);
454        assert_eq!(encoded.total_count(), 1);
455
456        let decoded = encoded.decode();
457        assert_eq!(values, decoded);
458    }
459
460    #[test]
461    fn test_encode_all_same() {
462        let values = vec![7u64; 1000];
463        let encoded = RunLengthEncoding::encode(&values);
464
465        assert_eq!(encoded.run_count(), 1);
466        assert_eq!(encoded.total_count(), 1000);
467
468        // Should compress very well
469        let ratio = encoded.compression_ratio();
470        assert!(ratio > 50.0, "Expected ratio > 50, got {}", ratio);
471
472        let decoded = encoded.decode();
473        assert_eq!(values, decoded);
474    }
475
476    #[test]
477    fn test_encode_all_different() {
478        let values: Vec<u64> = (0..100).collect();
479        let encoded = RunLengthEncoding::encode(&values);
480
481        assert_eq!(encoded.run_count(), 100);
482        assert_eq!(encoded.total_count(), 100);
483
484        // Should not compress (expand by 2x)
485        let ratio = encoded.compression_ratio();
486        assert!(ratio < 1.0, "Expected ratio < 1, got {}", ratio);
487
488        let decoded = encoded.decode();
489        assert_eq!(values, decoded);
490    }
491
492    #[test]
493    fn test_compression_ratio() {
494        // Perfect case: all same values
495        let all_same = vec![1u64; 100];
496        let encoded = RunLengthEncoding::encode(&all_same);
497        assert!(encoded.compression_ratio() > 1.0);
498        assert!(encoded.is_beneficial());
499
500        // Bad case: all different values
501        let all_diff: Vec<u64> = (0..100).collect();
502        let encoded = RunLengthEncoding::encode(&all_diff);
503        assert!(encoded.compression_ratio() < 1.0);
504        assert!(!encoded.is_beneficial());
505    }
506
507    #[test]
508    fn test_serialization() {
509        let values = vec![1, 1, 1, 2, 2, 3, 3, 3, 3, 3];
510        let encoded = RunLengthEncoding::encode(&values);
511
512        let bytes = encoded.to_bytes();
513        let decoded_encoding = RunLengthEncoding::from_bytes(&bytes).unwrap();
514
515        assert_eq!(encoded.run_count(), decoded_encoding.run_count());
516        assert_eq!(encoded.decode(), decoded_encoding.decode());
517    }
518
519    #[test]
520    fn test_get_index() {
521        let values = vec![1, 1, 1, 2, 2, 3, 3, 3, 3, 3];
522        let encoded = RunLengthEncoding::encode(&values);
523
524        assert_eq!(encoded.get(0), Some(1));
525        assert_eq!(encoded.get(2), Some(1));
526        assert_eq!(encoded.get(3), Some(2));
527        assert_eq!(encoded.get(4), Some(2));
528        assert_eq!(encoded.get(5), Some(3));
529        assert_eq!(encoded.get(9), Some(3));
530        assert_eq!(encoded.get(10), None);
531    }
532
533    #[test]
534    fn test_iterator() {
535        let values = vec![1, 1, 1, 2, 2, 3];
536        let encoded = RunLengthEncoding::encode(&values);
537
538        let iterated: Vec<u64> = encoded.iter().collect();
539        assert_eq!(values, iterated);
540    }
541
542    #[test]
543    fn test_signed_integers() {
544        let values = vec![-5, -5, -5, 0, 0, 10, 10, 10, 10];
545        let encoded = SignedRunLengthEncoding::encode(&values);
546
547        assert_eq!(encoded.run_count(), 3);
548
549        let decoded = encoded.decode();
550        assert_eq!(values, decoded);
551    }
552
553    #[test]
554    fn test_signed_serialization() {
555        let values = vec![-100, -100, 0, 0, 0, 100];
556        let encoded = SignedRunLengthEncoding::encode(&values);
557
558        let bytes = encoded.to_bytes();
559        let decoded_encoding = SignedRunLengthEncoding::from_bytes(&bytes).unwrap();
560
561        assert_eq!(encoded.decode(), decoded_encoding.decode());
562    }
563
564    #[test]
565    fn test_zigzag() {
566        assert_eq!(zigzag_encode(0), 0);
567        assert_eq!(zigzag_encode(-1), 1);
568        assert_eq!(zigzag_encode(1), 2);
569        assert_eq!(zigzag_encode(-2), 3);
570        assert_eq!(zigzag_encode(2), 4);
571
572        for i in -1000i64..1000 {
573            assert_eq!(zigzag_decode(zigzag_encode(i)), i);
574        }
575    }
576
577    #[test]
578    fn test_analyzer_estimate() {
579        let all_same = vec![1u64; 100];
580        let ratio = RunLengthAnalyzer::estimate_ratio(&all_same);
581        assert!(ratio > 1.0);
582        assert!(RunLengthAnalyzer::is_beneficial(&all_same));
583
584        let all_diff: Vec<u64> = (0..100).collect();
585        let ratio = RunLengthAnalyzer::estimate_ratio(&all_diff);
586        assert!(ratio < 1.0);
587        assert!(!RunLengthAnalyzer::is_beneficial(&all_diff));
588    }
589
590    #[test]
591    fn test_analyzer_average_run_length() {
592        let values = vec![1, 1, 1, 2, 2, 3, 3, 3, 3, 3]; // 3 runs, 10 values
593        let avg = RunLengthAnalyzer::average_run_length(&values);
594        assert!((avg - 3.33).abs() < 0.1);
595
596        let all_same = vec![1u64; 100];
597        let avg = RunLengthAnalyzer::average_run_length(&all_same);
598        assert!((avg - 100.0).abs() < 0.1);
599    }
600
601    #[test]
602    fn test_from_runs() {
603        let runs = vec![Run::new(1, 3), Run::new(2, 2), Run::new(3, 5)];
604        let encoded = RunLengthEncoding::from_runs(runs);
605
606        assert_eq!(encoded.run_count(), 3);
607        assert_eq!(encoded.total_count(), 10);
608        assert_eq!(encoded.decode(), vec![1, 1, 1, 2, 2, 3, 3, 3, 3, 3]);
609    }
610}