decstr/bitstring/
arbitrary.rs

1use crate::{
2    binary::{
3        ArbitrarySizedBinaryBuf,
4        BinaryBuf,
5    },
6    text::VecTextBuf,
7    Error,
8    OverflowError,
9};
10
11/**
12An arbitrary precision decimal number.
13
14This type is only available when the `arbitrary-precision` feature is enabled.
15*/
16pub struct BigBitstring(ArbitrarySizedBinaryBuf);
17
18impl BigBitstring {
19    /**
20    Try create a decimal from the given buffer.
21
22    The buffer is assumed to be in little-endian byte-order already.
23    This method will fail if the buffer length is not a multiple of 4 bytes.
24    */
25    pub fn try_from_le_bytes(bytes: &[u8]) -> Result<Self, Error> {
26        if bytes.len() == 0 || bytes.len() % 4 != 0 {
27            Err(OverflowError::exact_size_mismatch(
28                bytes.len(),
29                bytes.len() + 4 - (bytes.len() % 4),
30                "decimals must be a multiple of 32 bits (4 bytes)",
31            ))?;
32        }
33
34        let mut buf = ArbitrarySizedBinaryBuf::try_with_exactly_storage_width_bytes(bytes.len())?;
35
36        buf.bytes_mut().copy_from_slice(bytes);
37
38        Ok(Self(buf))
39    }
40
41    /**
42    Get a reference to the underlying bitstring buffer.
43
44    This buffer is always stored in little-endian byte-order, regardless of the endianness
45    of the platform.
46    */
47    pub fn as_le_bytes(&self) -> &[u8] {
48        // Even on big-endian platforms we always encode numbers in little-endian order
49        self.0.bytes()
50    }
51
52    /**
53    Create a decimal with the finite value zero.
54    */
55    pub fn zero() -> Self {
56        Self::from(0u8)
57    }
58
59    #[cfg(test)]
60    fn max() -> Option<Self> {
61        None
62    }
63
64    #[cfg(test)]
65    fn min() -> Option<Self> {
66        None
67    }
68}
69
70classify!(BigBitstring);
71
72try_s2d!(VecTextBuf => BigBitstring);
73d2s!(BigBitstring);
74
75f2d!(f32 => from_f32 => BigBitstring);
76f2d!(f64 => from_f64 => BigBitstring);
77
78try_d2f!(BigBitstring => to_f32 => f32);
79try_d2f!(BigBitstring => to_f64 => f64);
80
81i2d!(i8 => from_i8 => BigBitstring);
82i2d!(i16 => from_i16 => BigBitstring);
83i2d!(i32 => from_i32 => BigBitstring);
84i2d!(i64 => from_i64 => BigBitstring);
85i2d!(i128 => from_i128 => BigBitstring);
86
87try_d2i!(BigBitstring => to_i8 => i8);
88try_d2i!(BigBitstring => to_i16 => i16);
89try_d2i!(BigBitstring => to_i32 => i32);
90try_d2i!(BigBitstring => to_i64 => i64);
91try_d2i!(BigBitstring => to_i128 => i128);
92
93i2d!(u8 => from_u8 => BigBitstring);
94i2d!(u16 => from_u16 => BigBitstring);
95i2d!(u32 => from_u32 => BigBitstring);
96i2d!(u64 => from_u64 => BigBitstring);
97i2d!(u128 => from_u128 => BigBitstring);
98
99try_d2i!(BigBitstring => to_u8 => u8);
100try_d2i!(BigBitstring => to_u16 => u16);
101try_d2i!(BigBitstring => to_u32 => u32);
102try_d2i!(BigBitstring => to_u64 => u64);
103try_d2i!(BigBitstring => to_u128 => u128);