Skip to main content

fennec_modbus/protocol/codec/
encoder.rs

1use alloc::vec::Vec;
2
3use bytes::BufMut;
4
5pub trait Encode {
6    fn encode_to(&self, buf: &mut impl BufMut);
7
8    fn to_bytes(&self) -> Vec<u8> {
9        let mut bytes = Vec::new();
10        self.encode_to(&mut bytes);
11        bytes
12    }
13}
14
15impl<T: Encode, const N: usize> Encode for [T; N] {
16    fn encode_to(&self, buf: &mut impl BufMut) {
17        for item in self {
18            item.encode_to(buf);
19        }
20    }
21}
22
23macro_rules! impl_encode {
24    ($type:ty => $encode:ident) => {
25        impl Encode for $type {
26            fn encode_to(&self, buf: &mut impl BufMut) {
27                buf.$encode(*self);
28            }
29        }
30    };
31}
32
33impl_encode!(u16 => put_u16);
34impl_encode!(i16 => put_i16);
35impl_encode!(u32 => put_u32);
36impl_encode!(i32 => put_i32);
37impl_encode!(u64 => put_u64);
38impl_encode!(i64 => put_i64);
39impl_encode!(u128 => put_u128);
40impl_encode!(i128 => put_i128);