assert significant is valid

This commit is contained in:
2025-07-18 21:19:30 +01:00
parent cd6f9486f7
commit 27f745ee6d

View File

@@ -23,14 +23,35 @@ impl Display for DecimalError {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Decimal<const SIZE: usize = 5, EXP = u16> {
pub minus: bool,
pub significant: [u8; SIZE],
pub minus_exponent: bool,
pub exponent: EXP,
minus: bool,
significant: [u8; SIZE],
minus_exponent: bool,
exponent: EXP,
}
impl<const SIZE: usize, EXP: PrimInt + Unsigned> Decimal<SIZE, EXP> {
pub fn from_float<F: FloatCore>(mut f: F) -> Result<Decimal<SIZE, EXP>, DecimalError> {
pub fn new(minus: bool, significant: [u8; SIZE], minus_exponent: bool, exponent: EXP) -> Self {
for s in significant {
assert!(s < 10, "bad significant");
}
Decimal {
minus,
significant,
minus_exponent,
exponent,
}
}
pub fn into_parts(self) -> (bool, [u8; SIZE], bool, EXP) {
(
self.minus,
self.significant,
self.minus_exponent,
self.exponent,
)
}
pub fn from_float<F: FloatCore>(mut f: F) -> Result<Self, DecimalError> {
if !f.is_finite() {
return Err(DecimalError::NotANumber);
}
@@ -57,10 +78,12 @@ impl<const SIZE: usize, EXP: PrimInt + Unsigned> Decimal<SIZE, EXP> {
}
let mut significant = [0; SIZE];
for i in 0..SIZE {
let s = f.trunc().to_u8().unwrap();
let mut s = f.trunc().to_u8().unwrap();
if s >= 10 {
s = 9;
}
f = f * F::from(10).unwrap();
f = f - F::from(s * 10).ok_or(DecimalError::ExponentOverflow)?;
debug_assert!(s < 10);
significant[i] = s;
}
Ok(Decimal {