bitis_lib/lib_impl/
berde.rs

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