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> BitisOption<T> where T: BiserdiTrait + Default {
293    pub fn new_some(val: T) -> BitisOption<T> { BitisOption { val: Some(val) } }
294    pub fn new_none() -> BitisOption<T> { BitisOption { val: None } }
295}
296impl<T> BiserdiTrait for BitisOption<T> where T: BiserdiTrait + Default {
297    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
298        let mut size = 1;
299        match &self.val {
300            None => { false.bit_serialize(biseri)?; },
301            Some(v) => {
302                true.bit_serialize(biseri)?;
303                size += v.bit_serialize(biseri)?;
304            }
305        }
306        Some(size)
307    }
308    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
309        let mut size = 1;
310
311        let (is_set, _) = bool::bit_deserialize(version_id, bides)?;
312        let v = if is_set {
313            let vv = T::bit_deserialize(version_id, bides)?;
314            size += vv.1.clone();
315            Some(vv.0)
316        }
317        else { None };
318
319        Some((BitisOption{val: v}, size))
320    }
321}
322impl<T, TT> From<Option<TT>> for BitisOption<T> where T: BiserdiTrait + Default, TT: Into<T> {
323    fn from(value: Option<TT>) -> Self {
324        match value {
325            Some(v) => Self { val: Some(v.into()) },
326            None => Self { val: None }
327        }
328    }
329}
330impl<T> From<T> for BitisOption<T> where T: BiserdiTrait + Default {
331    fn from(val: T) -> Self {
332        Self{ val: Some(val) }
333    } }
334// impl<T, TT> Into<Option<TT>> for BitisOption<T> where T: BiserdiTrait + Default, TT: From<T>  {
335//     fn into(val: BitisOption<T>) -> Option<TT> {
336//         match val.val { Some(v) => Some(v.into()), None => None }
337//     }
338// }
339impl<T> std::fmt::Display for BitisOption<T> where T: BiserdiTrait + Default + Display {
340    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
341        match &self.val {
342            None => { write!(f, "None [opt]") },
343            Some(v) => { write!(f, "{} [opt]", v) }
344        }
345    } }
346impl<T> Default for BitisOption<T> where T: BiserdiTrait + Default {
347    fn default() -> Self { Self{val: None} }
348}
349
350// ****************************************************************************
351#[derive(Debug, Clone, PartialEq, Eq, Copy)]
352pub struct FixedArray<T: Default, const N: usize> { pub val: [T; N] }
353impl<T, const N: usize> BiserdiTrait for FixedArray<T, N> where T: BiserdiTrait + Default + Copy {
354    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
355        let mut s = 0;
356        for i in 0..N { s += self.val[i].bit_serialize(biseri)?; }
357        Some(s)
358    }
359    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
360        let mut v: [T; N] = [T::default(); N];
361        let mut bits = 0;
362        let mut cur_bits;
363        for i in 0..N { (v[i], cur_bits) = T::bit_deserialize(version_id, bides)?; bits += cur_bits; }
364        Some((Self{ val: v}, bits))
365    }
366}
367impl<T, const N: usize> BiserdiTraitVarBitSize for FixedArray<T, N> where T: BiserdiTraitVarBitSize + Default + Copy {
368    fn bit_serialize(self: &Self, total_bits_per_unit: u64, biseri: &mut Biseri) -> Option<u64> {
369        let mut s = 0;
370        for i in 0..N {
371            s += self.val[i].bit_serialize(total_bits_per_unit, biseri)?;
372        }
373        Some(s)
374    }
375    fn bit_deserialize(version_id: u16, total_bits_per_unit: u64, bides: &mut Bides) -> Option<(Self, u64)> {
376        let mut v = [T::default(); N];
377        let mut bits = 0;
378        let mut cur_bits;
379        for i in 0..N {
380            (v[i], cur_bits) = T::bit_deserialize(version_id, total_bits_per_unit, bides)?; bits += cur_bits; }
381        Some((Self{ val: v}, bits))
382    }
383}
384impl<T: Sized + Copy + BiserdiTrait + Default, const N: usize> From<[T; N]> for FixedArray<T, N> {
385    fn from(val: [T;N]) -> Self { Self{ val: val.clone()} } }
386impl<T: Sized + Copy + Display + Default, const N: usize> std::fmt::Display for FixedArray<T, N> {
387    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
388        let das: Vec<String> = self.val.iter().map(|v| format!("{}", v)).collect();
389        write!(f, "[{}]", das.join(", "))
390    } }
391impl<T: Sized + Copy + BiserdiTrait + Default, const N: usize> Default for FixedArray<T, N>  {
392    fn default() -> Self {
393        Self{val: [T::default(); N]}
394    }
395}
396
397// ****************************************************************************
398pub struct DynArray<T, const DYNSIZEBITS: u8> { pub val: Vec<T> }
399impl<T, const DYNSIZEBITS: u8> BiserdiTrait for DynArray<T, DYNSIZEBITS> where T: BiserdiTrait + Default + Copy {
400    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
401        let mut s = 0;
402        s += DynInteger::<u32, DYNSIZEBITS>::new(self.val.len() as u32).bit_serialize(biseri)?;
403        for d in self.val.iter() { s += d.bit_serialize(biseri)?; };
404        Some(s)
405    }
406    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
407        let mut s = 0;
408        let (v, cs) =
409            DynInteger::<u32, DYNSIZEBITS>::bit_deserialize(version_id, bides)?;
410        let mut data = Vec::with_capacity(cs as usize);
411        for _ci in 0..v.val {
412            let (vi, si) = T::bit_deserialize(version_id, bides)?;
413            s += si;
414            data.push(vi);
415        }
416        Some((Self{ val: data }, s+cs))
417    }
418}
419impl<T: Sized + Copy + BiserdiTraitVarBitSize, const DYNSIZEBITS: u8, const N: usize> From<[T; N]> for DynArray<T, DYNSIZEBITS> {
420    fn from(val: [T;N]) -> Self {
421        DynArray{ val:Vec::from(val)}
422    } }
423impl<T: Sized + Copy + BiserdiTraitVarBitSize, const DYNSIZEBITS: u8> From<Vec<T>> for DynArray<T, DYNSIZEBITS> {
424    fn from(val: Vec<T>) -> Self {
425        DynArray{ val: val.clone()}
426    } }
427impl<T: Sized + Copy + BiserdiTraitVarBitSize + Display, const DYNSIZEBITS: u8> std::fmt::Display for DynArray<T, DYNSIZEBITS> {
428    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
429        let das: Vec<String> = self.val.iter().map(|v| v.to_string()).collect();
430        write!(f, "[{} |dynbits:{}]", das.join(", "), DYNSIZEBITS)
431    } }
432impl<T: Sized + Copy + BiserdiTraitVarBitSize, const DYNSIZEBITS: u8> Default for DynArray<T, DYNSIZEBITS> {
433    fn default() -> Self {
434        Self{val: Vec::new()}
435    }
436}
437
438// ****************************************************************************
439#[derive(Debug, Clone, PartialEq, Eq, Default, Copy)]
440pub struct VarWithGivenBitSize<T: Sized + Copy + BiserdiTraitVarBitSize + Default, const NUM_BITS: u64> {
441    pub val: T
442}
443impl<T: Sized + Copy + BiserdiTraitVarBitSize + Default, const NUM_BITS: u64> VarWithGivenBitSize<T, NUM_BITS> {
444    pub fn new(v: T) -> Self { VarWithGivenBitSize {val: v} }
445}
446impl<T: Sized + Copy + BiserdiTraitVarBitSize + Default, const NUM_BITS: u64> From<T> for VarWithGivenBitSize<T, NUM_BITS> {
447    fn from(val: T) -> Self {
448        VarWithGivenBitSize::<T, NUM_BITS>::new(val)
449    }
450}
451// impl<const NUM_BITS: u64> From<usize> for VarWithGivenBitSize<usize, NUM_BITS> {
452//     fn from(val: usize) -> Self {
453//         VarWithGivenBitSize::<usize, NUM_BITS>::new(val)
454//     }
455// }
456impl<T: Sized + Copy + BiserdiTraitVarBitSize + Display + Default, const NUM_BITS: u64> std::fmt::Display for VarWithGivenBitSize<T, NUM_BITS> {
457    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
458        write!(f, "{} |bits:{}", self.val, NUM_BITS)
459} }
460impl<T: Sized + Copy + BiserdiTraitVarBitSize + Default, const NUM_BITS: u64> BiserdiTrait for VarWithGivenBitSize<T, NUM_BITS> {
461    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
462        self.val.bit_serialize(NUM_BITS, biseri)
463    }
464    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
465        let v = T::bit_deserialize(version_id, NUM_BITS, bides)?;
466        Some((Self{val: v.0}, v.1))
467    }
468}
469
470#[derive(Debug, Clone, PartialEq, Eq, Default, Copy)]
471pub struct DynInteger<
472    T: Sized + Copy + BiserdiTraitVarBitSize + AddAssign + Shl<Output = T> + Shr + Ord + PartialEq //+ TryFrom<u64>
473    + IntegerBaseFunctions + Default, const N: u8> {
474    pub val: T
475}
476impl<T: Display + Sized + Copy + BiserdiTraitVarBitSize + AddAssign + Shl<Output = T> + Shr + Ord + PartialEq + TryFrom<u64>
477    + IntegerBaseFunctions + Default, const N: u8> DynInteger<T, N> {
478    const DYN_SIZE: u8 = N;
479    pub fn new(v: T) -> Self{
480        DynInteger{val: v}
481    }
482}
483impl<T: Display + Sized + Copy + BiserdiTraitVarBitSize + AddAssign + Shl<Output = T> + Shr + Ord + PartialEq + TryFrom<u64>
484    + IntegerBaseFunctions + Default, const N: u8> BiserdiTrait for DynInteger<T, N> {
485    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
486        // let br = self.bits_required();
487        // let dyn_sections = br / Self::DYN_SIZE;
488        let mut bit_size: u64 = 1;
489        let mut val_work = self.val.get_absolute_uint();
490
491        if T::IS_SIGNED { self.val.is_val_negative().bit_serialize(biseri)?; bit_size +=1; }
492
493        (val_work != 0).bit_serialize(biseri);
494        while val_work > 0 {
495            // todo only serialize up to bitsize of T
496            val_work.bit_serialize(u64::from(Self::DYN_SIZE), biseri)?;
497            val_work >>= Self::DYN_SIZE;
498            bit_size += (Self::DYN_SIZE + 1) as u64;
499            let further_data = val_work > 0;
500            further_data.bit_serialize(biseri);
501        }
502        Some(bit_size)
503    }
504    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
505        let mut cur_shift: u64 = 0;
506        let mut v: u64 = 0;
507        let mut negative_sign = false;
508
509        let mut bit_size = 1;
510        if T::IS_SIGNED {
511            negative_sign = bool::bit_deserialize(version_id, bides)?.0; bit_size += 1; }
512        let mut further_data = bool::bit_deserialize(version_id, bides)?.0;
513        while further_data {
514            let vt = u64::bit_deserialize(version_id, Self::DYN_SIZE as u64, bides)?;
515            bit_size += vt.1 + 1;
516            v += vt.0 << cur_shift;
517            cur_shift += u64::from(Self::DYN_SIZE);
518            further_data = bool::bit_deserialize(version_id, bides)?.0;
519        }
520        let mut vv= T::try_from(v).ok()?;
521        if negative_sign {
522            vv = vv.switch_sign_if_possible();
523        }
524        Some((Self{val: vv}, bit_size))
525    }
526}
527impl<T: Display + Sized + Copy + BiserdiTraitVarBitSize + AddAssign + Shl<Output = T> + Shr + Ord + PartialEq + TryFrom<u64>
528    + IntegerBaseFunctions + Default, const N: u8> Display for DynInteger<T, N> {
529    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
530        write!(f, "{} |dynbits:{}]", self.val, N)
531    } }
532
533
534// ***
535#[derive(Debug, Clone, Default)]
536pub enum FixPrecisionVal {
537    #[default]
538    Overflow,
539    Value(f64),
540    Underflow
541}
542#[derive(Debug, Clone, Default)]
543pub struct FixPrecisionMinMax<const NUM_BITS: u8, const MIN_IVALUE: i64, const MAX_IVALUE: i64> {
544    pub val: FixPrecisionVal
545}
546impl<const NUM_BITS: u8, const MIN_IVALUE: i64, const MAX_IVALUE: i64> FixPrecisionMinMax<NUM_BITS, MIN_IVALUE, MAX_IVALUE> {
547    const MIN_VALUE: f64 = MIN_IVALUE as f64;
548    const MAX_VALUE: f64 = MAX_IVALUE as f64;
549    const RANGE_VALUE: f64 = Self::MAX_VALUE - Self::MIN_VALUE;
550    const MAX_INT_VALUE_FOR_BITS: u64 = (1_u64<<NUM_BITS) - 1_u64;
551    const MAX_VALUE_FOR_BITS: f64 = (Self::MAX_INT_VALUE_FOR_BITS - 2_u64) as f64;
552
553    pub fn new(val: f64) -> Self {
554        let mut obj = Self{val: FixPrecisionVal::Underflow};
555        obj.set(val);
556        obj
557    }
558    pub fn set(&mut self, val: f64) {
559        self.val = Self::u64_to_val(Self::val_to_u64(&Self::val_to_enum(val)));
560    }
561    fn val_to_enum(val: f64) -> FixPrecisionVal {
562        if val > Self::MAX_VALUE { FixPrecisionVal::Overflow }
563        else if val < Self::MIN_VALUE { FixPrecisionVal::Underflow }
564        else { FixPrecisionVal::Value(val) }
565    }
566    fn val_to_u64(v: &FixPrecisionVal) -> u64 {
567        let vu = match v {
568            // i = (v-Min) / (Max-Min) * 253 + 1
569            FixPrecisionVal::Value(v) => {
570                let vv= (v - Self::MIN_VALUE) / Self::RANGE_VALUE * Self::MAX_VALUE_FOR_BITS + 1.0;
571                vv.round() as u64
572            },
573            FixPrecisionVal::Underflow => 0,
574            FixPrecisionVal::Overflow => Self::MAX_INT_VALUE_FOR_BITS
575        };
576        // println!("vu: {}", vu);
577        vu
578    }
579    fn u64_to_val(v: u64) -> FixPrecisionVal {
580        if v == 0 { FixPrecisionVal::Underflow }
581        else if v == Self::MAX_INT_VALUE_FOR_BITS { FixPrecisionVal::Overflow }
582        else {
583            FixPrecisionVal::Value(((v-1) as f64) / Self::MAX_VALUE_FOR_BITS
584                * Self::RANGE_VALUE + Self::MIN_VALUE)
585        }
586    }
587}
588impl<const NUM_BITS: u8, const MIN_IVALUE: i64, const MAX_IVALUE: i64> BiserdiTrait for FixPrecisionMinMax<NUM_BITS, MIN_IVALUE, MAX_IVALUE> {
589    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
590        let v = Self::val_to_u64(&self.val);
591        println!("t: {}", v);
592        v.bit_serialize(NUM_BITS as u64, biseri)
593    }
594    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
595        // v = (i-1)/253 * (Max-Min) + Min
596        let (v, bits) = u64::bit_deserialize(version_id, NUM_BITS as u64, bides)?;
597        let vv = Self::u64_to_val(v);
598        Some((Self{val: vv}, bits))
599    }
600}
601impl<const NUM_BITS: u8, const MIN_IVALUE: i64, const MAX_IVALUE: i64> Display for FixPrecisionMinMax<NUM_BITS, MIN_IVALUE, MAX_IVALUE> {
602    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
603        match self.val {
604            FixPrecisionVal::Overflow => write!(f, "Overflow |dynbits:{}", NUM_BITS),
605            FixPrecisionVal::Underflow => write!(f, "Underflow |dynbits:{}", NUM_BITS),
606            FixPrecisionVal::Value(v) => write!(f, "{} |dynbits:{}", v, NUM_BITS)
607        }
608    } }
609impl<const NUM_BITS: u8, const MIN_IVALUE: i64, const MAX_IVALUE: i64> From<f32> for FixPrecisionMinMax<NUM_BITS, MIN_IVALUE, MAX_IVALUE> {
610    fn from(value: f32) -> Self { Self::new(value.into()) }
611}
612impl<const NUM_BITS: u8, const MIN_IVALUE: i64, const MAX_IVALUE: i64> From<f64> for FixPrecisionMinMax<NUM_BITS, MIN_IVALUE, MAX_IVALUE> {
613    fn from(value: f64) -> Self { Self::new(value.into()) }
614}
615impl<const NUM_BITS: u8, const MIN_IVALUE: i64, const MAX_IVALUE: i64> PartialEq for FixPrecisionMinMax<NUM_BITS, MIN_IVALUE, MAX_IVALUE> {
616    fn eq(&self, other: &Self) -> bool {
617        Self::val_to_u64(&self.val) == Self::val_to_u64(&other.val)
618    }
619    fn ne(&self, other: &Self) -> bool { !self.eq(other) }
620}
621
622// *****
623#[derive(Debug, Clone, PartialEq)]
624pub struct Binary<const DYNSIZEBITS: u8> {
625    pub val: Vec<u8>
626}
627impl<const DYNSIZEBITS: u8> Binary<DYNSIZEBITS> {
628    pub fn new(data: Vec<u8>) -> Self {
629        Self{ val: data }
630    }
631    pub fn empty() -> Self {
632        Self{val: Vec::new()}
633    }
634}
635impl<const DYNSIZEBITS: u8> BiserdiTrait for Binary<DYNSIZEBITS> {
636    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
637        let mut s = 0;
638        s += DynInteger::<u32, DYNSIZEBITS>::new(self.val.len() as u32).bit_serialize(biseri)?;
639        for d in self.val.iter() { s += d.bit_serialize(8, biseri)?; };
640        Some(s)
641    }
642    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
643        let mut s = 0;
644        let (v, cs) =
645            DynInteger::<u32, DYNSIZEBITS>::bit_deserialize(version_id, bides)?;
646        let mut data = Vec::with_capacity(cs as usize);
647        for _ci in 0..v.val {
648            let (vi, si) = u8::bit_deserialize(version_id, 8, bides)?;
649            s += si;
650            data.push(vi);
651        }
652        Some((Self{ val: data }, s+cs))
653    }
654}
655impl<const N: u8> std::fmt::Display for Binary< N> {
656    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
657        let hex = self.val.iter().map(|b| format!("{:02x}", b).to_string()).collect::<Vec<String>>().join(" ");
658        write!(f, "{:x?} |dynbits:{}", hex, N)
659    }
660}
661
662#[cfg(test)]
663mod bitis_base_serialization_deserialization {
664    use rstest::rstest;
665    use crate::lib_impl::berde::{Bides, Biseri};
666    use crate::{deserialize, serialize};
667    use super::*;
668
669    #[rstest]
670    fn add_one_u8() {
671        let mut b = Biseri::new();
672        let d = 0b10101010_u8;
673
674        b.add_data_base_u8(&d, 8);
675
676        assert_eq!(b.clone().data_cache.len(), 1);
677        assert_eq!(b.sub_byte_counter, 0);
678
679        let r = b.finish_add_data().unwrap();
680        assert_eq!((r.total_bits, r.total_bytes), (8, 1));
681    }
682
683    #[rstest]
684    #[case::ot_uint4(4, 1, 4, 1)]
685    #[case::tt_uint4(4, 2, 8, 1)]
686    #[case::ot_uint6(6, 1, 6, 1)]
687    #[case::tt_uint6(6, 2, 12, 2)]
688    #[case::trt_uint6(6, 3, 18, 3)]
689    #[case::ft_uint6(6, 4, 24, 3)]
690    fn add_one_var(#[case] bitsize: u64, #[case] repeated: u8, #[case] final_bitsize: u64, #[case] num_bytes: u64) {
691        let mut b = Biseri::new();
692        let d = 0b10101010_u8;
693
694        for _i in 0..repeated {
695            b.add_data_base_u8(&d, bitsize);
696        }
697
698        let r = b.finish_add_data().unwrap();
699        assert_eq!((r.total_bits, r.total_bytes), (final_bitsize, num_bytes));
700    }
701
702    #[rstest]
703    #[case::ok(5, 4, 5)]
704    #[case::expected_overflow(0b10011, 4, 3)]
705    fn serialize_and_deserialize_base(#[case] val_in: u8, #[case] bitsize: u64, #[case] val_out: u8) {
706        let mut ser = Biseri::new();
707
708        ser.add_data_base_u8(&val_in, bitsize);
709        ser.finish_add_data();
710
711        let mut des = Bides::from_biseri(&ser);
712
713        assert_eq!(des.data_cache, ser.data_cache);
714
715        let r = des.decode_data_base_u8(bitsize);
716        assert!(r.is_some());
717        let (dd, bs) = r.unwrap();
718        assert_eq!(bs, 0);
719
720        println!("val_in: {val_in} vs. dd: {dd} (expected: {val_out}");
721        assert_eq!(val_out, dd);
722    }
723
724    #[rstest]
725    #[case::ok(3*256+5, 16, 3*256+5)]
726    #[case::ok(3*256+5, 12, 3*256+5)]
727    #[case::ok(3*256+5, 9, 1*256+5)]
728    fn serialize_and_deserialize_u16_single(#[case] val_in: u16, #[case] bitsize: u64, #[case] val_out: u16) {
729        let val_in_vec = val_in.to_le_bytes().clone();
730
731        let mut ser = Biseri::new();
732
733        let mut total_size = bitsize;
734        val_in_vec.clone().iter().for_each(|x| {
735            total_size = ser.add_data_base_u8(&x, bitsize);
736        });
737        ser.finish_add_data();
738
739        println!("ser.cache: {:?}", ser.data_cache);
740
741        assert_eq!(ser.data_cache.len(), 2);
742
743        let mut des = Bides::from_biseri(&ser);
744
745        assert_eq!(des.data_cache, ser.data_cache);
746
747        let mut dd = Vec::new();
748        let mut total_size = bitsize;
749        while total_size > 0 {
750            let ddd;
751            let r = des.decode_data_base_u8(total_size);
752            assert!(r.is_some());
753            (ddd, total_size) = r.unwrap();
754            dd.push(ddd);
755        };
756
757        let ddv = u16::from_le_bytes(dd.clone().try_into().unwrap());
758        println!("val_in: {val_in} ({val_in_vec:?}) vs. ddv: {ddv:?} ({dd:?}) (expected: {val_out})");
759        assert_eq!(val_out, ddv);
760    }
761
762    fn add_two_u16_fixed(ser: &mut Biseri, bits: u64) -> BiserSizes {
763        let d: u16 = 3;
764
765        ser.add_data(&d.to_le_bytes().to_vec(), bits);
766        ser.add_data(&d.to_le_bytes().to_vec(), bits);
767        ser.finish_add_data().unwrap()
768    }
769    #[rstest]
770    fn serialize_u16_fixed_full() {
771        let mut ser = Biseri::new();
772
773        let r = add_two_u16_fixed(&mut ser, 16);
774        let (lbits, lbytes) = (r.total_bits, r.total_bytes);
775
776        assert_eq!(ser.data_cache.len(), 4);
777        assert_eq!(lbytes, 4);
778        assert_eq!(lbits, 2 * 16);
779
780        assert_eq!(ser.data_cache[0], 3);
781        assert_eq!(ser.data_cache[1], 0);
782        assert_eq!(ser.data_cache[2], 3);
783        assert_eq!(ser.data_cache[3], 0);
784    }
785
786    #[rstest]
787    fn serialize_u16_fixed_12b() {
788        let mut ser = Biseri::new();
789
790        let r = add_two_u16_fixed(&mut ser, 12);
791        let (lbits, lbytes) = (r.total_bits, r.total_bytes);
792
793        assert_eq!(ser.data_cache.len(), 3);
794        assert_eq!(lbytes, 3);
795        assert_eq!(lbits, 2 * 12);
796
797        assert_eq!(ser.data_cache[0], 3);
798        assert_eq!(ser.data_cache[1], 3 << 4);
799        assert_eq!(ser.data_cache[2], 0);
800    }
801
802    #[rstest]
803    #[case::bitsize_16(16)]
804    #[case::bitsize_14(14)]
805    #[case::bitsize_12(12)]
806    fn ser_and_deserialize_u16_fixed(#[case] bits: u64) {
807        let mut ser = Biseri::new();
808
809        let _ = add_two_u16_fixed(&mut ser, bits);
810
811        let mut des = Bides::from_biseri(&ser);
812
813        assert_eq!(des.data_cache, ser.data_cache);
814
815        let d1 = des.decode_data(bits, 2);
816        assert!(d1.is_some());
817        let d2 = des.decode_data(bits, 2);
818        assert!(d2.is_some());
819
820        let d1 = d1.unwrap();
821        let d2 = d2.unwrap();
822
823        assert_eq!(d1[0], 3);
824        assert_eq!(d1[1], 0);
825        assert_eq!(d2[0], 3);
826        assert_eq!(d2[1], 0);
827    }
828
829    #[rstest]
830    fn ser_and_deserialize_i16_fixed() {
831        let mut ser = Biseri::new();
832
833        let v: i8 = -11;
834        v.bit_serialize(5, &mut ser);
835
836        let r = ser.finish_add_data().unwrap();
837        let (bits, bytes) = (r.total_bits, r.total_bytes);
838
839        println!("bits: {}, bytes: {}", bits, bytes);
840
841        let mut des = Bides::from_biseri(&ser);
842
843        let vv = i8::bit_deserialize(1,5, &mut des);
844        println!("v: {}, vv: {:?}", v, vv);
845
846        assert!(vv.is_some());
847
848        let vv = vv.unwrap();
849        println!("bits_des: {}", vv.1);
850        assert_eq!(v, vv.0);
851    }
852
853    #[rstest]
854    fn de_and_serialize_various_unsigned() {
855        // ***********************************************************
856        let mut ser = Biseri::new();
857        let v1: u8 = 5;
858        v1.bit_serialize(6, &mut ser);
859        // ser.add_data_u8(&v1, 6);
860        let v2: u16 = 15;
861        v2.bit_serialize(14, &mut ser);
862        // ser.add_data_u16(&v2, 14);
863        let v3: u32 = 55;
864        v3.bit_serialize(22, &mut ser);
865        // ser.add_data_u32(&v3, 30);
866        let r = ser.finish_add_data().unwrap();
867        let (bits, bytes) = (r.total_bits, r.total_bytes);
868
869        println!("bits: {}, bytes: {}", bits, bytes);
870
871        // // ***********************************************************
872        let mut des = Bides::from_biseri(&ser);
873        let vo1 = u8::bit_deserialize(1,6, &mut des);
874        // let vo1 = des.decode_data_u8(6);
875        let vo2 = u16::bit_deserialize(1,14, &mut des);
876        // let vo2 = des.decode_data_u16(14);
877        let vo3 = u32::bit_deserialize(1,22, &mut des);
878        // let vo3 = des.decode_data_u32(30);
879
880        println!("v1: {}, v2: {}, v3: {} vs vo1: {:?}, vo2: {:?}, vo3: {:?}", v1, v2, v3, vo1, vo2, vo3);
881
882        // ***********************************************************
883        assert!(vo1.is_some());
884        assert_eq!(v1, vo1.unwrap().0);
885
886        assert!(vo2.is_some());
887        assert_eq!(v2, vo2.unwrap().0);
888
889        assert!(vo3.is_some());
890        assert_eq!(v3, vo3.unwrap().0);
891    }
892
893    #[rstest]
894    fn de_and_serialize_various_float() {
895        // ***********************************************************
896        let mut ser = Biseri::new();
897        let v1: f32 = 56.78;
898        v1.bit_serialize(&mut ser);
899        // ser.add_data_f32(&v1);
900        let v2: u8 = 5;
901        v2.bit_serialize(5, &mut ser);
902        // ser.add_data_u8(&v2, 5);
903        let v3: bool = true;
904        v3.bit_serialize(&mut ser);
905        // ser.add_data_bool(&v3);
906        let v4: bool = false;
907        v4.bit_serialize(&mut ser);
908        // ser.add_data_bool(&v4);
909        v1.bit_serialize(&mut ser);
910        // ser.add_data_f32(&v1);
911        let r = ser.finish_add_data().unwrap();
912        let (bits, bytes) = (r.total_bits, r.total_bytes);
913
914        println!("bits: {}, bytes: {}", bits, bytes);
915
916        // ***********************************************************
917        let mut des = Bides::from_biseri(&ser);
918        let vo1 = f32::bit_deserialize(1, &mut des);
919        let vo2 = u8::bit_deserialize(1,5, &mut des);
920        let vo3 = bool::bit_deserialize(1,&mut des);
921        let vo4 = bool::bit_deserialize(1,&mut des);
922        let vo5 = f32::bit_deserialize(1,&mut des);
923        // let vo1 = des.decode_data_f32();
924        // let vo2 = des.decode_data_u8(5);
925        // let vo3 = des.decode_data_bool();
926        // let vo4 = des.decode_data_bool();
927        // let vo5 = des.decode_data_f32();
928
929        println!("vo1: {:?}, vo2: {:?}, vo3: {:?}, vo4: {:?}, vo4: {:?}", vo1, vo2, vo3, vo4, vo5);
930
931        // ***********************************************************
932        assert!(vo1.is_some());
933        assert_eq!(v1, vo1.unwrap().0);
934
935        assert!(vo2.is_some());
936        assert_eq!(v2, vo2.unwrap().0);
937
938        assert!(vo3.is_some());
939        assert_eq!(v3, vo3.unwrap().0);
940
941        assert!(vo4.is_some());
942        assert_eq!(v4, vo4.unwrap().0);
943
944        assert!(vo5.is_some());
945        assert_eq!(v1, vo5.unwrap().0);
946    }
947
948    #[rstest]
949    fn serialize_and_deserialize_array_uint() {
950        let mut ser = Biseri::new();
951
952        let v: FixedArray<VarWithGivenBitSize<u16, 5>, 4> = [11.into(), 12.into(), 22.into(), 23.into()].into();
953        v.bit_serialize(&mut ser);
954        let r = ser.finish_add_data().unwrap();
955        let (bits, bytes) = (r.total_bits, r.total_bytes);
956
957        println!("bits: {}, bytes: {}", bits, bytes);
958
959        let mut des = Bides::from_biseri(&ser);
960        let vv = FixedArray::<VarWithGivenBitSize<u16, 5>, 4>::bit_deserialize(1,&mut des);
961
962        assert!(vv.is_some());
963        let vv = vv.unwrap().0;
964
965        assert_eq!(v.val[0], vv.val[0]);
966        assert_eq!(v.val[1], vv.val[1]);
967        assert_eq!(v.val[2], vv.val[2]);
968        assert_eq!(v.val[3], vv.val[3]);
969    }
970
971    #[rstest]
972    fn serialize_and_deserialize_array_bool() {
973        let mut ser = Biseri::new();
974
975        let v= FixedArray::from([true, true, false, true]);
976        v.bit_serialize(&mut ser);
977        let r = ser.finish_add_data().unwrap();
978        let (bits, bytes) = (r.total_bits, r.total_bytes);
979        println!("bits: {}, bytes: {}", bits, bytes);
980
981        let mut des = Bides::from_biseri(&ser);
982        let vv = FixedArray::<bool, 4>::bit_deserialize(1,&mut des);
983
984        assert!(vv.is_some());
985        let vv = vv.unwrap().0;
986
987        assert_eq!(v.val[0], vv.val[0]);
988        assert_eq!(v.val[1], vv.val[1]);
989        assert_eq!(v.val[2], vv.val[2]);
990        assert_eq!(v.val[3], vv.val[3]);
991    }
992    #[rstest]
993    fn serialize_and_deserialize_array_f64() {
994        let mut ser = Biseri::new();
995
996        let v = FixedArray::from([1.1, 1.2, 22.34, 123456.78]);
997        v.bit_serialize(&mut ser);
998        let r = ser.finish_add_data().unwrap();
999        let (bits, bytes) = (r.total_bits, r.total_bytes);
1000        println!("bits: {}, bytes: {}", bits, bytes);
1001
1002        let mut des = Bides::from_biseri(&ser);
1003        let vv = FixedArray::<f64, 4>::bit_deserialize(1,&mut des);
1004
1005        assert!(vv.is_some());
1006        let vv = vv.unwrap().0;
1007
1008        assert_eq!(v.val[0], vv.val[0]);
1009        assert_eq!(v.val[1], vv.val[1]);
1010        assert_eq!(v.val[2], vv.val[2]);
1011        assert_eq!(v.val[3], vv.val[3]);
1012    }
1013
1014    #[rstest]
1015    #[case::val_0(0, 1, 1)]
1016    #[case::val_1(1, 5, 1)]
1017    #[case::val_10(10, 9, 2)]
1018    fn serialize_dyn_int_u32_3(#[case] val: u32, #[case] ex_bits: u64, #[case] ex_bytes: u64) {
1019        // #[test]
1020        // fn serialize_dyn_int_u32_3() {
1021        //     let val: u32 = 10;
1022        //     let ex_bits: u64 = 9;
1023        //     let ex_bytes: u64 = 2;
1024
1025        let mut ser = Biseri::new();
1026
1027        let v = DynInteger::<u32, 3>::new(val);
1028        v.bit_serialize(&mut ser);
1029        let r = ser.finish_add_data().unwrap();
1030        let (bits, bytes) = (r.total_bits, r.total_bytes);
1031        println!("bits: {}, bytes: {}", bits, bytes);
1032
1033        assert_eq!(bits, ex_bits);
1034        assert_eq!(bytes, ex_bytes);
1035    }
1036
1037    #[rstest]
1038    #[case::val_0(0, 2, 1)]
1039    #[case::val_1(1, 6, 1)]
1040    #[case::val_10(10, 10, 2)]
1041    fn serialize_dyn_int_i32_3(#[case] val: i32, #[case] ex_bits: u64, #[case] ex_bytes: u64) {
1042        // #[test]
1043        // fn serialize_dyn_int_i32_3() {
1044        //     let val: i32 = -1;
1045        //     let ex_bits: u64 = 6;
1046        //     let ex_bytes: u64 = 1;
1047
1048        let mut ser = Biseri::new();
1049
1050        let v = DynInteger::<i32, 3>::new(val);
1051        v.bit_serialize(&mut ser);
1052        let r = ser.finish_add_data().unwrap();
1053        let (bits, bytes) = (r.total_bits, r.total_bytes);
1054        println!("bits: {}, bytes: {}", bits, bytes);
1055
1056        assert_eq!(bits, ex_bits);
1057        assert_eq!(bytes, ex_bytes);
1058    }
1059
1060    #[rstest]
1061    #[case::val_0(0)]
1062    #[case::val_1(1)]
1063    #[case::val_10(10)]
1064    #[case::val_m1(-1)]
1065    #[case::val_m1111(-1111)]
1066    fn ser_and_deserialize_dyn_int_i32_3(#[case] val: i32) {
1067        // #[test]
1068        // fn ser_and_deserialize_dyn_int_i32_3() {
1069        //     let val: i32 = -111;
1070
1071        let mut ser = Biseri::new();
1072
1073        let v = DynInteger::<i32, 3>::new(val);
1074        v.bit_serialize(&mut ser);
1075        let r = ser.finish_add_data().unwrap();
1076        let (bits, bytes) = (r.total_bits, r.total_bytes);
1077        println!("bits: {}, bytes: {}", bits, bytes);
1078
1079        let mut der = Bides::from_biseri(&ser);
1080
1081        let dv = DynInteger::<i32, 3>::bit_deserialize(1, &mut der);
1082        assert!(dv.is_some());
1083
1084        let dv = dv.unwrap();
1085        assert_eq!(val, dv.0.val);
1086    }
1087
1088    #[rstest]
1089    fn ser_and_deserialize_fixed_int() {
1090        let mut ser = Biseri::new();
1091
1092        let v = VarWithGivenBitSize::<u32, 20>::new(1111);
1093        v.bit_serialize(&mut ser);
1094
1095        let r = ser.finish_add_data().unwrap();
1096        let (bits, bytes) = (r.total_bits, r.total_bytes);
1097        println!("bits: {}, bytes: {}", bits, bytes);
1098
1099        let mut der = Bides::from_biseri(&ser);
1100        let vv = VarWithGivenBitSize::<u32, 20>::bit_deserialize(1, &mut der);
1101
1102        println!("v: {:?}, vv: {:?}", v, vv);
1103        assert!(vv.is_some());
1104        let vv = vv.unwrap().0;
1105
1106        assert_eq!(v.val, vv.val);
1107    }
1108
1109    #[rstest]
1110    fn ser_and_deserialize_fixed_int_not_enough_data() {
1111        let mut ser = Biseri::new();
1112
1113        let v = VarWithGivenBitSize::<u32, 20>::new(1111);
1114        v.bit_serialize(&mut ser);
1115
1116        let r = ser.finish_add_data().unwrap();
1117        let (bits, bytes) = (r.total_bits, r.total_bytes);
1118        println!("bits: {}, bytes: {}", bits, bytes);
1119
1120        let mut der = Bides::from_biseri(&ser);
1121        der.data_cache.truncate(1);
1122        let vv = VarWithGivenBitSize::<u32, 20>::bit_deserialize(1, &mut der);
1123
1124        println!("v: {:?}, vv: {:?}", v, vv);
1125        assert!(vv.is_none());
1126    }
1127
1128    #[rstest]
1129    fn ser_and_deserialize_fixed_precision_1() {
1130        let mut ser = Biseri::new();
1131
1132        let v = FixPrecisionMinMax::<20, -50, 50>::new(12.3456);
1133        v.bit_serialize(&mut ser);
1134
1135        let r = ser.finish_add_data().unwrap();
1136        let (bits, bytes) = (r.total_bits, r.total_bytes);
1137        println!("bits: {}, bytes: {}", bits, bytes);
1138
1139        let mut der = Bides::from_biseri(&ser);
1140        let vv = FixPrecisionMinMax::<20, -50, 50>::bit_deserialize(1, &mut der);
1141
1142        println!("v: {:?}, vv: {:?}", v, vv);
1143        assert!(vv.is_some());
1144        let vv = vv.unwrap().0;
1145
1146        let eps = 1e-1;
1147        match v.val {
1148            FixPrecisionVal::Value(fpv) => {
1149                match vv.val {
1150                    FixPrecisionVal::Value(fpvv) => assert!((fpv - fpvv).abs() < eps),
1151                    _ => assert!(false)
1152                }
1153            },
1154            _ => assert!(false)
1155        }
1156    }
1157    #[rstest]
1158    fn ser_and_deserialize_fixed_precision_2() {
1159        let mut ser = Biseri::new();
1160
1161        let v = FixPrecisionMinMax::<20, -50, 50>::new(-12.3456);
1162        v.bit_serialize(&mut ser);
1163
1164        let r = ser.finish_add_data().unwrap();
1165        let (bits, bytes) = (r.total_bits, r.total_bytes);
1166        println!("bits: {}, bytes: {}", bits, bytes);
1167
1168        let mut der = Bides::from_biseri(&ser);
1169        let vv = FixPrecisionMinMax::<20, -50, 50>::bit_deserialize(1, &mut der);
1170
1171        println!("v: {:?}, vv: {:?}", v, vv);
1172        assert!(vv.is_some());
1173        let vv = vv.unwrap().0;
1174
1175        let eps = 1e-1;
1176        match v.val {
1177            FixPrecisionVal::Value(fpv) => {
1178                match vv.val {
1179                    FixPrecisionVal::Value(fpvv) => assert!((fpv - fpvv).abs() < eps),
1180                    _ => assert!(false)
1181                }
1182            },
1183            _ => assert!(false)
1184        }
1185    }
1186    #[rstest]
1187    fn ser_and_deserialize_fixed_precision_under() {
1188        let mut ser = Biseri::new();
1189
1190        let v = FixPrecisionMinMax::<10, -50, 50>::new(-60.0);
1191        v.bit_serialize(&mut ser);
1192
1193        let r = ser.finish_add_data().unwrap();
1194        let (bits, bytes) = (r.total_bits, r.total_bytes);
1195        println!("bits: {}, bytes: {}", bits, bytes);
1196
1197        let mut der = Bides::from_biseri(&ser);
1198        let vv = FixPrecisionMinMax::<10, -50, 50>::bit_deserialize(1, &mut der);
1199
1200        println!("v: {:?}, vv: {:?}", v, vv);
1201        assert!(vv.is_some());
1202        let vv = vv.unwrap().0;
1203
1204        match vv.val {
1205            FixPrecisionVal::Underflow => assert!(true),
1206            _ => assert!(false),
1207        }
1208    }
1209    #[rstest]
1210    fn ser_and_deserialize_fixed_precision_over() {
1211        let mut ser = Biseri::new();
1212
1213        let v = FixPrecisionMinMax::<10, -50, 50>::new(60.0);
1214        v.bit_serialize(&mut ser);
1215
1216        let r = ser.finish_add_data().unwrap();
1217        let (bits, bytes) = (r.total_bits, r.total_bytes);
1218        println!("bits: {}, bytes: {}", bits, bytes);
1219
1220        let mut der = Bides::from_biseri(&ser);
1221        let vv = FixPrecisionMinMax::<10, -50, 50>::bit_deserialize(1, &mut der);
1222
1223        println!("v: {:?}, vv: {:?}", v, vv);
1224        assert!(vv.is_some());
1225        let vv = vv.unwrap().0;
1226
1227        match vv.val {
1228            FixPrecisionVal::Overflow => assert!(true),
1229            _ => assert!(false)
1230        }
1231    }
1232
1233    #[rstest]
1234    fn ser_and_deserialize_fixed_precision_vals() {
1235        type ValT = FixPrecisionMinMax<3, 1, 2>;
1236
1237        {
1238            let v = ValT::new(1.);
1239            let vv = deserialize::<ValT>(&serialize(&v));
1240            println!("v: {:?}, vv: {:?}", v, vv);
1241            assert!(vv.is_some());
1242            let vv = vv.unwrap().0;
1243            assert!(v==vv);
1244        }
1245        {
1246            let v = ValT::new(1.2);
1247            let vv = deserialize::<ValT>(&serialize(&v));
1248            println!("v: {:?}, vv: {:?}", v, vv);
1249            assert!(vv.is_some());
1250            let vv = vv.unwrap().0;
1251            assert!(v==vv);
1252        }
1253        {
1254            let v = ValT::new(1.21);
1255            let vv = deserialize::<ValT>(&serialize(&v));
1256            println!("v: {:?}, vv: {:?}", v, vv);
1257            assert!(vv.is_some());
1258            let vv = vv.unwrap().0;
1259            assert!(v==vv);
1260        }
1261    }
1262}
1263