delta_encoding/
decoder.rs1use num_traits::WrappingAdd;
2
3#[derive(Debug, Default, Copy, Clone)]
5pub struct DeltaDecoder<T> {
6 current: T,
7}
8
9impl<T: WrappingAdd + Copy> DeltaDecoder<T> {
10 pub fn decode(&mut self, value: T) -> T {
11 self.current = self.current.wrapping_add(&value);
12 self.current
13 }
14}
15
16#[derive(Clone, Debug)]
18#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
19pub struct DeltaDecoderIter<I>
20where
21 I: Iterator,
22 <I as Iterator>::Item: WrappingAdd + Copy,
23{
24 iter: I,
25 decoder: DeltaDecoder<I::Item>,
26}
27
28impl<I> Iterator for DeltaDecoderIter<I>
29where
30 I: Iterator,
31 <I as Iterator>::Item: WrappingAdd + Copy,
32{
33 type Item = I::Item;
34
35 fn next(&mut self) -> Option<Self::Item> {
36 Some(self.decoder.decode(self.iter.next()?))
37 }
38
39 fn size_hint(&self) -> (usize, Option<usize>) {
40 self.iter.size_hint()
41 }
42}
43
44impl<I> ExactSizeIterator for DeltaDecoderIter<I>
45where
46 I: ExactSizeIterator,
47 <I as Iterator>::Item: WrappingAdd + Copy,
48{
49}
50
51pub trait DeltaDecoderExt: Iterator
52where
53 <Self as Iterator>::Item: Default + Copy + WrappingAdd,
54{
55 fn original(self) -> DeltaDecoderIter<Self>
72 where
73 Self: Sized,
74 {
75 DeltaDecoderIter {
76 iter: self,
77 decoder: DeltaDecoder::default(),
78 }
79 }
80}
81
82impl<I> DeltaDecoderExt for I
83where
84 I: Iterator,
85 <I as Iterator>::Item: Default + Copy + WrappingAdd,
86{
87}
88
89#[cfg(test)]
90mod tests {
91 use super::*;
92 use crate::tests::TEST_DATA;
93
94 fn run(original: &[i64], encoded: &[i64]) {
95 let mut dec = DeltaDecoder::default();
96 let result: Vec<i64> = encoded.iter().map(|&v| dec.decode(v)).collect();
97 assert_eq!(result, original, "decoded from: {encoded:?}");
98
99 let result: Vec<i64> = encoded.iter().copied().original().collect();
100 assert_eq!(result, original, "iter().copied() encoded: {encoded:?}");
101 }
102
103 #[test]
104 fn test() {
105 for &(original, encoded) in TEST_DATA {
106 run(original, encoded);
107 }
108 }
109}