avro_boxing/
lib.rs

1use std::convert::TryFrom;
2
3use apache_avro::Decimal;
4use bigdecimal::BigDecimal;
5use bigdecimal::num_bigint::{BigInt};
6use bigdecimal::num_traits::FromBytes;
7
8pub fn to_bigdecimal(avro_d: Decimal) -> BigDecimal {
9    let bytes = <Vec<u8>>::try_from(avro_d).unwrap();
10
11    return BigDecimal::from(BigInt::from_be_bytes(&bytes));
12}
13
14#[cfg(test)]
15mod tests {
16    use bigdecimal::num_traits::{ToBytes};
17    use bigdecimal::num_bigint::{ToBigInt};
18    use super::*;
19
20    fn bigint_100() -> BigInt {
21        return 100.to_bigint().unwrap();
22    }
23    #[test]
24    fn test_decimal_from_int() {
25        let dec = BigDecimal::from(1);
26        println!("{}", dec);
27    }
28
29    #[test]
30    fn test_decimal_from_bigint() {
31        let dec = BigDecimal::from(bigint_100());
32        println!("{}", dec);
33    }
34
35    #[test]
36    fn test_decimal_from_bytes_from_ref_decimal() {
37        let input = bigint_100().to_be_bytes();
38        let d = Decimal::from(input.clone());
39
40        let output = <Vec<u8>>::try_from(&d).unwrap();
41        assert_eq!(output, input);
42    }
43
44    #[test]
45    fn test_decimal_from_bytes_from_owned_decimal() {
46        let input = bigint_100().to_be_bytes();
47        let d = Decimal::from(input.clone());
48
49        let output = <Vec<u8>>::try_from(d).unwrap();
50        assert_eq!(output, input.clone());
51    }
52
53    #[test]
54    fn test_avro2big() {
55        let avro_d = Decimal::from(bigint_100().to_be_bytes());
56        let bytes = <Vec<u8>>::try_from(avro_d).unwrap();
57
58
59        let big_decimal = BigDecimal::from(BigInt::from_be_bytes(&bytes));
60        assert_eq!(big_decimal.to_string(), "100");
61    }
62}