bitis_lib/lib_impl/
berde.rs

1use std::ops::{AddAssign, Neg, Shl, Shr};
2use std::convert::{TryFrom, From, TryInto};
3use std::fmt::Display;
4
5// ***
6pub trait IntegerBaseFunctions {
7    const IS_SIGNED: bool;
8    fn get_absolute_uint(self: &Self) -> u64;
9    fn is_val_negative(self: &Self) -> bool;
10    fn switch_sign_if_possible(self: &Self) -> Self;
11    fn get_zero() -> Self;
12}
13macro_rules! impl_integer_signed {
14    ($type:ty) => {
15        impl IntegerBaseFunctions for $type {
16            const IS_SIGNED: bool = true;
17            fn get_absolute_uint(self: &Self) -> u64 {
18                if *self < 0 { self.clone().neg() as u64 }
19                else { self.clone() as u64 }
20            }
21            fn is_val_negative(self: &Self) -> bool { *self < 0 }
22            fn switch_sign_if_possible(self: &Self) -> Self { return self.clone().neg() }
23            fn get_zero() -> Self { 0 as $type }
24        }
25} }
26macro_rules! impl_integer_unsigned {
27    ($type:ty) => {
28        impl IntegerBaseFunctions for $type {
29            const IS_SIGNED: bool = false;
30            fn get_absolute_uint(self: &Self) -> u64 { self.clone() as u64 }
31            fn is_val_negative(self: &Self) -> bool { false }
32            fn switch_sign_if_possible(self: &Self) -> Self { return self.clone() }
33            fn get_zero() -> Self { 0 as $type }
34        }
35} }
36impl_integer_signed!(i8);
37impl_integer_signed!(i16);
38impl_integer_signed!(i32);
39impl_integer_signed!(i64);
40impl_integer_unsigned!(u8);
41impl_integer_unsigned!(u16);
42impl_integer_unsigned!(u32);
43impl_integer_unsigned!(u64);
44
45// ***
46#[derive(Debug, Clone)]
47pub struct Biseri {
48    cur_cache_u8: u16,
49    sub_byte_counter: u8,
50    data_cache: Vec<u8>,
51    final_total_bits: u64,
52}
53
54fn bits_for_and(x: u8) -> u16 {
55    u16::MAX >> (u16::BITS as u8 - x)
56}
57
58#[allow(dead_code)]
59pub trait BiserdiTraitVarBitSize : Sized {
60    fn bit_serialize(self: &Self, total_bits: u64, biseri: &mut Biseri) -> Option<u64>;
61    fn bit_deserialize(version_id: u16, total_bits: u64, bides: &mut Bides) -> Option<(Self, u64)>;
62}
63#[allow(dead_code)]
64pub trait BiserdiTrait: Sized {
65    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64>;
66    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)>;
67}
68
69pub struct BiserSizes {
70    pub total_bits: u64,
71    pub total_bytes: u64
72}
73#[allow(dead_code)]
74impl Biseri {
75    pub fn new() -> Biseri {
76        Biseri { cur_cache_u8: 0, data_cache: Vec::new(), sub_byte_counter: 0, final_total_bits: 0 }
77    }
78
79    pub fn data_size_bytes(&self) -> u64 {
80        self.data_cache.len() as u64
81    }
82    pub fn get_data_ref(&self) -> &Vec<u8> {
83        &self.data_cache
84    }
85    pub fn get_data(&self) -> Vec<u8> {
86        self.data_cache.clone()
87    }
88
89    fn add_data_base_u8(&mut self, cur_u8: &u8, total_bits: u64) -> u64 {
90        if total_bits > 0 {
91            let cur_u16 = cur_u8.clone() as u16;
92            let shift_by = self.sub_byte_counter & 7;
93
94            let cur_bit_size = std::cmp::min(8, total_bits as u8);
95            // println!("cur_bit_size: {}", cur_bit_size);
96            let cur_u16 = (cur_u16 & (bits_for_and(cur_bit_size))) << shift_by;
97            self.cur_cache_u8 += cur_u16;
98
99            self.sub_byte_counter += cur_bit_size;
100            let total_bits = total_bits - cur_bit_size as u64;
101
102            if self.sub_byte_counter >= 8 {
103                self.sub_byte_counter -= 8;
104                let u8_to_add = (self.cur_cache_u8 & 0xFF) as u8;
105                self.data_cache.push(u8_to_add);
106                self.cur_cache_u8 >>= 8;
107            }
108            total_bits
109        }
110        else { 0 }
111    }
112
113    pub fn add_data(&mut self, cur_data: &Vec<u8>, total_bits: u64) -> Option<u64> {
114        // if (cur_data.len() as u64)*8 > total_bits {
115        //     // return None;
116        //     println!("")
117        // }
118        // if (cur_data.len() as u64)*8  < total_bits {
119        //     return None;
120        // }
121        let mut cur_total_bits = total_bits;
122        for cu8 in cur_data.iter() {
123            cur_total_bits = self.add_data_base_u8(cu8, cur_total_bits);
124        }
125        Some(total_bits)
126    }
127
128    pub fn add_biseri_data(&mut self, data: &Biseri) -> Option<u64> {
129        self.add_data(&data.data_cache, data.final_total_bits)
130        // self.add_data(&data.data_cache, ((data.data_cache.len() << 3) +
131        //     data.sub_byte_counter as usize) as u64)
132    }
133    pub fn finish_add_data(&mut self) -> Option<BiserSizes> {
134        if self.final_total_bits > 0 {
135            None
136        }
137        else {
138            let total_bits = ((self.data_cache.len() as u64) << 3) + self.sub_byte_counter as u64;
139            if self.sub_byte_counter > 0 {
140                let u8_to_add = (self.cur_cache_u8 & 0xFF) as u8;
141                self.data_cache.push(u8_to_add);
142            }
143
144            self.final_total_bits = total_bits;
145            Some(BiserSizes{total_bits, total_bytes: self.data_cache.len() as u64})
146        }
147    }
148}
149
150#[derive(Debug, Clone)]
151pub struct Bides {
152    cur_read_pos: u64,
153    sub_byte_counter: u8,
154    pub data_cache: Vec<u8>,
155}
156#[allow(dead_code)]
157impl Bides {
158    pub fn new() -> Bides { Bides { cur_read_pos: 0, sub_byte_counter: 0, data_cache: Vec::new() } }
159    pub fn from_vec(data: &Vec<u8>) -> Bides {
160        Bides{sub_byte_counter: 0, data_cache: data.clone(), cur_read_pos: 0}
161    }
162    pub fn from_biseri(biseri: &Biseri) -> Bides {
163        Bides{sub_byte_counter: 0, data_cache: biseri.get_data().clone(), cur_read_pos: 0}
164    }
165
166    pub fn append_data(&mut self, data: &Vec<u8>) {
167        self.data_cache.extend(data);
168    }
169
170    pub fn reset_position(&mut self) {
171        self.sub_byte_counter = 0;
172        self.cur_read_pos = 0;
173    }
174    pub fn decode_data_base_u8(&mut self, total_bits: u64) -> Option<(u8, u64)> {
175        if self.cur_read_pos as usize >= self.data_cache.len() { return None }
176        let mut cur_u16: u16 = self.data_cache[self.cur_read_pos as usize] as u16;
177        if (self.cur_read_pos + 1 < self.data_cache.len() as u64) && (self.sub_byte_counter > 0) {
178            cur_u16 += (self.data_cache[(self.cur_read_pos + 1) as usize] as u16) << 8;
179        }
180
181        let cur_used_bits = std::cmp::min(total_bits as u8, 8);
182
183        // println!("d cur_used_bits={} (total_bits={})", cur_used_bits, total_bits);
184
185        let d = ((cur_u16 >> self.sub_byte_counter) & bits_for_and(cur_used_bits)) as u8;
186
187        self.sub_byte_counter += cur_used_bits;
188        if self.sub_byte_counter >= 8 {
189            self.sub_byte_counter -= 8;
190            self.cur_read_pos += 1;
191        }
192
193        Some((d, total_bits - cur_used_bits as u64))
194    }
195
196    pub fn decode_data(&mut self, total_bits: u64, expected_bytes: u32) -> Option<Vec<u8>> {
197        if self.cur_read_pos >= self.data_cache.len() as u64 {
198            return None;
199        }
200        let mut cur_total_bits = total_bits;
201        let mut dv = Vec::new();
202        while cur_total_bits > 0 {
203            let d;
204            (d, cur_total_bits) = match self.decode_data_base_u8(cur_total_bits) {
205                Some(d) => d, None => { return None; }
206            };
207            dv.push(d);
208        }
209        let num_add = expected_bytes - dv.len() as u32;
210        for _ in 0..num_add { dv.push(0); }
211        Some(dv)
212    }
213
214    pub fn skip_bits(&mut self, bits: u64) {
215        let bits_total_pos = bits + self.sub_byte_counter as u64;
216        self.sub_byte_counter = (bits_total_pos.clone() & 7) as u8;
217        self.cur_read_pos += bits_total_pos >> 3;
218    }
219}
220
221macro_rules! impl_biserdi_var_bitsize_trait {
222    ($type:ty, $num_bytes: expr) => {
223        impl BiserdiTraitVarBitSize for $type {
224            fn bit_serialize(self: &Self, total_bits: u64, biseri: &mut Biseri) -> Option<u64> {
225                if Self::IS_SIGNED { self.is_val_negative().bit_serialize(biseri)?; }
226                let v = self.get_absolute_uint();
227                let vv = &v.to_le_bytes().to_vec();
228                let bits = biseri.add_data(vv, total_bits)?;
229
230                let bits_with_sign = if Self::IS_SIGNED { bits+1 } else { bits };
231                Some(bits_with_sign)
232            }
233            fn bit_deserialize(version_id: u16, total_bits: u64, bides: &mut Bides) -> Option<(Self, u64)> {
234                let is_neg = if Self::IS_SIGNED {
235                    bool::bit_deserialize(version_id, bides)?.0 }
236                else { false };
237
238                let mut v = Self::from_le_bytes(
239                    bides.decode_data(total_bits, $num_bytes)?.try_into().ok()?);
240                if is_neg { v = v.switch_sign_if_possible() }
241
242                let bits_with_sign = if Self::IS_SIGNED { total_bits + 1 } else { total_bits };
243                Some((v, bits_with_sign))
244            }
245        }
246    };
247}
248macro_rules! impl_biserdi {
249    ($type:ty, $num_bits: expr) => {
250        impl BiserdiTrait for $type {
251            fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
252                Some(biseri.add_data(&self.clone().to_le_bytes().to_vec(), ($num_bits))?)
253            }
254            fn bit_deserialize(_version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
255                Some((Self::from_le_bytes(bides.decode_data(
256                    ($num_bits), std::cmp::max((($num_bits)>>3),1))?.try_into().ok()?),
257                $num_bits))
258            }
259        }
260    };
261}
262
263// ****************************************************************************
264impl BiserdiTrait for bool {
265    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
266        let val = if *self { 1_u8 } else { 0_u8 };
267        biseri.add_data_base_u8(&val, 1);
268        Some(1)
269    }
270    fn bit_deserialize(_version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
271        let vec = bides.decode_data(1, 1)?;
272        Some((if vec[0] == 0 { false } else { true }, 1))
273    }
274}
275impl_biserdi_var_bitsize_trait!(u8, u8::BITS>>3);
276impl_biserdi_var_bitsize_trait!(u16, u16::BITS>>3);
277impl_biserdi_var_bitsize_trait!(u32, u32::BITS>>3);
278impl_biserdi_var_bitsize_trait!(u64, u64::BITS>>3);
279impl_biserdi_var_bitsize_trait!(i8, i8::BITS>>3);
280impl_biserdi_var_bitsize_trait!(i16, i16::BITS>>3);
281impl_biserdi_var_bitsize_trait!(i32, i32::BITS>>3);
282impl_biserdi_var_bitsize_trait!(i64, i64::BITS>>3);
283impl_biserdi!(f32, 32);
284impl_biserdi!(f64, 64);
285
286
287// ****************************************************************************
288#[derive(Clone, Debug, PartialEq)]
289pub struct BitisOption<T> {
290    pub val: Option<T>
291}
292impl<T> BiserdiTrait for BitisOption<T> where T: BiserdiTrait + Default {
293    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
294        let mut size = 1;
295        match &self.val {
296            None => { false.bit_serialize(biseri)?; },
297            Some(v) => {
298                true.bit_serialize(biseri)?;
299                size += v.bit_serialize(biseri)?;
300            }
301        }
302        Some(size)
303    }
304    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
305        let mut size = 1;
306
307        let (is_set, _) = bool::bit_deserialize(version_id, bides)?;
308        let v = if is_set {
309            let vv = T::bit_deserialize(version_id, bides)?;
310            size += vv.1.clone();
311            Some(vv.0)
312        }
313        else { None };
314
315        Some((BitisOption{val: v}, size))
316    }
317}
318impl<T, TT> From<Option<TT>> for BitisOption<T> where T: BiserdiTrait + Default, TT: Into<T> {
319    fn from(value: Option<TT>) -> Self {
320        match value {
321            Some(v) => Self { val: Some(v.into()) },
322            None => Self { val: None }
323        }
324    }
325}
326impl<T> From<T> for BitisOption<T> where T: BiserdiTrait + Default {
327    fn from(val: T) -> Self {
328        Self{ val: Some(val) }
329    } }
330// impl<T, TT> Into<Option<TT>> for BitisOption<T> where T: BiserdiTrait + Default, TT: From<T>  {
331//     fn into(val: BitisOption<T>) -> Option<TT> {
332//         match val.val { Some(v) => Some(v.into()), None => None }
333//     }
334// }
335impl<T> std::fmt::Display for BitisOption<T> where T: BiserdiTrait + Default + Display {
336    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
337        match &self.val {
338            None => { write!(f, "None [opt]") },
339            Some(v) => { write!(f, "{} [opt]", v) }
340        }
341    } }
342impl<T> Default for BitisOption<T> where T: BiserdiTrait + Default {
343    fn default() -> Self { Self{val: None} }
344}
345
346// ****************************************************************************
347#[derive(Debug, Clone, PartialEq, Eq, Copy)]
348pub struct FixedArray<T: Default, const N: usize> { pub val: [T; N] }
349impl<T, const N: usize> BiserdiTrait for FixedArray<T, N> where T: BiserdiTrait + Default + Copy {
350    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
351        let mut s = 0;
352        for i in 0..N { s += self.val[i].bit_serialize(biseri)?; }
353        Some(s)
354    }
355    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
356        let mut v: [T; N] = [T::default(); N];
357        let mut bits = 0;
358        let mut cur_bits;
359        for i in 0..N { (v[i], cur_bits) = T::bit_deserialize(version_id, bides)?; bits += cur_bits; }
360        Some((Self{ val: v}, bits))
361    }
362}
363impl<T, const N: usize> BiserdiTraitVarBitSize for FixedArray<T, N> where T: BiserdiTraitVarBitSize + Default + Copy {
364    fn bit_serialize(self: &Self, total_bits_per_unit: u64, biseri: &mut Biseri) -> Option<u64> {
365        let mut s = 0;
366        for i in 0..N {
367            s += self.val[i].bit_serialize(total_bits_per_unit, biseri)?;
368        }
369        Some(s)
370    }
371    fn bit_deserialize(version_id: u16, total_bits_per_unit: u64, bides: &mut Bides) -> Option<(Self, u64)> {
372        let mut v = [T::default(); N];
373        let mut bits = 0;
374        let mut cur_bits;
375        for i in 0..N {
376            (v[i], cur_bits) = T::bit_deserialize(version_id, total_bits_per_unit, bides)?; bits += cur_bits; }
377        Some((Self{ val: v}, bits))
378    }
379}
380impl<T: Sized + Copy + BiserdiTrait + Default, const N: usize> From<[T; N]> for FixedArray<T, N> {
381    fn from(val: [T;N]) -> Self { Self{ val: val.clone()} } }
382impl<T: Sized + Copy + Display + Default, const N: usize> std::fmt::Display for FixedArray<T, N> {
383    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
384        let das: Vec<String> = self.val.iter().map(|v| format!("{}", v)).collect();
385        write!(f, "[{}]", das.join(", "))
386    } }
387impl<T: Sized + Copy + BiserdiTrait + Default, const N: usize> Default for FixedArray<T, N>  {
388    fn default() -> Self {
389        Self{val: [T::default(); N]}
390    }
391}
392
393// ****************************************************************************
394pub struct DynArray<T, const DYNSIZEBITS: u8> { pub val: Vec<T> }
395impl<T, const DYNSIZEBITS: u8> BiserdiTrait for DynArray<T, DYNSIZEBITS> where T: BiserdiTrait + Default + Copy {
396    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
397        let mut s = 0;
398        s += DynInteger::<u32, DYNSIZEBITS>::new(self.val.len() as u32).bit_serialize(biseri)?;
399        for d in self.val.iter() { s += d.bit_serialize(biseri)?; };
400        Some(s)
401    }
402    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
403        let mut s = 0;
404        let (v, cs) =
405            DynInteger::<u32, DYNSIZEBITS>::bit_deserialize(version_id, bides)?;
406        let mut data = Vec::with_capacity(cs as usize);
407        for _ci in 0..v.val {
408            let (vi, si) = T::bit_deserialize(version_id, bides)?;
409            s += si;
410            data.push(vi);
411        }
412        Some((Self{ val: data }, s+cs))
413    }
414}
415impl<T: Sized + Copy + BiserdiTraitVarBitSize, const DYNSIZEBITS: u8, const N: usize> From<[T; N]> for DynArray<T, DYNSIZEBITS> {
416    fn from(val: [T;N]) -> Self {
417        DynArray{ val:Vec::from(val)}
418    } }
419impl<T: Sized + Copy + BiserdiTraitVarBitSize, const DYNSIZEBITS: u8> From<Vec<T>> for DynArray<T, DYNSIZEBITS> {
420    fn from(val: Vec<T>) -> Self {
421        DynArray{ val: val.clone()}
422    } }
423impl<T: Sized + Copy + BiserdiTraitVarBitSize + Display, const DYNSIZEBITS: u8> std::fmt::Display for DynArray<T, DYNSIZEBITS> {
424    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
425        let das: Vec<String> = self.val.iter().map(|v| v.to_string()).collect();
426        write!(f, "[{} |dynbits:{}]", das.join(", "), DYNSIZEBITS)
427    } }
428impl<T: Sized + Copy + BiserdiTraitVarBitSize, const DYNSIZEBITS: u8> Default for DynArray<T, DYNSIZEBITS> {
429    fn default() -> Self {
430        Self{val: Vec::new()}
431    }
432}
433
434// ****************************************************************************
435#[derive(Debug, Clone, PartialEq, Eq, Default, Copy)]
436pub struct VarWithGivenBitSize<T: Sized + Copy + BiserdiTraitVarBitSize + Default, const NUM_BITS: u64> {
437    pub val: T
438}
439impl<T: Sized + Copy + BiserdiTraitVarBitSize + Default, const NUM_BITS: u64> VarWithGivenBitSize<T, NUM_BITS> {
440    pub fn new(v: T) -> Self { VarWithGivenBitSize {val: v} }
441}
442impl<T: Sized + Copy + BiserdiTraitVarBitSize + Default, const NUM_BITS: u64> From<T> for VarWithGivenBitSize<T, NUM_BITS> {
443    fn from(val: T) -> Self {
444        VarWithGivenBitSize::<T, NUM_BITS>::new(val)
445    }
446}
447// impl<const NUM_BITS: u64> From<usize> for VarWithGivenBitSize<usize, NUM_BITS> {
448//     fn from(val: usize) -> Self {
449//         VarWithGivenBitSize::<usize, NUM_BITS>::new(val)
450//     }
451// }
452impl<T: Sized + Copy + BiserdiTraitVarBitSize + Display + Default, const NUM_BITS: u64> std::fmt::Display for VarWithGivenBitSize<T, NUM_BITS> {
453    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
454        write!(f, "{} |bits:{}", self.val, NUM_BITS)
455} }
456impl<T: Sized + Copy + BiserdiTraitVarBitSize + Default, const NUM_BITS: u64> BiserdiTrait for VarWithGivenBitSize<T, NUM_BITS> {
457    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
458        self.val.bit_serialize(NUM_BITS, biseri)
459    }
460    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
461        let v = T::bit_deserialize(version_id, NUM_BITS, bides)?;
462        Some((Self{val: v.0}, v.1))
463    }
464}
465
466#[derive(Debug, Clone, PartialEq, Eq, Default, Copy)]
467pub struct DynInteger<
468    T: Sized + Copy + BiserdiTraitVarBitSize + AddAssign + Shl<Output = T> + Shr + Ord + PartialEq //+ TryFrom<u64>
469    + IntegerBaseFunctions + Default, const N: u8> {
470    pub val: T
471}
472impl<T: Display + Sized + Copy + BiserdiTraitVarBitSize + AddAssign + Shl<Output = T> + Shr + Ord + PartialEq + TryFrom<u64>
473    + IntegerBaseFunctions + Default, const N: u8> DynInteger<T, N> {
474    const DYN_SIZE: u8 = N;
475    pub fn new(v: T) -> Self{
476        DynInteger{val: v}
477    }
478}
479impl<T: Display + Sized + Copy + BiserdiTraitVarBitSize + AddAssign + Shl<Output = T> + Shr + Ord + PartialEq + TryFrom<u64>
480    + IntegerBaseFunctions + Default, const N: u8> BiserdiTrait for DynInteger<T, N> {
481    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
482        // let br = self.bits_required();
483        // let dyn_sections = br / Self::DYN_SIZE;
484        let mut bit_size: u64 = 1;
485        let mut val_work = self.val.get_absolute_uint();
486
487        if T::IS_SIGNED { self.val.is_val_negative().bit_serialize(biseri)?; bit_size +=1; }
488
489        (val_work != 0).bit_serialize(biseri);
490        while val_work > 0 {
491            // todo only serialize up to bitsize of T
492            val_work.bit_serialize(u64::from(Self::DYN_SIZE), biseri)?;
493            val_work >>= Self::DYN_SIZE;
494            bit_size += (Self::DYN_SIZE + 1) as u64;
495            let further_data = val_work > 0;
496            further_data.bit_serialize(biseri);
497        }
498        Some(bit_size)
499    }
500    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
501        let mut cur_shift: u64 = 0;
502        let mut v: u64 = 0;
503        let mut negative_sign = false;
504
505        let mut bit_size = 1;
506        if T::IS_SIGNED {
507            negative_sign = bool::bit_deserialize(version_id, bides)?.0; bit_size += 1; }
508        let mut further_data = bool::bit_deserialize(version_id, bides)?.0;
509        while further_data {
510            let vt = u64::bit_deserialize(version_id, Self::DYN_SIZE as u64, bides)?;
511            bit_size += vt.1 + 1;
512            v += vt.0 << cur_shift;
513            cur_shift += u64::from(Self::DYN_SIZE);
514            further_data = bool::bit_deserialize(version_id, bides)?.0;
515        }
516        let mut vv= T::try_from(v).ok()?;
517        if negative_sign {
518            vv = vv.switch_sign_if_possible();
519        }
520        Some((Self{val: vv}, bit_size))
521    }
522}
523impl<T: Display + Sized + Copy + BiserdiTraitVarBitSize + AddAssign + Shl<Output = T> + Shr + Ord + PartialEq + TryFrom<u64>
524    + IntegerBaseFunctions + Default, const N: u8> Display for DynInteger<T, N> {
525    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
526        write!(f, "{} |dynbits:{}]", self.val, N)
527    } }
528
529
530// ***
531#[derive(Debug, Clone, PartialEq, Default)]
532pub enum FixPrecisionVal {
533    #[default]
534    Overflow,
535    Value(f64),
536    Underflow
537}
538#[derive(Debug, Clone, PartialEq, Default)]
539pub struct FixPrecisionMinMax<const NUM_BITS: u8, const MIN_IVALUE: i64, const MAX_IVALUE: i64> {
540    pub val: FixPrecisionVal
541}
542impl<const NUM_BITS: u8, const MIN_IVALUE: i64, const MAX_IVALUE: i64> FixPrecisionMinMax<NUM_BITS, MIN_IVALUE, MAX_IVALUE> {
543    const MIN_VALUE: f64 = MIN_IVALUE as f64;
544    const MAX_VALUE: f64 = MAX_IVALUE as f64;
545    const RANGE_VALUE: f64 = Self::MAX_VALUE - Self::MIN_VALUE;
546    const MAX_INT_VALUE_FOR_BITS: u64 = (1_u64<<NUM_BITS) - 1_u64;
547    const MAX_VALUE_FOR_BITS: f64 = (Self::MAX_INT_VALUE_FOR_BITS - 1_u64) as f64;
548
549    pub fn new(val: f64) -> Self {
550        if val > Self::MAX_VALUE { FixPrecisionMinMax { val: FixPrecisionVal::Overflow } }
551        else if val < Self::MIN_VALUE { FixPrecisionMinMax { val: FixPrecisionVal::Underflow } }
552        else { FixPrecisionMinMax { val: FixPrecisionVal::Value(val) } }
553    }
554}
555impl<const NUM_BITS: u8, const MIN_IVALUE: i64, const MAX_IVALUE: i64> BiserdiTrait for FixPrecisionMinMax<NUM_BITS, MIN_IVALUE, MAX_IVALUE> {
556    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
557        let v = match self.val {
558            // i = (v-Min) / (Max-Min) * 253 + 1
559            FixPrecisionVal::Value(v) =>
560                ((v - Self::MIN_VALUE) / Self::RANGE_VALUE * Self::MAX_VALUE_FOR_BITS + 1.0) as u64,
561            FixPrecisionVal::Underflow => 0,
562            FixPrecisionVal::Overflow => Self::MAX_INT_VALUE_FOR_BITS
563        };
564        v.bit_serialize(NUM_BITS as u64, biseri)
565    }
566    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
567        // v = (i-1)/253 * (Max-Min) + Min
568        let (v, bits) = u64::bit_deserialize(version_id, NUM_BITS as u64, bides)?;
569        let vv = if v == 0 { FixPrecisionVal::Underflow }
570        else if v == Self::MAX_INT_VALUE_FOR_BITS { FixPrecisionVal::Overflow }
571        else {
572            FixPrecisionVal::Value(((v-1) as f64) / Self::MAX_VALUE_FOR_BITS
573                * Self::RANGE_VALUE + Self::MIN_VALUE)
574        };
575        Some((Self{val: vv}, bits))
576    }
577}
578impl<const NUM_BITS: u8, const MIN_IVALUE: i64, const MAX_IVALUE: i64> Display for FixPrecisionMinMax<NUM_BITS, MIN_IVALUE, MAX_IVALUE> {
579    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
580        match self.val {
581            FixPrecisionVal::Overflow => write!(f, "Overflow |dynbits:{}", NUM_BITS),
582            FixPrecisionVal::Underflow => write!(f, "Underflow |dynbits:{}", NUM_BITS),
583            FixPrecisionVal::Value(v) => write!(f, "{} |dynbits:{}", v, NUM_BITS)
584        }
585    } }
586
587// *****
588#[derive(Debug, Clone, PartialEq)]
589pub struct Binary<const DYNSIZEBITS: u8> {
590    pub val: Vec<u8>
591}
592impl<const DYNSIZEBITS: u8> Binary<DYNSIZEBITS> {
593    pub fn new(data: Vec<u8>) -> Self {
594        Self{ val: data }
595    }
596    pub fn empty() -> Self {
597        Self{val: Vec::new()}
598    }
599}
600impl<const DYNSIZEBITS: u8> BiserdiTrait for Binary<DYNSIZEBITS> {
601    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
602        let mut s = 0;
603        s += DynInteger::<u32, DYNSIZEBITS>::new(self.val.len() as u32).bit_serialize(biseri)?;
604        for d in self.val.iter() { s += d.bit_serialize(8, biseri)?; };
605        Some(s)
606    }
607    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
608        let mut s = 0;
609        let (v, cs) =
610            DynInteger::<u32, DYNSIZEBITS>::bit_deserialize(version_id, bides)?;
611        let mut data = Vec::with_capacity(cs as usize);
612        for _ci in 0..v.val {
613            let (vi, si) = u8::bit_deserialize(version_id, 8, bides)?;
614            s += si;
615            data.push(vi);
616        }
617        Some((Self{ val: data }, s+cs))
618    }
619}
620impl<const N: u8> std::fmt::Display for Binary< N> {
621    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
622        let hex = self.val.iter().map(|b| format!("{:02x}", b).to_string()).collect::<Vec<String>>().join(" ");
623        write!(f, "{:x?} |dynbits:{}", hex, N)
624    }
625}
626
627#[cfg(test)]
628mod bitis_base_serialization_deserialization {
629    use rstest::rstest;
630    use crate::lib_impl::berde::{Bides, Biseri};
631    use super::*;
632
633    #[rstest]
634    fn add_one_u8() {
635        let mut b = Biseri::new();
636        let d = 0b10101010_u8;
637
638        b.add_data_base_u8(&d, 8);
639
640        assert_eq!(b.clone().data_cache.len(), 1);
641        assert_eq!(b.sub_byte_counter, 0);
642
643        let r = b.finish_add_data().unwrap();
644        assert_eq!((r.total_bits, r.total_bytes), (8, 1));
645    }
646
647    #[rstest]
648    #[case::ot_uint4(4, 1, 4, 1)]
649    #[case::tt_uint4(4, 2, 8, 1)]
650    #[case::ot_uint6(6, 1, 6, 1)]
651    #[case::tt_uint6(6, 2, 12, 2)]
652    #[case::trt_uint6(6, 3, 18, 3)]
653    #[case::ft_uint6(6, 4, 24, 3)]
654    fn add_one_var(#[case] bitsize: u64, #[case] repeated: u8, #[case] final_bitsize: u64, #[case] num_bytes: u64) {
655        let mut b = Biseri::new();
656        let d = 0b10101010_u8;
657
658        for _i in 0..repeated {
659            b.add_data_base_u8(&d, bitsize);
660        }
661
662        let r = b.finish_add_data().unwrap();
663        assert_eq!((r.total_bits, r.total_bytes), (final_bitsize, num_bytes));
664    }
665
666    #[rstest]
667    #[case::ok(5, 4, 5)]
668    #[case::expected_overflow(0b10011, 4, 3)]
669    fn serialize_and_deserialize_base(#[case] val_in: u8, #[case] bitsize: u64, #[case] val_out: u8) {
670        let mut ser = Biseri::new();
671
672        ser.add_data_base_u8(&val_in, bitsize);
673        ser.finish_add_data();
674
675        let mut des = Bides::from_biseri(&ser);
676
677        assert_eq!(des.data_cache, ser.data_cache);
678
679        let r = des.decode_data_base_u8(bitsize);
680        assert!(r.is_some());
681        let (dd, bs) = r.unwrap();
682        assert_eq!(bs, 0);
683
684        println!("val_in: {val_in} vs. dd: {dd} (expected: {val_out}");
685        assert_eq!(val_out, dd);
686    }
687
688    #[rstest]
689    #[case::ok(3*256+5, 16, 3*256+5)]
690    #[case::ok(3*256+5, 12, 3*256+5)]
691    #[case::ok(3*256+5, 9, 1*256+5)]
692    fn serialize_and_deserialize_u16_single(#[case] val_in: u16, #[case] bitsize: u64, #[case] val_out: u16) {
693        let val_in_vec = val_in.to_le_bytes().clone();
694
695        let mut ser = Biseri::new();
696
697        let mut total_size = bitsize;
698        val_in_vec.clone().iter().for_each(|x| {
699            total_size = ser.add_data_base_u8(&x, bitsize);
700        });
701        ser.finish_add_data();
702
703        println!("ser.cache: {:?}", ser.data_cache);
704
705        assert_eq!(ser.data_cache.len(), 2);
706
707        let mut des = Bides::from_biseri(&ser);
708
709        assert_eq!(des.data_cache, ser.data_cache);
710
711        let mut dd = Vec::new();
712        let mut total_size = bitsize;
713        while total_size > 0 {
714            let ddd;
715            let r = des.decode_data_base_u8(total_size);
716            assert!(r.is_some());
717            (ddd, total_size) = r.unwrap();
718            dd.push(ddd);
719        };
720
721        let ddv = u16::from_le_bytes(dd.clone().try_into().unwrap());
722        println!("val_in: {val_in} ({val_in_vec:?}) vs. ddv: {ddv:?} ({dd:?}) (expected: {val_out})");
723        assert_eq!(val_out, ddv);
724    }
725
726    fn add_two_u16_fixed(ser: &mut Biseri, bits: u64) -> BiserSizes {
727        let d: u16 = 3;
728
729        ser.add_data(&d.to_le_bytes().to_vec(), bits);
730        ser.add_data(&d.to_le_bytes().to_vec(), bits);
731        ser.finish_add_data().unwrap()
732    }
733    #[rstest]
734    fn serialize_u16_fixed_full() {
735        let mut ser = Biseri::new();
736
737        let r = add_two_u16_fixed(&mut ser, 16);
738        let (lbits, lbytes) = (r.total_bits, r.total_bytes);
739
740        assert_eq!(ser.data_cache.len(), 4);
741        assert_eq!(lbytes, 4);
742        assert_eq!(lbits, 2 * 16);
743
744        assert_eq!(ser.data_cache[0], 3);
745        assert_eq!(ser.data_cache[1], 0);
746        assert_eq!(ser.data_cache[2], 3);
747        assert_eq!(ser.data_cache[3], 0);
748    }
749
750    #[rstest]
751    fn serialize_u16_fixed_12b() {
752        let mut ser = Biseri::new();
753
754        let r = add_two_u16_fixed(&mut ser, 12);
755        let (lbits, lbytes) = (r.total_bits, r.total_bytes);
756
757        assert_eq!(ser.data_cache.len(), 3);
758        assert_eq!(lbytes, 3);
759        assert_eq!(lbits, 2 * 12);
760
761        assert_eq!(ser.data_cache[0], 3);
762        assert_eq!(ser.data_cache[1], 3 << 4);
763        assert_eq!(ser.data_cache[2], 0);
764    }
765
766    #[rstest]
767    #[case::bitsize_16(16)]
768    #[case::bitsize_14(14)]
769    #[case::bitsize_12(12)]
770    fn ser_and_deserialize_u16_fixed(#[case] bits: u64) {
771        let mut ser = Biseri::new();
772
773        let _ = add_two_u16_fixed(&mut ser, bits);
774
775        let mut des = Bides::from_biseri(&ser);
776
777        assert_eq!(des.data_cache, ser.data_cache);
778
779        let d1 = des.decode_data(bits, 2);
780        assert!(d1.is_some());
781        let d2 = des.decode_data(bits, 2);
782        assert!(d2.is_some());
783
784        let d1 = d1.unwrap();
785        let d2 = d2.unwrap();
786
787        assert_eq!(d1[0], 3);
788        assert_eq!(d1[1], 0);
789        assert_eq!(d2[0], 3);
790        assert_eq!(d2[1], 0);
791    }
792
793    #[rstest]
794    fn ser_and_deserialize_i16_fixed() {
795        let mut ser = Biseri::new();
796
797        let v: i8 = -11;
798        v.bit_serialize(5, &mut ser);
799
800        let r = ser.finish_add_data().unwrap();
801        let (bits, bytes) = (r.total_bits, r.total_bytes);
802
803        println!("bits: {}, bytes: {}", bits, bytes);
804
805        let mut des = Bides::from_biseri(&ser);
806
807        let vv = i8::bit_deserialize(1,5, &mut des);
808        println!("v: {}, vv: {:?}", v, vv);
809
810        assert!(vv.is_some());
811
812        let vv = vv.unwrap();
813        println!("bits_des: {}", vv.1);
814        assert_eq!(v, vv.0);
815    }
816
817    #[rstest]
818    fn de_and_serialize_various_unsigned() {
819        // ***********************************************************
820        let mut ser = Biseri::new();
821        let v1: u8 = 5;
822        v1.bit_serialize(6, &mut ser);
823        // ser.add_data_u8(&v1, 6);
824        let v2: u16 = 15;
825        v2.bit_serialize(14, &mut ser);
826        // ser.add_data_u16(&v2, 14);
827        let v3: u32 = 55;
828        v3.bit_serialize(22, &mut ser);
829        // ser.add_data_u32(&v3, 30);
830        let r = ser.finish_add_data().unwrap();
831        let (bits, bytes) = (r.total_bits, r.total_bytes);
832
833        println!("bits: {}, bytes: {}", bits, bytes);
834
835        // // ***********************************************************
836        let mut des = Bides::from_biseri(&ser);
837        let vo1 = u8::bit_deserialize(1,6, &mut des);
838        // let vo1 = des.decode_data_u8(6);
839        let vo2 = u16::bit_deserialize(1,14, &mut des);
840        // let vo2 = des.decode_data_u16(14);
841        let vo3 = u32::bit_deserialize(1,22, &mut des);
842        // let vo3 = des.decode_data_u32(30);
843
844        println!("v1: {}, v2: {}, v3: {} vs vo1: {:?}, vo2: {:?}, vo3: {:?}", v1, v2, v3, vo1, vo2, vo3);
845
846        // ***********************************************************
847        assert!(vo1.is_some());
848        assert_eq!(v1, vo1.unwrap().0);
849
850        assert!(vo2.is_some());
851        assert_eq!(v2, vo2.unwrap().0);
852
853        assert!(vo3.is_some());
854        assert_eq!(v3, vo3.unwrap().0);
855    }
856
857    #[rstest]
858    fn de_and_serialize_various_float() {
859        // ***********************************************************
860        let mut ser = Biseri::new();
861        let v1: f32 = 56.78;
862        v1.bit_serialize(&mut ser);
863        // ser.add_data_f32(&v1);
864        let v2: u8 = 5;
865        v2.bit_serialize(5, &mut ser);
866        // ser.add_data_u8(&v2, 5);
867        let v3: bool = true;
868        v3.bit_serialize(&mut ser);
869        // ser.add_data_bool(&v3);
870        let v4: bool = false;
871        v4.bit_serialize(&mut ser);
872        // ser.add_data_bool(&v4);
873        v1.bit_serialize(&mut ser);
874        // ser.add_data_f32(&v1);
875        let r = ser.finish_add_data().unwrap();
876        let (bits, bytes) = (r.total_bits, r.total_bytes);
877
878        println!("bits: {}, bytes: {}", bits, bytes);
879
880        // ***********************************************************
881        let mut des = Bides::from_biseri(&ser);
882        let vo1 = f32::bit_deserialize(1, &mut des);
883        let vo2 = u8::bit_deserialize(1,5, &mut des);
884        let vo3 = bool::bit_deserialize(1,&mut des);
885        let vo4 = bool::bit_deserialize(1,&mut des);
886        let vo5 = f32::bit_deserialize(1,&mut des);
887        // let vo1 = des.decode_data_f32();
888        // let vo2 = des.decode_data_u8(5);
889        // let vo3 = des.decode_data_bool();
890        // let vo4 = des.decode_data_bool();
891        // let vo5 = des.decode_data_f32();
892
893        println!("vo1: {:?}, vo2: {:?}, vo3: {:?}, vo4: {:?}, vo4: {:?}", vo1, vo2, vo3, vo4, vo5);
894
895        // ***********************************************************
896        assert!(vo1.is_some());
897        assert_eq!(v1, vo1.unwrap().0);
898
899        assert!(vo2.is_some());
900        assert_eq!(v2, vo2.unwrap().0);
901
902        assert!(vo3.is_some());
903        assert_eq!(v3, vo3.unwrap().0);
904
905        assert!(vo4.is_some());
906        assert_eq!(v4, vo4.unwrap().0);
907
908        assert!(vo5.is_some());
909        assert_eq!(v1, vo5.unwrap().0);
910    }
911
912    #[rstest]
913    fn serialize_and_deserialize_array_uint() {
914        let mut ser = Biseri::new();
915
916        let v: FixedArray<VarWithGivenBitSize<u16, 5>, 4> = [11.into(), 12.into(), 22.into(), 23.into()].into();
917        v.bit_serialize(&mut ser);
918        let r = ser.finish_add_data().unwrap();
919        let (bits, bytes) = (r.total_bits, r.total_bytes);
920
921        println!("bits: {}, bytes: {}", bits, bytes);
922
923        let mut des = Bides::from_biseri(&ser);
924        let vv = FixedArray::<VarWithGivenBitSize<u16, 5>, 4>::bit_deserialize(1,&mut des);
925
926        assert!(vv.is_some());
927        let vv = vv.unwrap().0;
928
929        assert_eq!(v.val[0], vv.val[0]);
930        assert_eq!(v.val[1], vv.val[1]);
931        assert_eq!(v.val[2], vv.val[2]);
932        assert_eq!(v.val[3], vv.val[3]);
933    }
934
935    #[rstest]
936    fn serialize_and_deserialize_array_bool() {
937        let mut ser = Biseri::new();
938
939        let v= FixedArray::from([true, true, false, true]);
940        v.bit_serialize(&mut ser);
941        let r = ser.finish_add_data().unwrap();
942        let (bits, bytes) = (r.total_bits, r.total_bytes);
943        println!("bits: {}, bytes: {}", bits, bytes);
944
945        let mut des = Bides::from_biseri(&ser);
946        let vv = FixedArray::<bool, 4>::bit_deserialize(1,&mut des);
947
948        assert!(vv.is_some());
949        let vv = vv.unwrap().0;
950
951        assert_eq!(v.val[0], vv.val[0]);
952        assert_eq!(v.val[1], vv.val[1]);
953        assert_eq!(v.val[2], vv.val[2]);
954        assert_eq!(v.val[3], vv.val[3]);
955    }
956    #[rstest]
957    fn serialize_and_deserialize_array_f64() {
958        let mut ser = Biseri::new();
959
960        let v = FixedArray::from([1.1, 1.2, 22.34, 123456.78]);
961        v.bit_serialize(&mut ser);
962        let r = ser.finish_add_data().unwrap();
963        let (bits, bytes) = (r.total_bits, r.total_bytes);
964        println!("bits: {}, bytes: {}", bits, bytes);
965
966        let mut des = Bides::from_biseri(&ser);
967        let vv = FixedArray::<f64, 4>::bit_deserialize(1,&mut des);
968
969        assert!(vv.is_some());
970        let vv = vv.unwrap().0;
971
972        assert_eq!(v.val[0], vv.val[0]);
973        assert_eq!(v.val[1], vv.val[1]);
974        assert_eq!(v.val[2], vv.val[2]);
975        assert_eq!(v.val[3], vv.val[3]);
976    }
977
978    #[rstest]
979    #[case::val_0(0, 1, 1)]
980    #[case::val_1(1, 5, 1)]
981    #[case::val_10(10, 9, 2)]
982    fn serialize_dyn_int_u32_3(#[case] val: u32, #[case] ex_bits: u64, #[case] ex_bytes: u64) {
983        // #[test]
984        // fn serialize_dyn_int_u32_3() {
985        //     let val: u32 = 10;
986        //     let ex_bits: u64 = 9;
987        //     let ex_bytes: u64 = 2;
988
989        let mut ser = Biseri::new();
990
991        let v = DynInteger::<u32, 3>::new(val);
992        v.bit_serialize(&mut ser);
993        let r = ser.finish_add_data().unwrap();
994        let (bits, bytes) = (r.total_bits, r.total_bytes);
995        println!("bits: {}, bytes: {}", bits, bytes);
996
997        assert_eq!(bits, ex_bits);
998        assert_eq!(bytes, ex_bytes);
999    }
1000
1001    #[rstest]
1002    #[case::val_0(0, 2, 1)]
1003    #[case::val_1(1, 6, 1)]
1004    #[case::val_10(10, 10, 2)]
1005    fn serialize_dyn_int_i32_3(#[case] val: i32, #[case] ex_bits: u64, #[case] ex_bytes: u64) {
1006        // #[test]
1007        // fn serialize_dyn_int_i32_3() {
1008        //     let val: i32 = -1;
1009        //     let ex_bits: u64 = 6;
1010        //     let ex_bytes: u64 = 1;
1011
1012        let mut ser = Biseri::new();
1013
1014        let v = DynInteger::<i32, 3>::new(val);
1015        v.bit_serialize(&mut ser);
1016        let r = ser.finish_add_data().unwrap();
1017        let (bits, bytes) = (r.total_bits, r.total_bytes);
1018        println!("bits: {}, bytes: {}", bits, bytes);
1019
1020        assert_eq!(bits, ex_bits);
1021        assert_eq!(bytes, ex_bytes);
1022    }
1023
1024    #[rstest]
1025    #[case::val_0(0)]
1026    #[case::val_1(1)]
1027    #[case::val_10(10)]
1028    #[case::val_m1(-1)]
1029    #[case::val_m1111(-1111)]
1030    fn ser_and_deserialize_dyn_int_i32_3(#[case] val: i32) {
1031        // #[test]
1032        // fn ser_and_deserialize_dyn_int_i32_3() {
1033        //     let val: i32 = -111;
1034
1035        let mut ser = Biseri::new();
1036
1037        let v = DynInteger::<i32, 3>::new(val);
1038        v.bit_serialize(&mut ser);
1039        let r = ser.finish_add_data().unwrap();
1040        let (bits, bytes) = (r.total_bits, r.total_bytes);
1041        println!("bits: {}, bytes: {}", bits, bytes);
1042
1043        let mut der = Bides::from_biseri(&ser);
1044
1045        let dv = DynInteger::<i32, 3>::bit_deserialize(1, &mut der);
1046        assert!(dv.is_some());
1047
1048        let dv = dv.unwrap();
1049        assert_eq!(val, dv.0.val);
1050    }
1051
1052    #[rstest]
1053    fn ser_and_deserialize_fixed_int() {
1054        let mut ser = Biseri::new();
1055
1056        let v = VarWithGivenBitSize::<u32, 20>::new(1111);
1057        v.bit_serialize(&mut ser);
1058
1059        let r = ser.finish_add_data().unwrap();
1060        let (bits, bytes) = (r.total_bits, r.total_bytes);
1061        println!("bits: {}, bytes: {}", bits, bytes);
1062
1063        let mut der = Bides::from_biseri(&ser);
1064        let vv = VarWithGivenBitSize::<u32, 20>::bit_deserialize(1, &mut der);
1065
1066        println!("v: {:?}, vv: {:?}", v, vv);
1067        assert!(vv.is_some());
1068        let vv = vv.unwrap().0;
1069
1070        assert_eq!(v.val, vv.val);
1071    }
1072
1073    #[rstest]
1074    fn ser_and_deserialize_fixed_int_not_enough_data() {
1075        let mut ser = Biseri::new();
1076
1077        let v = VarWithGivenBitSize::<u32, 20>::new(1111);
1078        v.bit_serialize(&mut ser);
1079
1080        let r = ser.finish_add_data().unwrap();
1081        let (bits, bytes) = (r.total_bits, r.total_bytes);
1082        println!("bits: {}, bytes: {}", bits, bytes);
1083
1084        let mut der = Bides::from_biseri(&ser);
1085        der.data_cache.truncate(1);
1086        let vv = VarWithGivenBitSize::<u32, 20>::bit_deserialize(1, &mut der);
1087
1088        println!("v: {:?}, vv: {:?}", v, vv);
1089        assert!(vv.is_none());
1090    }
1091
1092    #[rstest]
1093    fn ser_and_deserialize_fixed_precision_1() {
1094        let mut ser = Biseri::new();
1095
1096        let v = FixPrecisionMinMax::<20, -50, 50>::new(12.3456);
1097        v.bit_serialize(&mut ser);
1098
1099        let r = ser.finish_add_data().unwrap();
1100        let (bits, bytes) = (r.total_bits, r.total_bytes);
1101        println!("bits: {}, bytes: {}", bits, bytes);
1102
1103        let mut der = Bides::from_biseri(&ser);
1104        let vv = FixPrecisionMinMax::<20, -50, 50>::bit_deserialize(1, &mut der);
1105
1106        println!("v: {:?}, vv: {:?}", v, vv);
1107        assert!(vv.is_some());
1108        let vv = vv.unwrap().0;
1109
1110        let eps = 1e-1;
1111        match v.val {
1112            FixPrecisionVal::Value(fpv) => {
1113                match vv.val {
1114                    FixPrecisionVal::Value(fpvv) => assert!((fpv - fpvv).abs() < eps),
1115                    _ => assert!(false)
1116                }
1117            },
1118            _ => assert!(false)
1119        }
1120    }
1121    #[rstest]
1122    fn ser_and_deserialize_fixed_precision_2() {
1123        let mut ser = Biseri::new();
1124
1125        let v = FixPrecisionMinMax::<20, -50, 50>::new(-12.3456);
1126        v.bit_serialize(&mut ser);
1127
1128        let r = ser.finish_add_data().unwrap();
1129        let (bits, bytes) = (r.total_bits, r.total_bytes);
1130        println!("bits: {}, bytes: {}", bits, bytes);
1131
1132        let mut der = Bides::from_biseri(&ser);
1133        let vv = FixPrecisionMinMax::<20, -50, 50>::bit_deserialize(1, &mut der);
1134
1135        println!("v: {:?}, vv: {:?}", v, vv);
1136        assert!(vv.is_some());
1137        let vv = vv.unwrap().0;
1138
1139        let eps = 1e-1;
1140        match v.val {
1141            FixPrecisionVal::Value(fpv) => {
1142                match vv.val {
1143                    FixPrecisionVal::Value(fpvv) => assert!((fpv - fpvv).abs() < eps),
1144                    _ => assert!(false)
1145                }
1146            },
1147            _ => assert!(false)
1148        }
1149    }
1150    #[rstest]
1151    fn ser_and_deserialize_fixed_precision_under() {
1152        let mut ser = Biseri::new();
1153
1154        let v = FixPrecisionMinMax::<10, -50, 50>::new(-60.0);
1155        v.bit_serialize(&mut ser);
1156
1157        let r = ser.finish_add_data().unwrap();
1158        let (bits, bytes) = (r.total_bits, r.total_bytes);
1159        println!("bits: {}, bytes: {}", bits, bytes);
1160
1161        let mut der = Bides::from_biseri(&ser);
1162        let vv = FixPrecisionMinMax::<10, -50, 50>::bit_deserialize(1, &mut der);
1163
1164        println!("v: {:?}, vv: {:?}", v, vv);
1165        assert!(vv.is_some());
1166        let vv = vv.unwrap().0;
1167
1168        match vv.val {
1169            FixPrecisionVal::Underflow => assert!(true),
1170            _ => assert!(false),
1171        }
1172    }
1173    #[rstest]
1174    fn ser_and_deserialize_fixed_precision_over() {
1175        let mut ser = Biseri::new();
1176
1177        let v = FixPrecisionMinMax::<10, -50, 50>::new(60.0);
1178        v.bit_serialize(&mut ser);
1179
1180        let r = ser.finish_add_data().unwrap();
1181        let (bits, bytes) = (r.total_bits, r.total_bytes);
1182        println!("bits: {}, bytes: {}", bits, bytes);
1183
1184        let mut der = Bides::from_biseri(&ser);
1185        let vv = FixPrecisionMinMax::<10, -50, 50>::bit_deserialize(1, &mut der);
1186
1187        println!("v: {:?}, vv: {:?}", v, vv);
1188        assert!(vv.is_some());
1189        let vv = vv.unwrap().0;
1190
1191        match vv.val {
1192            FixPrecisionVal::Overflow => assert!(true),
1193            _ => assert!(false)
1194        }
1195    }
1196}
1197