mih_rs/
codeint.rs

1use std::io::{Read, Write};
2
3use anyhow::Result;
4
5use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
6
7use num_traits::int::PrimInt;
8use num_traits::{FromPrimitive, ToPrimitive};
9
10/// Generic trait of binary codes.
11pub trait CodeInt: PrimInt + FromPrimitive + ToPrimitive + Popcnt + Default {
12    fn dimensions() -> usize;
13    fn serialize_into<W: Write>(&self, writer: W) -> Result<()>;
14    fn deserialize_from<R: Read>(reader: R) -> Result<Self>;
15}
16
17impl CodeInt for u8 {
18    fn dimensions() -> usize {
19        8
20    }
21
22    fn serialize_into<W: Write>(&self, mut writer: W) -> Result<()> {
23        writer.write_u8(*self)?;
24        Ok(())
25    }
26
27    fn deserialize_from<R: Read>(mut reader: R) -> Result<Self> {
28        let x = reader.read_u8()?;
29        Ok(x)
30    }
31}
32
33impl CodeInt for u16 {
34    fn dimensions() -> usize {
35        16
36    }
37
38    fn serialize_into<W: Write>(&self, mut writer: W) -> Result<()> {
39        writer.write_u16::<LittleEndian>(*self)?;
40        Ok(())
41    }
42
43    fn deserialize_from<R: Read>(mut reader: R) -> Result<Self> {
44        let x = reader.read_u16::<LittleEndian>()?;
45        Ok(x)
46    }
47}
48
49impl CodeInt for u32 {
50    fn dimensions() -> usize {
51        32
52    }
53
54    fn serialize_into<W: Write>(&self, mut writer: W) -> Result<()> {
55        writer.write_u32::<LittleEndian>(*self)?;
56        Ok(())
57    }
58
59    fn deserialize_from<R: Read>(mut reader: R) -> Result<Self> {
60        let x = reader.read_u32::<LittleEndian>()?;
61        Ok(x)
62    }
63}
64
65impl CodeInt for u64 {
66    fn dimensions() -> usize {
67        64
68    }
69
70    fn serialize_into<W: Write>(&self, mut writer: W) -> Result<()> {
71        writer.write_u64::<LittleEndian>(*self)?;
72        Ok(())
73    }
74
75    fn deserialize_from<R: Read>(mut reader: R) -> Result<Self> {
76        let x = reader.read_u64::<LittleEndian>()?;
77        Ok(x)
78    }
79}
80
81/// Generic trait for pop-countable integers.
82pub trait Popcnt {
83    fn popcnt(&self) -> u32;
84}
85
86impl Popcnt for u8 {
87    fn popcnt(&self) -> u32 {
88        self.count_ones()
89    }
90}
91
92impl Popcnt for u16 {
93    fn popcnt(&self) -> u32 {
94        self.count_ones()
95    }
96}
97
98impl Popcnt for u32 {
99    fn popcnt(&self) -> u32 {
100        self.count_ones()
101    }
102}
103
104impl Popcnt for u64 {
105    fn popcnt(&self) -> u32 {
106        self.count_ones()
107    }
108}