1use alloc::vec::Vec;
2
3use crate::profile::{validate_bignum_bytes, validate_int_safe_i64};
4use crate::CborError;
5
6#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct BigInt {
12 negative: bool,
13 magnitude: Vec<u8>,
14}
15
16impl BigInt {
17 pub fn new(negative: bool, magnitude: Vec<u8>) -> Result<Self, CborError> {
25 validate_bignum_bytes(negative, &magnitude).map_err(|code| CborError::new(code, 0))?;
26 Ok(Self {
27 negative,
28 magnitude,
29 })
30 }
31
32 #[inline]
34 #[must_use]
35 pub const fn is_negative(&self) -> bool {
36 self.negative
37 }
38
39 #[inline]
41 #[must_use]
42 pub fn magnitude(&self) -> &[u8] {
43 &self.magnitude
44 }
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct CborInteger(IntegerRepr);
50
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum IntegerRepr {
53 Safe(i64),
54 Big(BigInt),
55}
56
57impl CborInteger {
58 pub fn safe(value: i64) -> Result<Self, CborError> {
64 validate_int_safe_i64(value).map_err(|code| CborError::new(code, 0))?;
65 Ok(Self(IntegerRepr::Safe(value)))
66 }
67
68 pub fn big(negative: bool, magnitude: Vec<u8>) -> Result<Self, CborError> {
74 Ok(Self(IntegerRepr::Big(BigInt::new(negative, magnitude)?)))
75 }
76
77 #[inline]
79 #[must_use]
80 pub const fn from_bigint(big: BigInt) -> Self {
81 Self(IntegerRepr::Big(big))
82 }
83
84 #[inline]
86 #[must_use]
87 pub const fn is_safe(&self) -> bool {
88 matches!(self.0, IntegerRepr::Safe(_))
89 }
90
91 #[inline]
93 #[must_use]
94 pub const fn is_big(&self) -> bool {
95 matches!(self.0, IntegerRepr::Big(_))
96 }
97
98 #[inline]
100 #[must_use]
101 pub const fn as_i64(&self) -> Option<i64> {
102 match &self.0 {
103 IntegerRepr::Safe(v) => Some(*v),
104 IntegerRepr::Big(_) => None,
105 }
106 }
107
108 #[inline]
110 #[must_use]
111 pub const fn as_bigint(&self) -> Option<&BigInt> {
112 match &self.0 {
113 IntegerRepr::Big(b) => Some(b),
114 IntegerRepr::Safe(_) => None,
115 }
116 }
117}
118
119impl From<BigInt> for CborInteger {
120 fn from(value: BigInt) -> Self {
121 Self(IntegerRepr::Big(value))
122 }
123}