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
use std::convert::TryInto;

use crate::data_types::{NumberLike, SignedLike};
use crate::errors::QCompressResult;

macro_rules! impl_signed {
  ($t: ty, $unsigned: ty, $header_byte: expr) => {
    impl SignedLike for $t {
      const ZERO: Self = 0;

      fn wrapping_add(self, other: Self) -> Self {
        self.wrapping_add(other)
      }

      fn wrapping_sub(self, other: Self) -> Self {
        self.wrapping_sub(other)
      }
    }

    impl NumberLike for $t {
      const HEADER_BYTE: u8 = $header_byte;
      const PHYSICAL_BITS: usize = Self::BITS as usize;

      type Signed = Self;
      type Unsigned = $unsigned;

      fn to_signed(self) -> Self::Signed {
        self
      }

      fn from_signed(signed: Self::Signed) -> Self {
        signed
      }

      fn to_unsigned(self) -> Self::Unsigned {
        self.wrapping_sub(Self::MIN) as $unsigned
      }

      fn from_unsigned(off: Self::Unsigned) -> Self {
        Self::MIN.wrapping_add(off as $t)
      }

      fn to_bytes(self) -> Vec<u8> {
        self.to_be_bytes().to_vec()
      }

      fn from_bytes(bytes: Vec<u8>) -> QCompressResult<Self> {
        Ok(Self::from_be_bytes(bytes.try_into().unwrap()))
      }
    }
  }
}

impl_signed!(i16, u16, 13);
impl_signed!(i32, u32, 3);
impl_signed!(i64, u64, 1);
impl_signed!(i128, u128, 10);