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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! # nano-leb128
//!
//! Little endian base 128 variable-length code compression.
//!
//! # Usage
//!
//! Signed LEB128 compression/decompression:
//!
//! ```
//! use nano_leb128::SLEB128;
//!
//! fn rand_i64() -> i64 {
//!     // ...
//! #   0
//! }
//!
//! let mut buf = [0; 10];
//! let value = rand_i64();
//!
//! // Compress the value into the buffer.
//! let len = SLEB128::from(value).write_into(&mut buf).unwrap();
//!
//! // Decompress the value from the buffer.
//! let (decompressed, _len) = SLEB128::read_from(&buf[..len]).unwrap();
//!
//! assert_eq!(i64::from(decompressed), value);
//! ```
//!
//! Unsigned LEB128 compression/decompression:
//!
//! ```
//! use nano_leb128::ULEB128;
//!
//! fn rand_u64() -> u64 {
//!     // ...
//! #   0
//! }
//!
//! let mut buf = [0; 10];
//! let value = rand_u64();
//!
//! // Compress the value into the buffer.
//! let len = ULEB128::from(value).write_into(&mut buf).unwrap();
//!
//! // Decompress the value from the buffer.
//! let (decompressed, _len) = ULEB128::read_from(&buf[..len]).unwrap();
//!
//! assert_eq!(u64::from(decompressed), value);
//! ```
//!
//! # Features
//!
//! * `std` (enabled by default)
//!
//!    This enables extensions that are only available with the Rust standard
//!    library.
//!
//! * `std_io_ext`
//!
//!   Adds methods for reading/writing LEB128 compressed values from
//!   implementors of the traits in [`std::io`]. This feature requires the
//!   `std` feature and will automatically enable it if it is not already
//!   enabled.
//!
//! * `byteio_ext`
//!
//!   Adds methods for reading/writing LEB128 compressed values from
//!   implementors of the traits in [`byteio`]. This feature does not require
//!   the `std` feature.
//!
//! [`std::io`]: https://doc.rust-lang.org/std/io/index.html
//! [`byteio`]: https://docs.rs/byteio

#![no_std]
#![allow(clippy::nonminimal_bool)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_sign_loss)]

#[cfg(feature = "std")]
extern crate std;

use core::mem;

use byteio::{ReadBytes, ReadBytesExt, WriteBytes, WriteBytesExt};

/// A value that can be (de)serialized using _signed_ LEB128 variable length
/// compression.
///
/// # Examples
///
/// Deserializing a value that was serialized using signed LEB128 variable
/// length compression:
///
/// ```
/// use nano_leb128::SLEB128;
///
/// let buf = [0xC0, 0xBB, 0x78];
///
/// let (val, len) = SLEB128::read_from(&buf).unwrap();
///
/// assert_eq!(i64::from(val), -123456);
/// assert_eq!(len, 3);
/// ```
///
/// Serializing a value using signed LEB128 variable length compression:
///
/// ```
/// use nano_leb128::SLEB128;
///
/// let mut buf = [0; 3];
///
/// assert_eq!(SLEB128::from(-123456).write_into(&mut buf).unwrap(), 3);
/// assert_eq!(buf, [0xC0, 0xBB, 0x78]);
/// ```
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct SLEB128(i64);

impl From<SLEB128> for i64 {
    fn from(sleb128: SLEB128) -> Self {
        sleb128.0
    }
}

impl From<i64> for SLEB128 {
    fn from(val: i64) -> Self {
        Self(val)
    }
}

impl SLEB128 {
    /// Attempts to read a signed LEB128 compressed value from a buffer.
    ///
    /// On success this will return the decompressed value and the number of
    /// bytes that were read.
    pub fn read_from(buf: &[u8]) -> Result<(Self, usize), LEB128DecodeError> {
        <Self as LEB128>::read_from(buf)
    }

    /// Attempts to write a value into a buffer using signed LEB128
    /// compression.
    ///
    /// On success this will return the number of bytes that were written.
    pub fn write_into(self, buf: &mut [u8]) -> Result<usize, LEB128EncodeError> {
        <Self as LEB128>::write_into(self, buf)
    }

    /// Attempts to read a signed LEB128 compressed value from an implementor
    /// of [`std::io::Read`].
    ///
    /// **Note**: Requires the feature `std_io_ext`.
    ///
    /// On success this will return the decompressed value and the number of
    /// bytes that were read.
    ///
    /// [`std::io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
    #[cfg(feature = "std_io_ext")]
    pub fn read_from_std_io<R: ::std::io::Read>(reader: R) -> ::std::io::Result<(Self, usize)> {
        <Self as LEB128>::read_from_std_io(reader)
    }

    /// Attempts to write a value into an implementor of [`std::io::Write`]
    /// using signed LEB128 compression.
    ///
    /// **Note**: Requires the feature `std_io_ext`.
    ///
    /// On success this will return the number of bytes that were written.
    ///
    /// [`std::io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
    #[cfg(feature = "std_io_ext")]
    pub fn write_into_std_io<W: ::std::io::Write>(self, writer: W) -> ::std::io::Result<usize> {
        <Self as LEB128>::write_into_std_io(self, writer)
    }

    /// Attempts to read a signed LEB128 compressed value from an implementor
    /// of [`byteio::ReadBytes`].
    ///
    /// **Note**: Requires the feature `byteio_ext`.
    ///
    /// On success this will return the decompressed value and the number of
    /// bytes that were read.
    ///
    /// [`byteio::ReadBytes`]: https://docs.rs/byteio/latest/trait.ReadBytes.html
    #[cfg(feature = "byteio_ext")]
    pub fn read_from_byteio<'a, R: ReadBytes<'a>>(
        reader: R,
    ) -> Result<(Self, usize), LEB128DecodeError> {
        <Self as LEB128>::read_from_byteio(reader)
    }

    /// Attempts to write a value into an implementor of [`byteio::WriteBytes`]
    /// using signed LEB128 compression.
    ///
    /// **Note**: Requires the feature `byteio_ext`.
    ///
    /// On success this will return the number of bytes that were written.
    ///
    /// [`byteio::WriteBytes`]: https://docs.rs/byteio/latest/trait.WriteBytes.html
    #[cfg(feature = "byteio_ext")]
    pub fn write_into_byteio<W: WriteBytes>(self, writer: W) -> Result<usize, LEB128EncodeError> {
        <Self as LEB128>::write_into_byteio(self, writer)
    }
}

/// A value that can be (de)serialized using _unsigned_ LEB128 variable length
/// compression.
///
/// # Examples
///
/// Deserializing a value that was serialized using unsigned LEB128 variable
/// length compression:
///
/// ```
/// use nano_leb128::ULEB128;
///
/// let buf = [0xE5, 0x8E, 0x26];
///
/// let (val, len) = ULEB128::read_from(&buf).unwrap();
///
/// assert_eq!(u64::from(val), 624485);
/// assert_eq!(len, 3);
/// ```
///
/// Serializing a value using unsigned LEB128 variable length compression:
///
/// ```
/// use nano_leb128::ULEB128;
///
/// let mut buf = [0; 3];
///
/// assert_eq!(ULEB128::from(624485).write_into(&mut buf).unwrap(), 3);
/// assert_eq!(buf, [0xE5, 0x8E, 0x26]);
/// ```
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct ULEB128(u64);

impl From<ULEB128> for u64 {
    fn from(uleb128: ULEB128) -> Self {
        uleb128.0
    }
}

impl From<u64> for ULEB128 {
    fn from(val: u64) -> Self {
        Self(val)
    }
}

impl ULEB128 {
    /// Attempts to read an unsigned LEB128 compressed value from a buffer.
    ///
    /// On success this will return the decompressed value and the number of
    /// bytes that were read.
    pub fn read_from(buf: &[u8]) -> Result<(Self, usize), LEB128DecodeError> {
        <Self as LEB128>::read_from(buf)
    }

    /// Attempts to write a value into a buffer using unsigned LEB128
    /// compression.
    ///
    /// On success this will return the number of bytes that were written.
    pub fn write_into(self, buf: &mut [u8]) -> Result<usize, LEB128EncodeError> {
        <Self as LEB128>::write_into(self, buf)
    }

    /// Attempts to read an unsigned LEB128 compressed value from an
    /// implementor of [`std::io::Read`].
    ///
    /// **Note**: Requires the feature `std_io_ext`.
    ///
    /// On success this will return the decompressed value and the number of
    /// bytes that were read.
    ///
    /// [`std::io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
    #[cfg(feature = "std_io_ext")]
    pub fn read_from_std_io<R: ::std::io::Read>(reader: R) -> ::std::io::Result<(Self, usize)> {
        <Self as LEB128>::read_from_std_io(reader)
    }

    /// Attempts to write a value into an implementor of [`std::io::Write`]
    /// using unsigned LEB128 compression.
    ///
    /// **Note**: Requires the feature `std_io_ext`.
    ///
    /// On success this will return the number of bytes that were written.
    ///
    /// [`std::io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
    #[cfg(feature = "std_io_ext")]
    pub fn write_into_std_io<W: ::std::io::Write>(self, writer: W) -> ::std::io::Result<usize> {
        <Self as LEB128>::write_into_std_io(self, writer)
    }

    /// Attempts to read an unsigned LEB128 compressed value from an
    /// implementor of [`byteio::ReadBytes`].
    ///
    /// **Note**: Requires the feature `byteio_ext`.
    ///
    /// On success this will return the decompressed value and the number of
    /// bytes that were read.
    ///
    /// [`byteio::ReadBytes`]: https://docs.rs/byteio/latest/trait.ReadBytes.html
    #[cfg(feature = "byteio_ext")]
    pub fn read_from_byteio<'a, R: ReadBytes<'a>>(
        reader: R,
    ) -> Result<(Self, usize), LEB128DecodeError> {
        <Self as LEB128>::read_from_byteio(reader)
    }

    /// Attempts to write a value into an implementor of [`byteio::WriteBytes`]
    /// using unsigned LEB128 compression.
    ///
    /// **Note**: Requires the feature `byteio_ext`.
    ///
    /// On success this will return the number of bytes that were written.
    ///
    /// [`byteio::WriteBytes`]: https://docs.rs/byteio/latest/trait.WriteBytes.html
    #[cfg(feature = "byteio_ext")]
    pub fn write_into_byteio<W: WriteBytes>(self, writer: W) -> Result<usize, LEB128EncodeError> {
        <Self as LEB128>::write_into_byteio(self, writer)
    }
}

/// Errors that can occur when decoding LEB128 compressed values.
///
/// When compiled with the `std` feature this error implements
/// [`std::error::Error`], and [`Into`] for [`std::io::Error`].
///
/// [`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html
/// [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html
/// [`std::io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum LEB128DecodeError {
    /// More bytes required than are available to complete the deserialization.
    BufferOverflow,
    /// The compressed value represents a larger number than can be decoded.
    IntegerOverflow,
}

#[cfg(feature = "std")]
impl From<LEB128DecodeError> for ::std::io::Error {
    fn from(err: LEB128DecodeError) -> Self {
        match err {
            LEB128DecodeError::BufferOverflow => ::std::io::ErrorKind::UnexpectedEof.into(),
            LEB128DecodeError::IntegerOverflow => ::std::io::ErrorKind::InvalidData.into(),
        }
    }
}

/// Errors that can occur when encoding values using LEB128 compression.
///
/// When compiled with the `std` feature this error implements
/// [`std::error::Error`], and [`Into`] for [`std::io::Error`].
///
/// [`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html
/// [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html
/// [`std::io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum LEB128EncodeError {
    /// More bytes required than are available to complete the serialization.
    BufferOverflow,
}

#[cfg(feature = "std")]
impl From<LEB128EncodeError> for ::std::io::Error {
    fn from(err: LEB128EncodeError) -> Self {
        match err {
            LEB128EncodeError::BufferOverflow => ::std::io::ErrorKind::UnexpectedEof.into(),
        }
    }
}

/*
 *
 * impl
 *
 */

const LEB128_HIGH_ORDER_BIT: u8 = 1 << 7;
const LEB128_SIGN_BIT: u8 = 1 << 6;

trait LEB128Decode: Sized {
    fn leb128_decode<'a, R: ReadBytes<'a>>(reader: R) -> Result<Self, LEB128DecodeError>;
}

trait LEB128Encode {
    fn leb128_encode<W: WriteBytes>(self, writer: W) -> Result<(), LEB128EncodeError>;
}

trait LEB128: LEB128Decode + LEB128Encode {
    fn read_from(buf: &[u8]) -> Result<(Self, usize), LEB128DecodeError> {
        let mut reader = ::byteio::Reader::new(buf);
        let value = Self::leb128_decode(&mut reader)?;

        Ok((value, reader.num_bytes_read()))
    }

    fn write_into(self, buf: &mut [u8]) -> Result<usize, LEB128EncodeError> {
        let mut writer = ::byteio::Writer::new(buf);
        self.leb128_encode(&mut writer)?;

        Ok(writer.num_bytes_written())
    }

    #[cfg(feature = "std_io_ext")]
    fn read_from_std_io<R: ::std::io::Read>(mut reader: R) -> ::std::io::Result<(Self, usize)> {
        let mut buf = ::std::vec::Vec::with_capacity(10);

        loop {
            let mut byte = [0];
            reader.read_exact(&mut byte)?;
            buf.push(byte[0]);

            match Self::leb128_decode(&*buf) {
                Ok(val) => {
                    return Ok((val, buf.len()));
                }
                Err(err) if err == LEB128DecodeError::IntegerOverflow => {
                    return Err(err.into());
                }
                _ => (),
            }
        }
    }

    #[cfg(feature = "std_io_ext")]
    fn write_into_std_io<W: ::std::io::Write>(self, mut writer: W) -> ::std::io::Result<usize> {
        let mut buf = ::std::vec::Vec::with_capacity(10);
        self.leb128_encode(&mut buf)?;
        writer.write_all(&buf)?;

        Ok(buf.len())
    }

    #[cfg(feature = "byteio_ext")]
    fn read_from_byteio<'a, R: ReadBytes<'a>>(
        reader: R,
    ) -> Result<(Self, usize), LEB128DecodeError> {
        let mut reader = ::byteio::Reader::new(reader);
        let value = Self::leb128_decode(&mut reader)?;

        Ok((value, reader.num_bytes_read()))
    }

    #[cfg(feature = "byteio_ext")]
    fn write_into_byteio<W: WriteBytes>(self, writer: W) -> Result<usize, LEB128EncodeError> {
        let mut writer = ::byteio::Writer::new(writer);
        self.leb128_encode(&mut writer)?;

        Ok(writer.num_bytes_written())
    }
}

impl LEB128Decode for SLEB128 {
    fn leb128_decode<'a, R: ReadBytes<'a>>(mut reader: R) -> Result<Self, LEB128DecodeError> {
        let mut result = 0;
        let mut shift = 0;

        let byte = loop {
            let byte = reader
                .try_read_u8()
                .map_err(|_| LEB128DecodeError::BufferOverflow)?;

            if shift == 63 && byte != 0x00 && byte != !LEB128_HIGH_ORDER_BIT {
                return Err(LEB128DecodeError::IntegerOverflow);
            }

            result |= i64::from(byte & !LEB128_HIGH_ORDER_BIT) << shift;
            shift += 7;

            if byte & LEB128_HIGH_ORDER_BIT == 0 {
                break byte;
            }
        };

        if shift < 8 * mem::size_of::<i64>() && (byte & LEB128_SIGN_BIT) != 0 {
            result |= !0 << shift;
        }

        Ok(Self(result))
    }
}

impl LEB128Encode for SLEB128 {
    fn leb128_encode<W: WriteBytes>(self, mut writer: W) -> Result<(), LEB128EncodeError> {
        let Self(mut value) = self;
        let mut more = true;

        while more {
            let mut byte = (value as u8) & !LEB128_HIGH_ORDER_BIT;
            value >>= 7;

            if value == 0 && (byte & LEB128_SIGN_BIT) == 0
                || value == -1 && (byte & LEB128_SIGN_BIT) != 0
            {
                more = false;
            } else {
                byte |= LEB128_HIGH_ORDER_BIT;
            }

            writer
                .try_write_u8(byte)
                .map_err(|_| LEB128EncodeError::BufferOverflow)?;
        }

        Ok(())
    }
}

impl LEB128 for SLEB128 {}

impl LEB128Decode for ULEB128 {
    fn leb128_decode<'a, R: ReadBytes<'a>>(mut reader: R) -> Result<Self, LEB128DecodeError> {
        let mut result = 0;
        let mut shift = 0;

        loop {
            let byte = reader
                .try_read_u8()
                .map_err(|_| LEB128DecodeError::BufferOverflow)?;

            if shift == 63 && byte > 1 {
                return Err(LEB128DecodeError::IntegerOverflow);
            }

            result |= u64::from(byte & !LEB128_HIGH_ORDER_BIT) << shift;

            if byte & LEB128_HIGH_ORDER_BIT == 0 {
                return Ok(Self(result));
            }

            shift += 7;
        }
    }
}

impl LEB128Encode for ULEB128 {
    fn leb128_encode<W: WriteBytes>(self, mut writer: W) -> Result<(), LEB128EncodeError> {
        let Self(mut value) = self;

        loop {
            let mut byte = (value as u8) & !LEB128_HIGH_ORDER_BIT;
            value >>= 7;

            if value != 0 {
                byte |= LEB128_HIGH_ORDER_BIT;
            }

            writer
                .try_write_u8(byte)
                .map_err(|_| LEB128EncodeError::BufferOverflow)?;

            if value == 0 {
                return Ok(());
            }
        }
    }
}

impl LEB128 for ULEB128 {}