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