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::MAX_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 + 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> Display for FixedArray<T, N> {
748    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
749        let das: Vec<String> = self.val.iter().map(|v| format!("{:?}", v)).collect();
750        write!(f, "[{}]", das.join(", "))
751    } }
752impl<T: Sized + BiserdiTrait + Default + Debug, const N: usize> Default for FixedArray<T, N>  {
753    fn default() -> Self {
754        Self{val: array_init::array_init(|_| T::default())}
755    }
756}
757impl<T: Sized + BiserdiTrait + Default + Debug + Clone, const N: usize> Into<[T; N]> for FixedArray<T, N> {
758    fn into(self) -> [T; N] { map_array_init(&self.val, |v| v.clone()) }
759}
760impl<T: Sized + Clone + BiserdiTrait + Default + Debug, const N: usize> From<[T; N]> for FixedArray<T, N> {
761    fn from(v: [T;N]) -> Self { Self{ val: map_array_init(&v, |v| v.clone()) } }
762}
763impl<T: Sized + Clone + BiserdiTrait + Default + Debug + ValFromInto<U>, const N: usize, U> ValFromInto<[U; N]> for FixedArray<T, N> {
764    fn val_into(&self) -> [U; N] { map_array_init(&self.val, |v| v.clone().val_into()) }
765    fn val_from(v: &[U; N]) -> Self { Self{val: map_array_init(&v, |v| T::val_from(v).into())} }
766}
767
768// ****************************************************************************
769#[derive(Debug, Clone, PartialEq)]
770pub struct DynArray<T, const DYNSIZEBITS: u8> where T: BiserdiTrait + Default { pub val: Vec<T> }
771impl<T, const DYNSIZEBITS: u8> BiserdiTrait for DynArray<T, DYNSIZEBITS> where T: BiserdiTrait + Default + Clone {
772    fn bit_serialize(self: &Self, biseri: &mut Biseri) -> Option<u64> {
773        let mut s = 0;
774        s += DynInteger::<u32, 32, DYNSIZEBITS>::new(self.val.len() as u32).bit_serialize(biseri)?;
775        for d in self.val.iter() { s += d.bit_serialize(biseri)?; };
776        Some(s)
777    }
778    fn bit_deserialize(version_id: u16, bides: &mut Bides) -> Option<(Self, u64)> {
779        let mut s = 0;
780        let (v, cs) =
781            DynInteger::<u32, 32, DYNSIZEBITS>::bit_deserialize(version_id, bides)?;
782        let mut data = Vec::with_capacity(cs as usize);
783        for _ci in 0..v.val {
784            let (vi, si) = T::bit_deserialize(version_id, bides)?;
785            s += si;
786            data.push(vi);
787        }
788        Some((Self{ val: data }, s+cs))
789    }
790}
791impl<T: Sized + BiserdiTrait + Default + Debug + Clone, const DYNSIZEBITS: u8, const N: usize> From<[T; N]> for DynArray<T, DYNSIZEBITS> {
792    fn from(val: [T;N]) -> Self {
793        DynArray{val: val.to_vec()}
794    } }
795impl<T: Sized + BiserdiTrait + Default + Debug + Clone, const DYNSIZEBITS: u8> From<Vec<T>> for DynArray<T, DYNSIZEBITS> {
796    fn from(val: Vec<T>) -> Self {
797        DynArray{val: val}
798    } }
799impl<T: Sized + BiserdiTrait + Display + Debug + Default + Clone, const DYNSIZEBITS: u8> std::fmt::Display for DynArray<T, DYNSIZEBITS> {
800    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
801        let das: Vec<String> = self.val.iter().map(|v| v.to_string()).collect();
802        write!(f, "[{} |dynbits:{}]", das.join(", "), DYNSIZEBITS)
803    } }
804impl<T: Sized + BiserdiTrait + Default + Debug + Clone, const DYNSIZEBITS: u8> Default for DynArray<T, DYNSIZEBITS> {
805    fn default() -> Self {
806        Self{val: Vec::new()}
807    }
808}
809impl<T: Sized + BiserdiTrait + Default + Debug, const DYNSIZEBITS: u8> Into<Vec<T>> for DynArray<T, DYNSIZEBITS> {
810    fn into(self) -> Vec<T> { self.val }
811}
812impl<T: Sized + BiserdiTrait + Default + Debug +  ValFromInto<U>, const DYNSIZEBITS: u8, U> ValFromInto<Vec<U>> for DynArray<T, DYNSIZEBITS> {
813    fn val_into(&self) -> Vec<U> { self.val.iter().map(|v| v.val_into()).collect() }
814    fn val_from(val: &Vec<U>) -> Self { Self { val: val.iter().map(|v| { T::val_from(v).into() }).collect() } }
815}
816
817
818
819#[cfg(test)]
820mod bitis_base_serialization_deserialization {
821    use rstest::rstest;
822    use crate::lib_impl::berde::{Bides, Biseri};
823    use crate::{deserialize, serialize};
824    use super::*;
825
826    #[rstest]
827    fn add_one_u8() {
828        let mut b = Biseri::new();
829        let d = 0b10101010_u8;
830
831        b.add_data_base_u8(&d, 8);
832
833        assert_eq!(b.clone().data_cache.len(), 1);
834        assert_eq!(b.sub_byte_counter, 0);
835
836        let r = b.finish_add_data().unwrap();
837        assert_eq!((r.total_bits, r.total_bytes), (8, 1));
838    }
839
840    #[rstest]
841    #[case::ot_uint4(4, 1, 4, 1)]
842    #[case::tt_uint4(4, 2, 8, 1)]
843    #[case::ot_uint6(6, 1, 6, 1)]
844    #[case::tt_uint6(6, 2, 12, 2)]
845    #[case::trt_uint6(6, 3, 18, 3)]
846    #[case::ft_uint6(6, 4, 24, 3)]
847    fn add_one_var(#[case] bitsize: u64, #[case] repeated: u8, #[case] final_bitsize: u64, #[case] num_bytes: u64) {
848        let mut b = Biseri::new();
849        let d = 0b10101010_u8;
850
851        for _i in 0..repeated {
852            b.add_data_base_u8(&d, bitsize);
853        }
854
855        let r = b.finish_add_data().unwrap();
856        assert_eq!((r.total_bits, r.total_bytes), (final_bitsize, num_bytes));
857    }
858
859    #[rstest]
860    #[case::ok(5, 4, 5)]
861    #[case::expected_overflow(0b10011, 4, 3)]
862    fn serialize_and_deserialize_base(#[case] val_in: u8, #[case] bitsize: u64, #[case] val_out: u8) {
863        let mut ser = Biseri::new();
864
865        ser.add_data_base_u8(&val_in, bitsize);
866        ser.finish_add_data();
867
868        let mut des = Bides::from_biseri(&ser);
869
870        assert_eq!(des.data_cache, ser.data_cache);
871
872        let r = des.decode_data_base_u8(bitsize);
873        assert!(r.is_some());
874        let (dd, bs) = r.unwrap();
875        assert_eq!(bs, 0);
876
877        println!("val_in: {val_in} vs. dd: {dd} (expected: {val_out}");
878        assert_eq!(val_out, dd);
879    }
880
881    #[rstest]
882    #[case::ok(3*256+5, 16, 3*256+5)]
883    #[case::ok(3*256+5, 12, 3*256+5)]
884    #[case::ok(3*256+5, 9, 1*256+5)]
885    fn serialize_and_deserialize_u16_single(#[case] val_in: u16, #[case] bitsize: u64, #[case] val_out: u16) {
886        let val_in_vec = val_in.to_le_bytes().clone();
887
888        let mut ser = Biseri::new();
889
890        let mut total_size = bitsize;
891        val_in_vec.clone().iter().for_each(|x| {
892            total_size = ser.add_data_base_u8(&x, bitsize);
893        });
894        ser.finish_add_data();
895
896        println!("ser.cache: {:?}", ser.data_cache);
897
898        assert_eq!(ser.data_cache.len(), 2);
899
900        let mut des = Bides::from_biseri(&ser);
901
902        assert_eq!(des.data_cache, ser.data_cache);
903
904        let mut dd = Vec::new();
905        let mut total_size = bitsize;
906        while total_size > 0 {
907            let ddd;
908            let r = des.decode_data_base_u8(total_size);
909            assert!(r.is_some());
910            (ddd, total_size) = r.unwrap();
911            dd.push(ddd);
912        };
913
914        let ddv = u16::from_le_bytes(dd.clone().try_into().unwrap());
915        println!("val_in: {val_in} ({val_in_vec:?}) vs. ddv: {ddv:?} ({dd:?}) (expected: {val_out})");
916        assert_eq!(val_out, ddv);
917    }
918
919    fn add_two_u16_fixed(ser: &mut Biseri, bits: u64) -> BiserSizes {
920        let d: u16 = 3;
921
922        ser.add_data(&d.to_le_bytes().to_vec(), bits);
923        ser.add_data(&d.to_le_bytes().to_vec(), bits);
924        ser.finish_add_data().unwrap()
925    }
926    #[rstest]
927    fn serialize_u16_fixed_full() {
928        let mut ser = Biseri::new();
929
930        let r = add_two_u16_fixed(&mut ser, 16);
931        let (lbits, lbytes) = (r.total_bits, r.total_bytes);
932
933        assert_eq!(ser.data_cache.len(), 4);
934        assert_eq!(lbytes, 4);
935        assert_eq!(lbits, 2 * 16);
936
937        assert_eq!(ser.data_cache[0], 3);
938        assert_eq!(ser.data_cache[1], 0);
939        assert_eq!(ser.data_cache[2], 3);
940        assert_eq!(ser.data_cache[3], 0);
941    }
942
943    #[rstest]
944    fn serialize_u16_fixed_12b() {
945        let mut ser = Biseri::new();
946
947        let r = add_two_u16_fixed(&mut ser, 12);
948        let (lbits, lbytes) = (r.total_bits, r.total_bytes);
949
950        assert_eq!(ser.data_cache.len(), 3);
951        assert_eq!(lbytes, 3);
952        assert_eq!(lbits, 2 * 12);
953
954        assert_eq!(ser.data_cache[0], 3);
955        assert_eq!(ser.data_cache[1], 3 << 4);
956        assert_eq!(ser.data_cache[2], 0);
957    }
958
959    #[rstest]
960    #[case::bitsize_16(16)]
961    #[case::bitsize_14(14)]
962    #[case::bitsize_12(12)]
963    fn ser_and_deserialize_u16_fixed(#[case] bits: u64) {
964        let mut ser = Biseri::new();
965
966        let _ = add_two_u16_fixed(&mut ser, bits);
967
968        let mut des = Bides::from_biseri(&ser);
969
970        assert_eq!(des.data_cache, ser.data_cache);
971
972        let d1 = des.decode_data(bits, 2);
973        assert!(d1.is_some());
974        let d2 = des.decode_data(bits, 2);
975        assert!(d2.is_some());
976
977        let d1 = d1.unwrap();
978        let d2 = d2.unwrap();
979
980        assert_eq!(d1[0], 3);
981        assert_eq!(d1[1], 0);
982        assert_eq!(d2[0], 3);
983        assert_eq!(d2[1], 0);
984    }
985
986    #[rstest]
987    fn ser_and_deserialize_i16_fixed() {
988        let mut ser = Biseri::new();
989
990        let v: i8 = -11;
991        v.bit_serialize(5, &mut ser);
992
993        let r = ser.finish_add_data().unwrap();
994        let (bits, bytes) = (r.total_bits, r.total_bytes);
995
996        println!("bits: {}, bytes: {}", bits, bytes);
997
998        let mut des = Bides::from_biseri(&ser);
999
1000        let vv = i8::bit_deserialize(1,5, &mut des);
1001        println!("v: {}, vv: {:?}", v, vv);
1002
1003        assert!(vv.is_some());
1004
1005        let vv = vv.unwrap();
1006        println!("bits_des: {}", vv.1);
1007        assert_eq!(v, vv.0);
1008    }
1009
1010    #[rstest]
1011    fn de_and_serialize_various_unsigned() {
1012        // ***********************************************************
1013        let mut ser = Biseri::new();
1014        let v1: u8 = 5;
1015        v1.bit_serialize(6, &mut ser);
1016        // ser.add_data_u8(&v1, 6);
1017        let v2: u16 = 15;
1018        v2.bit_serialize(14, &mut ser);
1019        // ser.add_data_u16(&v2, 14);
1020        let v3: u32 = 55;
1021        v3.bit_serialize(22, &mut ser);
1022        // ser.add_data_u32(&v3, 30);
1023        let r = ser.finish_add_data().unwrap();
1024        let (bits, bytes) = (r.total_bits, r.total_bytes);
1025
1026        println!("bits: {}, bytes: {}", bits, bytes);
1027
1028        // // ***********************************************************
1029        let mut des = Bides::from_biseri(&ser);
1030        let vo1 = u8::bit_deserialize(1,6, &mut des);
1031        // let vo1 = des.decode_data_u8(6);
1032        let vo2 = u16::bit_deserialize(1,14, &mut des);
1033        // let vo2 = des.decode_data_u16(14);
1034        let vo3 = u32::bit_deserialize(1,22, &mut des);
1035        // let vo3 = des.decode_data_u32(30);
1036
1037        println!("v1: {}, v2: {}, v3: {} vs vo1: {:?}, vo2: {:?}, vo3: {:?}", v1, v2, v3, vo1, vo2, vo3);
1038
1039        // ***********************************************************
1040        assert!(vo1.is_some());
1041        assert_eq!(v1, vo1.unwrap().0);
1042
1043        assert!(vo2.is_some());
1044        assert_eq!(v2, vo2.unwrap().0);
1045
1046        assert!(vo3.is_some());
1047        assert_eq!(v3, vo3.unwrap().0);
1048    }
1049
1050    #[rstest]
1051    fn de_and_serialize_various_float() {
1052        // ***********************************************************
1053        let mut ser = Biseri::new();
1054        let v1: f32 = 56.78;
1055        v1.bit_serialize(&mut ser);
1056        // ser.add_data_f32(&v1);
1057        let v2: u8 = 5;
1058        v2.bit_serialize(5, &mut ser);
1059        // ser.add_data_u8(&v2, 5);
1060        let v3: bool = true;
1061        v3.bit_serialize(&mut ser);
1062        // ser.add_data_bool(&v3);
1063        let v4: bool = false;
1064        v4.bit_serialize(&mut ser);
1065        // ser.add_data_bool(&v4);
1066        v1.bit_serialize(&mut ser);
1067        // ser.add_data_f32(&v1);
1068        let r = ser.finish_add_data().unwrap();
1069        let (bits, bytes) = (r.total_bits, r.total_bytes);
1070
1071        println!("bits: {}, bytes: {}", bits, bytes);
1072
1073        // ***********************************************************
1074        let mut des = Bides::from_biseri(&ser);
1075        let vo1 = f32::bit_deserialize(1, &mut des);
1076        let vo2 = u8::bit_deserialize(1,5, &mut des);
1077        let vo3 = bool::bit_deserialize(1,&mut des);
1078        let vo4 = bool::bit_deserialize(1,&mut des);
1079        let vo5 = f32::bit_deserialize(1,&mut des);
1080        // let vo1 = des.decode_data_f32();
1081        // let vo2 = des.decode_data_u8(5);
1082        // let vo3 = des.decode_data_bool();
1083        // let vo4 = des.decode_data_bool();
1084        // let vo5 = des.decode_data_f32();
1085
1086        println!("vo1: {:?}, vo2: {:?}, vo3: {:?}, vo4: {:?}, vo4: {:?}", vo1, vo2, vo3, vo4, vo5);
1087
1088        // ***********************************************************
1089        assert!(vo1.is_some());
1090        assert_eq!(v1, vo1.unwrap().0);
1091
1092        assert!(vo2.is_some());
1093        assert_eq!(v2, vo2.unwrap().0);
1094
1095        assert!(vo3.is_some());
1096        assert_eq!(v3, vo3.unwrap().0);
1097
1098        assert!(vo4.is_some());
1099        assert_eq!(v4, vo4.unwrap().0);
1100
1101        assert!(vo5.is_some());
1102        assert_eq!(v1, vo5.unwrap().0);
1103    }
1104
1105    #[rstest]
1106    fn serialize_and_deserialize_array_uint() {
1107        let mut ser = Biseri::new();
1108
1109        let v: FixedArray<IntWithGivenBitSize<u16, 5>, 4> = [11.into(), 12.into(), 22.into(), 23.into()].into();
1110        v.bit_serialize(&mut ser);
1111        let r = ser.finish_add_data().unwrap();
1112        let (bits, bytes) = (r.total_bits, r.total_bytes);
1113
1114        println!("bits: {}, bytes: {}", bits, bytes);
1115
1116        let mut des = Bides::from_biseri(&ser);
1117        let vv = FixedArray::<IntWithGivenBitSize<u16, 5>, 4>::bit_deserialize(1, &mut des);
1118
1119        assert!(vv.is_some());
1120        let vv = vv.unwrap().0;
1121
1122        assert_eq!(v.val[0], vv.val[0]);
1123        assert_eq!(v.val[1], vv.val[1]);
1124        assert_eq!(v.val[2], vv.val[2]);
1125        assert_eq!(v.val[3], vv.val[3]);
1126    }
1127
1128    #[rstest]
1129    fn serialize_and_deserialize_array_bool() {
1130        let mut ser = Biseri::new();
1131
1132        let v= FixedArray::from([true, true, false, true]);
1133        v.bit_serialize(&mut ser);
1134        let r = ser.finish_add_data().unwrap();
1135        let (bits, bytes) = (r.total_bits, r.total_bytes);
1136        println!("bits: {}, bytes: {}", bits, bytes);
1137
1138        let mut des = Bides::from_biseri(&ser);
1139        let vv = FixedArray::<bool, 4>::bit_deserialize(1,&mut des);
1140
1141        assert!(vv.is_some());
1142        let vv = vv.unwrap().0;
1143
1144        assert_eq!(v.val[0], vv.val[0]);
1145        assert_eq!(v.val[1], vv.val[1]);
1146        assert_eq!(v.val[2], vv.val[2]);
1147        assert_eq!(v.val[3], vv.val[3]);
1148    }
1149    #[rstest]
1150    fn serialize_and_deserialize_array_f64() {
1151        let mut ser = Biseri::new();
1152
1153        let v = FixedArray::from([1.1, 1.2, 22.34, 123456.78]);
1154        v.bit_serialize(&mut ser);
1155        let r = ser.finish_add_data().unwrap();
1156        let (bits, bytes) = (r.total_bits, r.total_bytes);
1157        println!("bits: {}, bytes: {}", bits, bytes);
1158
1159        let mut des = Bides::from_biseri(&ser);
1160        let vv = FixedArray::<f64, 4>::bit_deserialize(1,&mut des);
1161
1162        assert!(vv.is_some());
1163        let vv = vv.unwrap().0;
1164
1165        assert_eq!(v.val[0], vv.val[0]);
1166        assert_eq!(v.val[1], vv.val[1]);
1167        assert_eq!(v.val[2], vv.val[2]);
1168        assert_eq!(v.val[3], vv.val[3]);
1169    }
1170
1171    #[rstest]
1172    #[case::val_0(0, 1, 1)]
1173    #[case::val_1(1, 5, 1)]
1174    #[case::val_10(10, 9, 2)]
1175    fn serialize_dyn_int_u32_3(#[case] val: u32, #[case] ex_bits: u64, #[case] ex_bytes: u64) {
1176        // #[test]
1177        // fn serialize_dyn_int_u32_3() {
1178        //     let val: u32 = 10;
1179        //     let ex_bits: u64 = 9;
1180        //     let ex_bytes: u64 = 2;
1181
1182        let mut ser = Biseri::new();
1183
1184        let v = DynInteger::<u32, 32, 3>::new(val);
1185        v.bit_serialize(&mut ser);
1186        let r = ser.finish_add_data().unwrap();
1187        let (bits, bytes) = (r.total_bits, r.total_bytes);
1188        println!("bits: {}, bytes: {}", bits, bytes);
1189
1190        assert_eq!(bits, ex_bits);
1191        assert_eq!(bytes, ex_bytes);
1192    }
1193
1194    #[rstest]
1195    #[case::val_0(0, 2, 1)]
1196    #[case::val_1(1, 6, 1)]
1197    #[case::val_10(10, 10, 2)]
1198    fn serialize_dyn_int_i32_3(#[case] val: i32, #[case] ex_bits: u64, #[case] ex_bytes: u64) {
1199        // #[test]
1200        // fn serialize_dyn_int_i32_3() {
1201        //     let val: i32 = -1;
1202        //     let ex_bits: u64 = 6;
1203        //     let ex_bytes: u64 = 1;
1204
1205        let mut ser = Biseri::new();
1206
1207        let v = DynInteger::<i32, 32, 3>::new(val);
1208        v.bit_serialize(&mut ser);
1209        let r = ser.finish_add_data().unwrap();
1210        let (bits, bytes) = (r.total_bits, r.total_bytes);
1211        println!("bits: {}, bytes: {}", bits, bytes);
1212
1213        assert_eq!(bits, ex_bits);
1214        assert_eq!(bytes, ex_bytes);
1215    }
1216
1217    #[rstest]
1218    #[case::val_0(0)]
1219    #[case::val_1(1)]
1220    #[case::val_10(10)]
1221    #[case::val_m1(-1)]
1222    #[case::val_m1111(-1111)]
1223    fn ser_and_deserialize_dyn_int_i32_3(#[case] val: i32) {
1224        // #[test]
1225        // fn ser_and_deserialize_dyn_int_i32_3() {
1226        //     let val: i32 = -111;
1227
1228        let mut ser = Biseri::new();
1229
1230        let v = DynInteger::<i32, 32, 3>::new(val);
1231        v.bit_serialize(&mut ser);
1232        let r = ser.finish_add_data().unwrap();
1233        let (bits, bytes) = (r.total_bits, r.total_bytes);
1234        println!("bits: {}, bytes: {}", bits, bytes);
1235
1236        let mut der = Bides::from_biseri(&ser);
1237
1238        let dv = DynInteger::<i32, 32, 3>::bit_deserialize(1, &mut der);
1239        assert!(dv.is_some());
1240
1241        let dv = dv.unwrap();
1242        assert_eq!(val, dv.0.val);
1243    }
1244
1245    #[rstest]
1246    fn ser_and_deserialize_fixed_int() {
1247        let mut ser = Biseri::new();
1248
1249        let v = IntWithGivenBitSize::<u32, 20>::new(1111);
1250        v.bit_serialize(&mut ser);
1251
1252        let r = ser.finish_add_data().unwrap();
1253        let (bits, bytes) = (r.total_bits, r.total_bytes);
1254        println!("bits: {}, bytes: {}", bits, bytes);
1255
1256        let mut der = Bides::from_biseri(&ser);
1257        let vv = IntWithGivenBitSize::<u32, 20>::bit_deserialize(1, &mut der);
1258
1259        println!("v: {:?}, vv: {:?}", v, vv);
1260        assert!(vv.is_some());
1261        let vv = vv.unwrap().0;
1262
1263        assert_eq!(v.val, vv.val);
1264    }
1265
1266    #[rstest]
1267    fn ser_and_deserialize_fixed_int_not_enough_data() {
1268        let mut ser = Biseri::new();
1269
1270        let v = IntWithGivenBitSize::<u32, 20>::new(1111);
1271        v.bit_serialize(&mut ser);
1272
1273        let r = ser.finish_add_data().unwrap();
1274        let (bits, bytes) = (r.total_bits, r.total_bytes);
1275        println!("bits: {}, bytes: {}", bits, bytes);
1276
1277        let mut der = Bides::from_biseri(&ser);
1278        der.data_cache.truncate(1);
1279        let vv = IntWithGivenBitSize::<u32, 20>::bit_deserialize(1, &mut der);
1280
1281        println!("v: {:?}, vv: {:?}", v, vv);
1282        assert!(vv.is_none());
1283    }
1284
1285    #[rstest]
1286    fn ser_and_deserialize_fixed_precision_1() {
1287        let mut ser = Biseri::new();
1288
1289        let v = FixPrecisionMinMax::<20, -50, 50>::new(12.3456);
1290        v.bit_serialize(&mut ser);
1291
1292        let r = ser.finish_add_data().unwrap();
1293        let (bits, bytes) = (r.total_bits, r.total_bytes);
1294        println!("bits: {}, bytes: {}", bits, bytes);
1295
1296        let mut der = Bides::from_biseri(&ser);
1297        let vv = FixPrecisionMinMax::<20, -50, 50>::bit_deserialize(1, &mut der);
1298
1299        println!("v: {:?}, vv: {:?}", v, vv);
1300        assert!(vv.is_some());
1301        let vv = vv.unwrap().0;
1302
1303        let eps = 1e-1;
1304        match v.val {
1305            FixPrecisionVal::Value(fpv) => {
1306                match vv.val {
1307                    FixPrecisionVal::Value(fpvv) => assert!((fpv - fpvv).abs() < eps),
1308                    _ => assert!(false)
1309                }
1310            },
1311            _ => assert!(false)
1312        }
1313    }
1314    #[rstest]
1315    fn ser_and_deserialize_fixed_precision_2() {
1316        let mut ser = Biseri::new();
1317
1318        let v = FixPrecisionMinMax::<20, -50, 50>::new(-12.3456);
1319        v.bit_serialize(&mut ser);
1320
1321        let r = ser.finish_add_data().unwrap();
1322        let (bits, bytes) = (r.total_bits, r.total_bytes);
1323        println!("bits: {}, bytes: {}", bits, bytes);
1324
1325        let mut der = Bides::from_biseri(&ser);
1326        let vv = FixPrecisionMinMax::<20, -50, 50>::bit_deserialize(1, &mut der);
1327
1328        println!("v: {:?}, vv: {:?}", v, vv);
1329        assert!(vv.is_some());
1330        let vv = vv.unwrap().0;
1331
1332        let eps = 1e-1;
1333        match v.val {
1334            FixPrecisionVal::Value(fpv) => {
1335                match vv.val {
1336                    FixPrecisionVal::Value(fpvv) => assert!((fpv - fpvv).abs() < eps),
1337                    _ => assert!(false)
1338                }
1339            },
1340            _ => assert!(false)
1341        }
1342    }
1343    #[rstest]
1344    fn ser_and_deserialize_fixed_precision_under() {
1345        let mut ser = Biseri::new();
1346
1347        let v = FixPrecisionMinMax::<10, -50, 50>::new(-60.0);
1348        v.bit_serialize(&mut ser);
1349
1350        let r = ser.finish_add_data().unwrap();
1351        let (bits, bytes) = (r.total_bits, r.total_bytes);
1352        println!("bits: {}, bytes: {}", bits, bytes);
1353
1354        let mut der = Bides::from_biseri(&ser);
1355        let vv = FixPrecisionMinMax::<10, -50, 50>::bit_deserialize(1, &mut der);
1356
1357        println!("v: {:?}, vv: {:?}", v, vv);
1358        assert!(vv.is_some());
1359        let vv = vv.unwrap().0;
1360
1361        match vv.val {
1362            FixPrecisionVal::Underflow => assert!(true),
1363            _ => assert!(false),
1364        }
1365    }
1366    #[rstest]
1367    fn ser_and_deserialize_fixed_precision_over() {
1368        let mut ser = Biseri::new();
1369
1370        let v = FixPrecisionMinMax::<10, -50, 50>::new(60.0);
1371        v.bit_serialize(&mut ser);
1372
1373        let r = ser.finish_add_data().unwrap();
1374        let (bits, bytes) = (r.total_bits, r.total_bytes);
1375        println!("bits: {}, bytes: {}", bits, bytes);
1376
1377        let mut der = Bides::from_biseri(&ser);
1378        let vv = FixPrecisionMinMax::<10, -50, 50>::bit_deserialize(1, &mut der);
1379
1380        println!("v: {:?}, vv: {:?}", v, vv);
1381        assert!(vv.is_some());
1382        let vv = vv.unwrap().0;
1383
1384        match vv.val {
1385            FixPrecisionVal::Overflow => assert!(true),
1386            _ => assert!(false)
1387        }
1388    }
1389
1390    #[rstest]
1391    fn ser_and_deserialize_fixed_precision_vals() {
1392        type ValT = FixPrecisionMinMax<3, 1, 2>;
1393
1394        {
1395            let v = ValT::new(1.);
1396            let vv = deserialize::<ValT>(&serialize(&v).0);
1397            println!("v: {:?}, vv: {:?}", v, vv);
1398            assert!(vv.is_some());
1399            let vv = vv.unwrap().0;
1400            assert!(v==vv);
1401        }
1402        {
1403            let v = ValT::new(1.2);
1404            let vv = deserialize::<ValT>(&serialize(&v).0);
1405            println!("v: {:?}, vv: {:?}", v, vv);
1406            assert!(vv.is_some());
1407            let vv = vv.unwrap().0;
1408            assert!(v==vv);
1409        }
1410        {
1411            let v = ValT::new(1.21);
1412            let vv = deserialize::<ValT>(&serialize(&v).0);
1413            println!("v: {:?}, vv: {:?}", v, vv);
1414            assert!(vv.is_some());
1415            let vv = vv.unwrap().0;
1416            assert!(v==vv);
1417        }
1418    }
1419}
1420