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