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