Skip to main content

deser_core/ext/bridges/
num_bigint.rs

1use ::num_bigint::BigUint;
2
3use crate::error::Error;
4use crate::event::Atom;
5use crate::ext::BigInt;
6use crate::ext::known::{Bridge, impl_bridge, out_of_range};
7
8super::num_bigint_conversions!(::num_bigint);
9
10impl Bridge for ::num_bigint::BigInt {
11    type Known = BigInt;
12
13    const EXPECTING: &'static str = "integer";
14
15    fn to_known(&self) -> Result<BigInt, Error> {
16        Ok(from_num(self))
17    }
18
19    fn from_known(value: BigInt) -> Result<::num_bigint::BigInt, Error> {
20        Ok(to_num(&value))
21    }
22
23    /// Integers that fit into 64 or 128 bits are serialized as such.
24    fn serialize_atom(&self) -> Result<Atom<'static>, Error> {
25        Ok(from_num(self).into_atom())
26    }
27}
28
29impl Bridge for BigUint {
30    type Known = BigInt;
31
32    const EXPECTING: &'static str = "unsigned integer";
33
34    fn to_known(&self) -> Result<BigInt, Error> {
35        Ok(BigInt {
36            negative: false,
37            magnitude: self.to_bytes_be(),
38        })
39    }
40
41    fn from_known(value: BigInt) -> Result<BigUint, Error> {
42        if value.is_negative() {
43            return Err(out_of_range("integer cannot be negative"));
44        }
45        Ok(BigUint::from_bytes_be(&value.magnitude))
46    }
47
48    fn serialize_atom(&self) -> Result<Atom<'static>, Error> {
49        Ok(self.to_known()?.into_atom())
50    }
51}
52
53impl_bridge!(::num_bigint::BigInt, BigUint);