bin_codec/
impls.rs

1use crate::*;
2use std::mem::size_of;
3macro_rules! check_eob {
4    ($target:expr, $offset:expr, $bits: expr) => {
5        if $target < $offset || $target - $offset < $bits {
6            return Err(Error::UnexpectEndOfBuff);
7        }
8    };
9}
10macro_rules! impl_number {
11    (
12        $($ty:ty),*
13    ) => {
14        $(
15            impl EncodeBe for $ty {
16                #[inline(always)]
17                fn encode_offset<T>(&self, target: &mut [u8], _ctx: &mut T, offset: &mut usize, bits: usize) {
18                    let v = self.to_be();
19                    let size = size_of::<$ty>() * 8;
20                    unsafe {
21                        crate::utils::bit_copy(target.as_mut_ptr(), offset, &v as *const $ty as *const u8, size - bits, bits);
22                        // let target_ptr = target.as_mut_ptr();
23                        // let v = &v as *const $ty as *const u8;
24                        // let mut v_start = size - bits;
25                        // bit_copy!(target_ptr, offset, v, v_start, bits, u8);
26                    }
27                }
28
29                #[inline(always)]
30                fn bits_with_user_define(&self, bits: Option<usize>) -> usize { bits.unwrap_or(size_of::<$ty>() * 8) }
31            }
32
33            impl EncodeLe for $ty {
34                #[inline(always)]
35                fn encode_offset<T>(&self, target: &mut [u8], _ctx: &mut T, offset: &mut usize, bits: usize) {
36                    // let size = size_of::<$ty>() * 8;
37                    let v = self.to_le();
38                    unsafe {
39                        crate::utils::bit_copy(target.as_mut_ptr(), offset, &v as *const $ty as *const u8, 0, bits);
40                    }
41                }
42
43                #[inline(always)]
44                fn bits_with_user_define(&self, bits: Option<usize>) -> usize { bits.unwrap_or(size_of::<$ty>() * 8) }
45            }
46
47            impl DecodeBe for $ty {
48                type Context = ();
49                #[inline(always)]
50                fn decode_offset(data: &[u8], offset: &mut usize, _: &mut ShouldDecode, _: &mut Self::Context, bits: usize) -> Result<Self> {
51                    let size = size_of::<$ty>() * 8;
52                    let mut v: $ty = 0;
53                    println!(">> {} {} {}", data.len(), *offset, bits);
54                    check_eob!(data.len() * 8, *offset, std::mem::size_of::<$ty>());
55                    unsafe {
56                        crate::utils::bit_copy(&mut v as *mut $ty as *mut u8, &mut (size - bits), data.as_ptr(), *offset, bits);
57                    }
58                    *offset += bits;
59                    Ok(v.to_be())
60                }
61                #[inline(always)]
62                fn default_bits() -> usize {
63                    size_of::<$ty>() * 8
64                }
65            }
66
67            impl DecodeLe for $ty {
68                type Context = ();
69                #[inline(always)]
70                fn decode_offset(data: &[u8], offset: &mut usize, _: &mut ShouldDecode, _: &mut Self::Context, bits: usize) -> Result<Self> {
71                    check_eob!(data.len() * 8, *offset, std::mem::size_of::<$ty>());
72                    let mut v: $ty = 0;
73                    unsafe {
74                        crate::utils::bit_copy(&mut v as *mut $ty as *mut u8, &mut 0, data.as_ptr(), *offset, bits);
75                    }
76                    *offset += bits;
77                    Ok(v.to_le())
78                }
79                #[inline(always)]
80                fn default_bits() -> usize {
81                    size_of::<$ty>() * 8
82                }
83            }
84        )*
85    }
86}
87
88macro_rules! impl_float {
89    (
90        $($ty:ty),*
91    ) => {
92        $(
93            impl EncodeBe for $ty {
94                #[inline(always)]
95                fn encode_offset<T>(&self, target: &mut [u8], _ctx: &mut T, offset: &mut usize, _bits: usize) {
96                    let size = size_of::<$ty>() * 8;
97                    unsafe {
98                        crate::utils::bit_copy(target.as_mut_ptr(), offset, self as *const $ty as *const u8, 0, size);
99                    }
100                }
101
102                #[inline(always)]
103                fn bits_with_user_define(&self, bits: Option<usize>) -> usize { bits.unwrap_or(size_of::<$ty>() * 8) }
104            }
105
106            impl EncodeLe for $ty {
107                #[inline(always)]
108                fn encode_offset<T>(&self, target: &mut [u8], _ctx: &mut T, offset: &mut usize, _bits: usize) {
109                    let size = size_of::<$ty>() * 8;
110                    unsafe {
111                        crate::utils::bit_copy(target.as_mut_ptr(), offset, self as *const $ty as *const u8, 0, size);
112                    }
113                }
114
115                #[inline(always)]
116                fn bits_with_user_define(&self, bits: Option<usize>) -> usize { bits.unwrap_or(size_of::<$ty>() * 8) }
117            }
118
119            impl DecodeBe for $ty {
120                type Context = ();
121                #[inline(always)]
122                fn decode_offset(data: &[u8], offset: &mut usize, _: &mut ShouldDecode, _: &mut Self::Context, _bits: usize) -> Result<Self> {
123                    check_eob!(data.len() * 8, *offset, std::mem::size_of::<$ty>());
124                    let size = size_of::<$ty>() * 8;
125                    let mut v: $ty = 0.;
126                    unsafe {
127                        crate::utils::bit_copy(&mut v as *mut $ty as *mut u8, &mut 0, data.as_ptr(), *offset, size);
128                    }
129                    *offset += size;
130                    Ok(v)
131                }
132                #[inline(always)]
133                fn default_bits() -> usize {
134                    size_of::<$ty>() * 8
135                }
136            }
137
138            impl DecodeLe for $ty {
139                type Context = ();
140                #[inline(always)]
141                fn decode_offset(data: &[u8], offset: &mut usize, _: &mut ShouldDecode, _: &mut Self::Context, _bits: usize) -> Result<Self> {
142                    check_eob!(data.len() * 8, *offset, std::mem::size_of::<$ty>());
143                    let size = size_of::<$ty>() * 8;
144                    let mut v: $ty = 0.;
145                    unsafe {
146                        crate::utils::bit_copy(&mut v as *mut $ty as *mut u8, &mut 0, data.as_ptr(), *offset, size);
147                    }
148                    *offset += size;
149                    Ok(v)
150                }
151                #[inline(always)]
152                fn default_bits() -> usize {
153                    size_of::<$ty>() * 8
154                }
155            }
156        )*
157    }
158}
159
160impl_number!(u8, i8, u16, i16, u32, i32, u64, i64, u128, i128);
161impl_float!(f32, f64);
162
163impl EncodeBe for bool {
164    #[inline(always)]
165    fn encode_offset<T>(&self, target: &mut [u8], _ctx: &mut T, offset: &mut usize, _bits: usize) {
166        // assert_eq!(bits, 1, "`bits` of bool type must be 1");
167        unsafe {
168            let v = self;
169            crate::utils::bit_copy(
170                target.as_mut_ptr(),
171                offset,
172                v as *const bool as *const u8,
173                7,
174                1,
175            );
176        }
177    }
178    fn bits_with_user_define(&self, _bits: Option<usize>) -> usize {
179        1
180    }
181}
182
183impl EncodeLe for bool {
184    #[inline(always)]
185    fn encode_offset<T>(&self, target: &mut [u8], _ctx: &mut T, offset: &mut usize, _bits: usize) {
186        // assert_eq!(bits, 1, "`bits` of bool type must be 1");
187        unsafe {
188            let v = self;
189            crate::utils::bit_copy(
190                target.as_mut_ptr(),
191                offset,
192                v as *const bool as *const u8,
193                7,
194                1,
195            );
196        }
197    }
198    fn bits_with_user_define(&self, _bits: Option<usize>) -> usize {
199        1
200    }
201}
202
203impl DecodeBe for bool {
204    type Context = ();
205    #[inline(always)]
206    fn decode_offset(
207        data: &[u8],
208        offset: &mut usize,
209        _: &mut ShouldDecode,
210        _: &mut Self::Context,
211        _bits: usize
212    ) -> Result<Self> {
213        check_eob!(data.len() * 8, *offset, 1);
214        let size = 1;
215        let mut v = false;
216        unsafe {
217            crate::utils::bit_copy(
218                &mut v as *mut bool as *mut u8,
219                &mut 7,
220                data.as_ptr(),
221                *offset,
222                size,
223            );
224        }
225        *offset += size;
226        Ok(v)
227    }
228    #[inline(always)]
229    fn default_bits() -> usize {
230        1
231    }
232}
233
234impl DecodeLe for bool {
235    type Context = ();
236    #[inline(always)]
237    fn decode_offset(
238        data: &[u8],
239        offset: &mut usize,
240        _: &mut ShouldDecode,
241        _: &mut Self::Context,
242        _bits: usize
243    ) -> Result<Self> {
244        check_eob!(data.len() * 8, *offset, 1);
245        let size = 1;
246        let mut v = false;
247        unsafe {
248            crate::utils::bit_copy(
249                &mut v as *mut bool as *mut u8,
250                &mut 7,
251                data.as_ptr(),
252                *offset,
253                size,
254            );
255        }
256        *offset += size;
257        Ok(v)
258    }
259    #[inline(always)]
260    fn default_bits() -> usize {
261        1
262    }
263}
264
265impl<E: EncodeBe> EncodeBe for Vec<E> {
266    #[inline(always)]
267    fn encode_offset<T>(&self, target: &mut [u8], ctx: &mut T, offset: &mut usize, bits: usize) {
268        for i in self {
269            i.encode_offset(target, ctx, offset, bits);
270        }
271    }
272    #[inline(always)]
273    fn bits_with_user_define(&self, bits: Option<usize>) -> usize {
274        self.iter().map(|i| i.bits_with_user_define(bits)).sum()
275    }
276}
277
278impl<E: EncodeLe> EncodeLe for Vec<E> {
279    #[inline(always)]
280    fn encode_offset<T>(&self, target: &mut [u8], ctx: &mut T, offset: &mut usize, bits: usize) {
281        for i in self {
282            i.encode_offset(target, ctx, offset, bits);
283        }
284    }
285    #[inline(always)]
286    fn bits_with_user_define(&self, bits: Option<usize>) -> usize {
287        self.iter().map(|i| i.bits_with_user_define(bits)).sum()
288    }
289}
290
291impl<E: EncodeBe> EncodeBe for Option<E> {
292    #[inline(always)]
293    fn encode_offset<T>(&self, target: &mut [u8], ctx: &mut T, offset: &mut usize, bits: usize) {
294        for i in self {
295            i.encode_offset(target, ctx, offset, bits);
296        }
297    }
298    #[inline(always)]
299    fn bits_with_user_define(&self, bits: Option<usize>) -> usize {
300        self.iter().map(|i| i.bits_with_user_define(bits)).sum()
301    }
302}
303
304impl<E: EncodeLe> EncodeLe for Option<E> {
305    #[inline(always)]
306    fn encode_offset<T>(&self, target: &mut [u8], ctx: &mut T, offset: &mut usize, bits: usize) {
307        for i in self {
308            i.encode_offset(target, ctx, offset, bits);
309        }
310    }
311    #[inline(always)]
312    fn bits_with_user_define(&self, bits: Option<usize>) -> usize {
313        self.iter().map(|i| i.bits_with_user_define(bits)).sum()
314    }
315}
316
317impl<E: DecodeBe> DecodeBe for Vec<E> {
318    type Context = E::Context;
319    #[inline(always)]
320    fn decode_offset(
321        data: &[u8],
322        offset: &mut usize,
323        sd: &mut ShouldDecode,
324        ctx: &mut Self::Context,
325        bits: usize,
326    ) -> Result<Self> {
327        match sd {
328            ShouldDecode::Count(count) => {
329                let mut rt = Vec::with_capacity(*count);
330                for _ in 0..*count {
331                    let i = DecodeBe::decode_offset(data, offset, sd, ctx, bits)?;
332                    rt.push(i);
333                }
334                Ok(rt)
335            }
336            ShouldDecode::HasNext(_) => {
337                let mut rt = Vec::new();
338                while let ShouldDecode::HasNext(true) = sd {
339                    let i = DecodeBe::decode_offset(data, offset, sd, ctx, bits)?;
340                    rt.push(i);
341                }
342                Ok(rt)
343            }
344            _ => panic!("must set `count` or `has_next` on `Vec` field"),
345        }
346    }
347    #[inline(always)]
348    fn default_bits() -> usize {
349        E::default_bits()
350    }
351}
352
353impl<E: DecodeLe> DecodeLe for Vec<E> {
354    type Context = E::Context;
355    #[inline(always)]
356    fn decode_offset(
357        data: &[u8],
358        offset: &mut usize,
359        sd: &mut ShouldDecode,
360        ctx: &mut Self::Context,
361        bits: usize,
362    ) -> Result<Self> {
363        match sd {
364            ShouldDecode::Count(count) => {
365                let mut rt = Vec::with_capacity(*count);
366                for _ in 0..*count {
367                    let i = DecodeLe::decode_offset(data, offset, sd, ctx, bits)?;
368                    rt.push(i);
369                }
370                Ok(rt)
371            }
372            ShouldDecode::HasNext(_) => {
373                let mut rt = Vec::new();
374                while let ShouldDecode::HasNext(true) = sd {
375                    let i = DecodeLe::decode_offset(data, offset, sd, ctx, bits)?;
376                    rt.push(i);
377                }
378                Ok(rt)
379            }
380            _ => panic!("must set `count` or `has_next` on `Vec` field"),
381        }
382    }
383    #[inline(always)]
384    fn default_bits() -> usize {
385        E::default_bits()
386    }
387}
388
389impl<E: DecodeBe> DecodeBe for Option<E> {
390    type Context = E::Context;
391    #[inline(always)]
392    fn decode_offset(
393        data: &[u8],
394        offset: &mut usize,
395        sd: &mut ShouldDecode,
396        ctx: &mut Self::Context,
397        bits: usize,
398    ) -> Result<Self> {
399        match sd {
400            ShouldDecode::IsSome(true) => Ok(Some(DecodeBe::decode_offset(data, offset, sd, ctx, bits)?)),
401            ShouldDecode::IsSome(false) => Ok(None),
402            _ => panic!("must set `is_some` on `Option` field"),
403        }
404    }
405    #[inline(always)]
406    fn default_bits() -> usize {
407        E::default_bits()
408    }
409}
410
411impl<E: DecodeLe> DecodeLe for Option<E> {
412    type Context = E::Context;
413    #[inline(always)]
414    fn decode_offset(
415        data: &[u8],
416        offset: &mut usize,
417        sd: &mut ShouldDecode,
418        ctx: &mut Self::Context,
419        bits: usize,
420    ) -> Result<Self> {
421        match sd {
422            ShouldDecode::IsSome(true) => Ok(Some(DecodeLe::decode_offset(data, offset, sd, ctx, bits)?)),
423            ShouldDecode::IsSome(false) => Ok(None),
424            _ => panic!("must set `is_some` on `Option` field"),
425        }
426    }
427    #[inline(always)]
428    fn default_bits() -> usize {
429        E::default_bits()
430    }
431}
432
433#[test]
434fn test_encode_le_number() {
435    let mut data = [0u8; 100];
436    let mut offset = 0;
437    EncodeLe::encode_offset(&0x11223344i32, &mut data, &mut (), &mut offset, 24);
438    assert_eq!(&data[..3], &[0x44, 0x33, 0x22], "{:X?}", &data[..3]);
439    assert_eq!(offset, 24);
440}
441
442#[test]
443fn test_decode_le_number() {
444    let data = [0x44, 0x33, 0x22];
445    let mut offset = 0;
446    let value: i32 = DecodeLe::decode_offset(&data, &mut offset, &mut ShouldDecode::None, &mut (), 24).unwrap();
447    assert_eq!(value, 0x223344);
448    assert_eq!(offset, 24);
449}