binbuf/impls/
primitive.rs1use crate::{Fixed, entry::{Buf, BufConst, BufMut}, fixed::{self}};
2
3macro_rules! impl_instance_num {
4 ($ty: ty, $buf: ident, $len: literal) => {
5 fixed! {
6 buf! { pub struct $buf<P>($ty, P); }
7 impl I for $ty {
8 type Buf<P> = $buf<P>;
9 }
10 }
11
12 impl Fixed for $ty {
13 const LEN: usize = $len;
14 fn encode(&self, buf: BufMut<Self>) {
15 buf.0.copy_from_slice(&self.to_le_bytes());
16 }
17 }
18 impl fixed::Decode for $ty {
19 fn decode(buf: BufConst<Self>) -> Self {
20 Self::from_le_bytes(*unsafe { buf.0.array() })
21 }
22 }
23 };
24}
25
26impl_instance_num!(u8, U8Buf, 1);
27impl_instance_num!(u32, U32Buf, 4);
28impl_instance_num!(u64, U64Buf, 8);
29impl_instance_num!(u128, U128Buf, 16);
30
31impl_instance_num!(i8, I8Buf, 1);
32impl_instance_num!(i32, I32Buf, 4);
33impl_instance_num!(i64, I64Buf, 8);
34impl_instance_num!(i128, I128Buf, 16);
35
36impl_instance_num!(f32, F32Buf, 4);
37impl_instance_num!(f64, F64Buf, 8);
38
39fixed! {
40 buf! { pub struct BoolBuf<P>(bool, P); }
41 impl I for bool {
42 type Buf<P> = BoolBuf<P>;
43 }
44}
45
46impl Fixed for bool {
47 const LEN: usize = 1;
48 fn encode(&self, mut buf: BufMut<Self>) {
49 unsafe { *buf.0.slice().get_unchecked_mut(0) = *self as u8 }
50 }
51}
52impl fixed::Decode for bool {
53 fn decode(buf: BufConst<Self>) -> Self {
54 unsafe { if *buf.0.slice().get_unchecked(0) == 0 { false } else { true } }
55 }
56}
57
58fixed! {
59 buf! { pub struct CharBuf<P>(char, P); }
60 impl I for char {
61 type Buf<P> = CharBuf<P>;
62 }
63}
64
65impl Fixed for char {
66 const LEN: usize = 4;
67 fn encode(&self, buf: BufMut<Self>) {
68 self.encode_utf8(buf.0.into());
69 }
70}
71impl fixed::Decode for char {
72 fn decode(buf: BufConst<Self>) -> Self {
73 match Self::from_u32(u32::from_le_bytes(*unsafe { buf.0.array() })) {
74 Some(v) => v,
75 None => char::REPLACEMENT_CHARACTER
76 }
77 }
78}