use crate::decode::Decoder;
use crate::encode::Encoder;
use crate::error::Error;
use crate::head::Major;
pub const TAG_UNSIGNED: u64 = 2;
pub const TAG_NEGATIVE: u64 = 3;
#[must_use]
pub fn normalized(magnitude_be: &[u8]) -> &[u8] {
let first = magnitude_be.iter().position(|&b| b != 0);
match first {
Some(i) => &magnitude_be[i..],
None => &[],
}
}
impl Encoder<'_> {
pub fn bignum_uint(&mut self, magnitude_be: &[u8]) -> Result<&mut Self, Error> {
self.bignum(TAG_UNSIGNED, magnitude_be)
}
pub fn bignum_nint(&mut self, magnitude_be: &[u8]) -> Result<&mut Self, Error> {
self.bignum(TAG_NEGATIVE, magnitude_be)
}
fn bignum(&mut self, tag: u64, magnitude_be: &[u8]) -> Result<&mut Self, Error> {
self.tag(tag)?;
let magnitude = normalized(magnitude_be);
let start = crate::head::head_len(tag);
if self.bytes(magnitude).is_err() {
self.pos -= start;
return Err(Error::OUT_OF_SPACE);
}
Ok(self)
}
}
impl<'a> Decoder<'a> {
pub fn bignum_unsigned(&mut self) -> Result<&'a [u8], Error> {
self.bignum_magnitude(TAG_UNSIGNED)
}
pub fn bignum_nint(&mut self) -> Result<&'a [u8], Error> {
self.bignum_magnitude(TAG_NEGATIVE)
}
fn bignum_magnitude(&mut self, want: u64) -> Result<&'a [u8], Error> {
let tag = self.tag()?;
match tag == want {
true => {}
false => return Err(Error::TYPE_MISMATCH),
}
self.bytes_of(Major::Bytes)
}
pub fn bignum_u64(&mut self) -> Result<u64, Error> {
let mag = self.bignum_unsigned()?;
be_to_u64(mag).ok_or(Error::INTEGER_OUT_OF_RANGE)
}
pub fn bignum_i128(&mut self) -> Result<i128, Error> {
const MAX_MAGNITUDE_BITS: usize = 127;
let tag = self.tag()?;
let mag = self.bytes_of(Major::Bytes)?;
let Some(&first) = normalized(mag).first() else {
return Ok(match tag {
TAG_UNSIGNED => 0,
_ => -1,
});
};
let bits = (mag.len() - 1) * 8 + (8 - first.leading_zeros() as usize);
if bits > MAX_MAGNITUDE_BITS {
return Err(Error::INTEGER_OUT_OF_RANGE);
}
let mut n: u128 = 0;
for &b in mag {
n = (n << 8) | u128::from(b);
}
match tag {
TAG_UNSIGNED => Ok(n as i128),
_ => Ok(-1 - n as i128),
}
}
}
fn be_to_u64(bytes: &[u8]) -> Option<u64> {
let trimmed = normalized(bytes);
match trimmed.len() {
0 => Some(0),
n @ 1..=8 => {
let mut v: u64 = 0;
for &b in bytes.iter().rev().take(n) {
v = (v << 8) | u64::from(b);
}
Some(v)
}
_ => None,
}
}