jkl 0.2.1

Asset compression and packing tool
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
416
417
418
419
420
421
422
423
424
425
426
//! Variable-length Elias delta encoding for unsigned integers.
//!
//! Small values are encoded in fewer bits, making this scheme well-suited for
//! compressing data with a skewed distribution. The [`Vle`] newtype provides a
//! convenient [`VarCode`] implementation.

use std::{error::Error, fmt, io, ops};

use crate::{
    bits::{ReadBits, WriteBits},
    encode::VarCode,
    math::Delta,
};

/// Trait abstracting over Rust unsigned integer primitives for use in
/// variable-length Elias delta encoding.
///
/// Implementing this trait allows a type to be encoded and decoded with the
/// [`encode`] / [`decode`] family of functions.
pub trait Unsigned:
    fmt::Debug + Ord + ops::Add<Output = Self> + ops::Sub<Output = Self> + Eq + Copy + 'static
{
    const BITS: u32;
    const MAX: Self;
    const ZERO: Self;
    const ONE: Self;

    fn next(self) -> Self;

    fn leading_zeros(self) -> u32;
    fn reverse_bits(self) -> Self;
    fn pow2(v: u32) -> Self;

    // Returns bytes in little-endian order.
    fn to_le_bytes(self) -> [u8; 16];
    fn from_le_bytes(bytes: [u8; 16]) -> Self;
}

macro_rules! impl_unsigned {
    ($($t:ty),* $(,)?) => {
        $(
            impl Unsigned for $t {
                const BITS: u32 = Self::BITS;
                const MAX: Self = Self::MAX;
                const ZERO: Self = 0;
                const ONE: Self = 1;

                fn next(self) -> Self {
                    self + 1
                }

                #[inline]
                fn leading_zeros(self) -> u32 {
                    self.leading_zeros()
                }

                #[inline]
                fn reverse_bits(self) -> Self {
                    self.reverse_bits()
                }

                #[inline]
                fn pow2(v: u32) -> Self {
                    1 << v
                }

                #[inline]
                fn to_le_bytes(self) -> [u8; 16] {
                    let le_bytes = self.to_le_bytes();
                    let mut buffer = [0u8; 16];
                    buffer[..le_bytes.len()].copy_from_slice(&le_bytes);
                    buffer
                }

                #[inline]
                fn from_le_bytes(bytes: [u8; 16]) -> Self {
                    let mut le_bytes = [0u8; size_of::<Self>()];
                    le_bytes.copy_from_slice(&bytes[..size_of::<Self>()]);
                    Self::from_le_bytes(le_bytes)
                }
            }
        )*
    };
}

impl_unsigned!(u8, u16, u32, u64, u128, usize);

fn gamma_bit_len<T>(v: T) -> u32
where
    T: Unsigned,
{
    debug_assert_ne!(v, T::ZERO);

    let msb = T::BITS - v.leading_zeros() - 1;

    // Unary bits for `msb` and 1 bit for the first '1'.
    let unary_bits = msb + 1;

    // Tail bits in little-endian order.
    let tail_bits = msb;

    unary_bits + tail_bits
}

#[inline]
fn encode_gamma<T, W>(v: T, writer: &mut WriteBits<W>) -> io::Result<()>
where
    T: Unsigned,
    W: io::Write,
{
    debug_assert_ne!(v, T::ZERO);

    let msb = T::BITS - v.leading_zeros() - 1;

    // Unary encode `msb` as n zeros followed by a one.
    for _ in 0..msb {
        writer.write_bit(false)?;
    }
    writer.write_bit(true)?;

    // tail = v - 2^msb;
    let tail: T = v - T::pow2(msb);

    if msb > 0 {
        // write remaining bits in LE.
        writer.write_all_bits(&tail.to_le_bytes(), 0, msb as usize)?;
    }

    Ok(())
}

/// Returns the number of bits required to Elias-delta-encode `v` (which may be zero).
pub fn encode_bit_len<T>(v: T) -> usize
where
    T: Unsigned,
{
    let msb = if v < T::MAX {
        // Can safely compute v+1 without overflow since v < MAX.
        let v = v.next();

        // n = floor(log2(v))
        

        T::BITS - v.leading_zeros() - 1
    } else {
        // v+1 is 2^BITS, so pos of MSB is BITS and the rest bits are 0.
        T::BITS
    };

    // gamma encode `msb + 1`.
    let gamma_bits = gamma_bit_len(msb + 1);

    let tail_bits = msb;

    (gamma_bits + tail_bits) as usize
}

/// Returns the number of bits required to Elias-delta-encode `v` (which must be non-zero).
pub fn encode_non_zero_bit_len<T>(v: T) -> usize
where
    T: Unsigned,
{
    // n = floor(log2(v))
    let msb = T::BITS - v.leading_zeros() - 1;

    // gamma encode `msb + 1`.
    let gamma_bits = gamma_bit_len(msb + 1);

    let tail_bits = msb;

    (gamma_bits + tail_bits) as usize
}

/// Encode unsigned value `v`.
///
/// Encodes `v+1` using Elias delta code.
pub fn encode<T, W>(v: T, writer: &mut WriteBits<W>) -> io::Result<()>
where
    T: Unsigned,
    W: io::Write,
{
    let (msb, tail) = if v < T::MAX {
        // Can safely compute v+1 without overflow since v < MAX.
        let v = v.next();

        // n = floor(log2(v))
        let msb = T::BITS - v.leading_zeros() - 1;

        let tail = v - T::pow2(msb);

        (msb, tail)
    } else {
        // v+1 is 2^BITS, so pos of MSB is BITS and the rest bits are 0.
        (T::BITS, T::ZERO)
    };

    // gamma encode `msb + 1`.
    encode_gamma(msb + 1, &mut *writer)?;

    if msb > 0 {
        // write the remainig bits in LE
        writer.write_all_bits(&tail.to_le_bytes(), 0, msb as usize)?;
    }

    Ok(())
}

/// Encode unsigned value `v`.
///
/// Encodes `v` using Elias delta code.
pub fn encode_non_zero<T, W>(v: T, writer: &mut WriteBits<W>) -> io::Result<()>
where
    T: Unsigned,
    W: io::Write,
{
    assert_ne!(v, T::ZERO);

    // n = floor(log2(v))
    let msb = T::BITS - v.leading_zeros() - 1;

    let tail = v - T::pow2(msb);

    // gamma encode `msb + 1`.
    encode_gamma(msb + 1, &mut *writer)?;

    if msb > 0 {
        // write the remainig bits in LE
        writer.write_all_bits(&tail.to_le_bytes(), 0, msb as usize)?;
    }

    Ok(())
}

/// Error indicating that a decoded value exceeds the range of the target integer type.
#[derive(Clone, Copy, Debug)]
pub struct TooLarge;

impl fmt::Display for TooLarge {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Value is too large to decode")
    }
}

impl Error for TooLarge {}

#[inline]
fn decode_gamma<T, R>(reader: &mut ReadBits<R>) -> io::Result<T>
where
    T: Unsigned,
    R: io::Read,
{
    // Count leading zeros until the first '1' (which is the MSB of the value).
    let mut msb: u32 = 0;
    loop {
        let bit = reader.read_bit()?;
        if bit {
            break;
        }

        msb += 1;

        if msb == T::BITS {
            // if msb == BITS, the value is 2^BITS, which is out of range for T.
            return Err(io::Error::new(io::ErrorKind::InvalidData, TooLarge));
        }
    }

    // Read remaining bits.
    let mut buffer = [0u8; 16];
    reader.read_all_bits(&mut buffer, 0, msb as usize)?;
    let tail = T::from_le_bytes(buffer);

    let value = T::pow2(msb) + tail;

    Ok(value)
}

/// Decode unsigned value.
///
/// Reads the value encoded by `encode` function.
/// Returns an error if the encoded value is too large to fit in T.
pub fn decode<T, R>(reader: &mut ReadBits<R>) -> io::Result<T>
where
    T: Unsigned,
    R: io::Read,
{
    let msb = decode_gamma::<u32, R>(reader)? - 1;

    let mut buffer = [0u8; 16];
    reader.read_all_bits(&mut buffer, 0, msb as usize)?;

    let tail = T::from_le_bytes(buffer);

    if msb >= T::BITS {
        // If msb == BITS and tail is not zero, the value is larger than 2^BITS - 1, which is out of range for T.
        if msb > T::BITS || tail != T::ZERO {
            return Err(io::Error::new(io::ErrorKind::InvalidData, TooLarge));
        }

        return Ok(T::MAX);
    }

    Ok(T::pow2(msb) + tail - T::ONE)
}

/// Decode unsigned value.
///
/// Reads the value encoded by `encode` function.
/// Returns an error if the encoded value is too large to fit in T.
pub fn decode_non_zero<T, R>(reader: &mut ReadBits<R>) -> io::Result<T>
where
    T: Unsigned,
    R: io::Read,
{
    let msb = decode_gamma::<u32, R>(reader)? - 1;

    let mut buffer = [0u8; 16];
    reader.read_all_bits(&mut buffer, 0, msb as usize)?;

    let tail = T::from_le_bytes(buffer);

    if msb >= T::BITS {
        return Err(io::Error::new(io::ErrorKind::InvalidData, TooLarge));
    }

    Ok(T::pow2(msb) + tail)
}

/// Newtype wrapper that implements [`VarCode`] via Elias delta encoding.
///
/// Wrapping an unsigned integer in `Vle` allows it to be serialized
/// with [`VarCode::var_write`] / [`VarCode::var_read`] using variable-length
/// bit encoding, where small values use fewer bits.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Vle<T>(pub T);

impl<T> Delta for Vle<T>
where
    T: Delta,
{
    #[inline]
    fn delta(self, base: Self) -> Vle<T> {
        Vle(self.0.delta(base.0))
    }

    #[inline]
    fn from_delta(base: Self, delta: Vle<T>) -> Self {
        Vle(T::from_delta(base.0, delta.0))
    }
}

impl<T> VarCode for Vle<T>
where
    T: Unsigned,
{
    fn var_bit_len(&self) -> usize {
        encode_bit_len(self.0)
    }

    fn var_write(&self, write: &mut WriteBits<impl io::Write>) -> io::Result<()> {
        encode(self.0, write)
    }

    fn var_read(read: &mut ReadBits<impl io::Read>) -> io::Result<Self> {
        let value = decode(read)?;
        Ok(Self(value))
    }
}

#[cfg(test)]
mod tests {
    use crate::zigzaq::ZigZag;

    use super::*;

    #[test]
    fn zero_is_one_bit() {
        let mut buffer = Vec::new();
        let mut writer = WriteBits::new(&mut buffer);
        encode(0u32, &mut writer).unwrap();
        writer.finish().unwrap();
        assert_eq!(buffer, [0b1]);
    }

    #[test]
    fn roundtrip_unsigned() {
        let vals: Vec<u64> = vec![0, 1, 2, 3, 4, 5, 7, 8, 15, 16, 255, 256, 1024, 1 << 40];
        let mut buffer = Vec::new();

        let mut writer = WriteBits::new(&mut buffer);
        for &v in &vals {
            encode(v, &mut writer).unwrap();
        }
        writer.finish().unwrap();

        let mut reader = ReadBits::new(&buffer[..]);
        let mut decoded = Vec::new();

        for _ in 0..vals.len() {
            decoded.push(decode::<u64, _>(&mut reader).unwrap());
        }

        assert_eq!(decoded, vals);
    }

    #[test]
    fn roundtrip_signed() {
        let vals: Vec<i32> = vec![0, -1, 1, -2, 2, -55, 55, -1000, 1000];
        let mut buffer = Vec::new();

        let mut writer = WriteBits::new(&mut buffer);
        for &v in &vals {
            encode(v.zigzag(), &mut writer).unwrap();
        }
        writer.finish().unwrap();

        let mut reader = ReadBits::new(&buffer[..]);
        let mut decoded = Vec::new();

        for _ in 0..vals.len() {
            decoded.push(i32::zagzig(decode(&mut reader).unwrap()));
        }

        assert_eq!(decoded, vals);
    }
}