tsz-compress 1.1.4

Delta-delta, Delta compression for time series data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use core::fmt::Binary;
use num_traits::PrimInt;

use crate::prelude::*;
use crate::v2::consts::headers;

use super::halfvec::{HalfVec, HalfWord};

///
/// A trait for types that can be represented as bits.
///
/// This trait is for types that can be used in binary operations and have a constant size in bits.
/// It provides methods for zigzag encoding, which is a form of variable-length encoding that
/// efficiently encodes signed integers.
///
pub trait Bits: PrimInt + Binary {
    const BITS: usize;

    /// Language limitations prevent us from writing simple math expressions
    /// ((self << 1) ^ self >> (Self::BITS - 1)) as u32
    fn zigzag(self) -> usize;

    /// Return the zigzag encoding and number of bits required to represent the value
    #[inline(always)]
    fn zigzag_bits(self) -> (usize, usize) {
        let zbits = self.zigzag();
        (zbits, (usize::BITS - zbits.leading_zeros()) as usize)
    }
}

impl Bits for i8 {
    const BITS: usize = 8;

    #[inline(always)]
    fn zigzag(self) -> usize {
        ((self << 1) ^ self >> (Self::BITS - 1)) as u8 as usize
    }
}

impl Bits for i16 {
    const BITS: usize = 16;

    #[inline(always)]
    fn zigzag(self) -> usize {
        ((self << 1) ^ self >> (Self::BITS - 1)) as u16 as usize
    }
}

impl Bits for i32 {
    const BITS: usize = 32;

    #[inline(always)]
    fn zigzag(self) -> usize {
        ((self << 1) ^ self >> (Self::BITS - 1)) as u32 as usize
    }
}

#[cfg(target_pointer_width = "64")]
impl Bits for i64 {
    const BITS: usize = 64;

    #[inline(always)]
    fn zigzag(self) -> usize {
        ((self << 1) ^ self >> (Self::BITS - 1)) as u64 as usize
    }
}

#[inline(always)]
fn push_three_bits(q: &mut CompressionQueue<10>, buf: &mut HalfVec) {
    const N: usize = 10;
    const N1: usize = N - 1;
    buf.push(HalfWord::Half(headers::THREE_BITS_TEN_SAMPLES));
    let mut word: usize = 0;
    let values = q.pop_n::<N>();
    for value in values.iter().take(N1) {
        word |= value;
        word <<= 3;
    }
    word |= values[N1];
    buf.push(HalfWord::Full(word as u32));
}

#[inline(always)]
fn push_six_bits(q: &mut CompressionQueue<10>, buf: &mut HalfVec) {
    const N: usize = 5;
    const N1: usize = N - 1;
    buf.push(HalfWord::Half(headers::SIX_BITS_FIVE_SAMPLES));
    let mut word: usize = 0;
    let values = q.pop_n::<N>();
    for value in values.iter().take(N1) {
        word |= value;
        word <<= 6;
    }
    word |= values[N1];
    buf.push(HalfWord::Full(word as u32));
}

#[inline(always)]
fn push_eight_bits(q: &mut CompressionQueue<10>, buf: &mut HalfVec) {
    const N: usize = 4;
    const N1: usize = N - 1;
    buf.push(HalfWord::Half(headers::EIGHT_BITS_FOUR_SAMPLES));
    let mut word: usize = 0;
    let values = q.pop_n::<N>();
    for value in values.iter().take(N1) {
        word |= value;
        word <<= 8;
    }
    word |= values[N1];
    buf.push(HalfWord::Full(word as u32));
}

#[inline(always)]
fn push_ten_bits(q: &mut CompressionQueue<10>, buf: &mut HalfVec) {
    const N: usize = 3;
    const N1: usize = N - 1;
    buf.push(HalfWord::Half(headers::TEN_BITS_THREE_SAMPLES));
    let mut word: usize = 0b00 << 10;
    let values = q.pop_n::<N>();
    for value in values.iter().take(N1) {
        word |= value;
        word <<= 10;
    }
    word |= values[N1];
    buf.push(HalfWord::Full(word as u32));
}

#[inline(always)]
fn push_sixteen_bits(q: &mut CompressionQueue<10>, buf: &mut HalfVec) {
    const N: usize = 2;
    const N1: usize = N - 1;
    buf.push(HalfWord::Half(headers::SIXTEEN_BITS_TWO_SAMPLES));
    let mut word: usize = 0b00 << 10;
    let values = q.pop_n::<N>();
    for value in values.iter().take(N1) {
        word |= value;
        word <<= 16;
    }
    word |= values[N1];
    buf.push(HalfWord::Full(word as u32));
}

#[inline(always)]
unsafe fn push_32_or_64_bits(q: &mut CompressionQueue<10>, buf: &mut HalfVec) {
    let value = q.pop().unwrap_unchecked();
    if value <= u32::MAX as usize {
        buf.push(HalfWord::Half(headers::THIRTY_TWO_BITS_ONE_SAMPLE));
    } else {
        buf.push(HalfWord::Half(headers::SIXTY_FOUR_BITS_ONE_SAMPLE));
        buf.push(HalfWord::Full((value >> 32) as u32));
    }
    buf.push(HalfWord::Full(value as u32));
}

///
/// A trait that emits bits according to the most efficient case of Delta Compression.
///
/// This trait provides methods for emitting bits and flushing the remaining bits in the queue.
/// The methods return the number of elements popped from the queue.
///
pub trait EmitDeltaBits {
    /// Emits bits according to the most efficient case of Delta Compression.
    /// Returns the number of elements popped from the queue.
    fn emit_delta_bits(&mut self, out: &mut HalfVec) -> usize;
    fn flush_delta_bits(&mut self, out: &mut HalfVec) -> usize;
}

impl EmitDeltaBits for CompressionQueue<10> {
    #[inline(always)]
    fn emit_delta_bits(&mut self, out: &mut HalfVec) -> usize {
        let mut fits = [true; 5];

        // Check if the values will fit in the cases
        let values = self.peak_bitcounts::<10>();
        for (index, bits_required) in values.into_iter().enumerate() {
            if (index < 2) & (bits_required > 16) {
                fits[4] = false;
            }
            if (index < 3) & (bits_required > 10) {
                fits[3] = false;
            }
            if (index < 4) & (bits_required > 8) {
                fits[2] = false;
            }
            if (index < 5) & (bits_required > 6) {
                fits[1] = false;
            }
            if (index < 10) & (bits_required > 3) {
                fits[0] = false;
            }
        }

        // Emit according to priority of cases
        if fits[0] {
            push_three_bits(self, out);
            10
        } else if fits[1] {
            push_six_bits(self, out);
            5
        } else if fits[2] {
            push_eight_bits(self, out);
            4
        } else if fits[3] {
            push_ten_bits(self, out);
            3
        } else if fits[4] {
            push_sixteen_bits(self, out);
            2
        } else {
            unsafe {
                push_32_or_64_bits(self, out);
            }
            1
        }
    }

    #[inline(always)]
    fn flush_delta_bits(&mut self, out: &mut HalfVec) -> usize {
        let mut fits = [true; 5];

        // Can not emit with any case of delta compression if queue is empty
        if self.is_empty() {
            return 0;
        }

        // Can not emit with case v of delta compression if number of samples < 10
        if self.len() < 10 {
            fits[0] = false;
        }

        // Can not emit with case iv of delta compression if number of samples < 5.
        if self.len() < 5 {
            fits[1] = false;
        }

        // Can not emit with case iii of delta compression if number of samples < 4
        if self.len() < 4 {
            fits[2] = false;
        }

        // Can not emit with case ii of delta compression if number of samples < 3
        if self.len() < 3 {
            fits[3] = false;
        }

        // Can not emit with case ii of delta compression if number of samples < 2
        if self.len() < 2 {
            fits[4] = false;
        }

        // Check if the values will fit in the cases
        let values = self.peak_bitcounts::<10>();
        for (index, bits_required) in values.into_iter().enumerate() {
            if (index < 2) & (bits_required > 16) {
                fits[4] = false;
            }
            if (index < 3) & (bits_required > 10) {
                fits[3] = false;
            }
            if (index < 4) & (bits_required > 8) {
                fits[2] = false;
            }
            if (index < 5) & (bits_required > 6) {
                fits[1] = false;
            }
            if (index < 10) & (bits_required > 3) {
                fits[0] = false;
            }
        }

        // Emit according to priority of cases
        if fits[0] {
            push_three_bits(self, out);
            10
        } else if fits[1] {
            push_six_bits(self, out);
            5
        } else if fits[2] {
            push_eight_bits(self, out);
            4
        } else if fits[3] {
            push_ten_bits(self, out);
            3
        } else if fits[4] {
            push_sixteen_bits(self, out);
            2
        } else {
            unsafe {
                push_32_or_64_bits(self, out);
            }
            1
        }
    }
}

// Delta-Delta Encoding
///
/// A trait that provides method for emitting bits according to the most efficient case of Delta-Delta Compression.
///
pub trait EmitDeltaDeltaBits {
    /// Emits bits according to the most efficient case of Delta-Delta Compression.
    /// Returns the number of elements popped from the queue.
    fn emit_delta_delta_bits(&mut self, out: &mut HalfVec) -> usize;
}

///
/// A helper function that emits bits according to the most efficient case of Delta-Delta Compression.
fn emit_popped_values<const N: usize>(
    bitcounts: &[usize; N],
    values: &[usize; N],
    out: &mut HalfVec,
) {
    for (bits, value) in bitcounts.iter().zip(values.iter()) {
        match bits {
            0 => out.push(HalfWord::Half(0b0000)),
            1..=5 => {
                let zigzag = (value & 0b1_1111) as u8;
                out.push(HalfWord::Byte(0b0010_0000 | zigzag));
            }
            6..=9 => {
                let zigzag = (value & 0b1_1111_1111) as u16;
                out.push(HalfWord::Half(0b0100 | (zigzag >> 8) as u8));
                out.push(HalfWord::Byte(zigzag as u8));
            }
            10..=16 => {
                let zigzag = (value & 0b1111_1111_1111_1111) as u16;
                out.push(HalfWord::Half(0b0110));
                out.push(HalfWord::Byte((zigzag >> 8) as u8));
                out.push(HalfWord::Byte(zigzag as u8));
            }
            _ => {
                out.push(HalfWord::Half(0b0111));
                out.push(HalfWord::Full(*value as u32));
            }
        }
    }
}

impl EmitDeltaDeltaBits for CompressionQueue<2> {
    fn emit_delta_delta_bits(&mut self, out: &mut HalfVec) -> usize {
        match self.len() {
            2 => {
                let bitcounts = self.peak_bitcounts::<2>();
                let values = self.pop_n::<2>();
                emit_popped_values(&bitcounts, &values, out);
                2
            }
            1 => {
                let bitcounts = self.peak_bitcounts::<1>();
                let values = self.pop_n::<1>();
                emit_popped_values(&bitcounts, &values, out);
                1
            }
            _ => 0,
        }
    }
}

///
/// Writes a 128-bit integer to a HalfVec.
///
/// This function takes a mutable reference to a HalfVec and a 128-bit integer.
/// It converts the integer to a 128-bit unsigned integer and pushes it to the HalfVec in 32-bit chunks.
///
pub fn write_i128_bits(buf: &mut HalfVec, i: i128) {
    let i = i as u128;
    buf.push(HalfWord::Full((i >> 96) as u32));
    buf.push(HalfWord::Full((i >> 64) as u32));
    buf.push(HalfWord::Full((i >> 32) as u32));
    buf.push(HalfWord::Full(i as u32));
}

///
/// Writes a 64-bit integer to a HalfVec.
///
/// This function takes a mutable reference to a HalfVec and a 64-bit integer.
/// It converts the integer to a 64-bit unsigned integer and pushes it to the HalfVec in 32-bit chunks.
///
pub fn write_i64_bits(buf: &mut HalfVec, i: i64) {
    let i = i as u64;
    buf.push(HalfWord::Full((i >> 32) as u32));
    buf.push(HalfWord::Full(i as u32));
}

///
/// Writes a 32-bit integer to a HalfVec.
///
/// This function takes a mutable reference to a HalfVec and a 32-bit integer.
/// It pushes the integer to the HalfVec as a 32-bit unsigned integer.
///
pub fn write_i32_bits(buf: &mut HalfVec, i: i32) {
    buf.push(HalfWord::Full(i as u32));
}

///
/// Writes a 16-bit integer to a HalfVec.
///
/// This function takes a mutable reference to a HalfVec and a 16-bit integer.
/// It converts the integer to a 16-bit unsigned integer and pushes it to the HalfVec in 8-bit chunks.
///
pub fn write_i16_bits(buf: &mut HalfVec, i: i16) {
    let i = i as u16;
    buf.push(HalfWord::Byte((i >> 8) as u8));
    buf.push(HalfWord::Byte(i as u8));
}

///
/// Writes an 8-bit integer to a HalfVec.
///
/// This function takes a mutable reference to a HalfVec and an 8-bit integer.
/// It pushes the integer to the HalfVec as an 8-bit unsigned integer.
///
pub fn write_i8_bits(buf: &mut HalfVec, i: i8) {
    buf.push(HalfWord::Byte(i as u8));
}