assert significant is valid
This commit is contained in:
37
src/lib.rs
37
src/lib.rs
@@ -23,14 +23,35 @@ impl Display for DecimalError {
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub struct Decimal<const SIZE: usize = 5, EXP = u16> {
|
pub struct Decimal<const SIZE: usize = 5, EXP = u16> {
|
||||||
pub minus: bool,
|
minus: bool,
|
||||||
pub significant: [u8; SIZE],
|
significant: [u8; SIZE],
|
||||||
pub minus_exponent: bool,
|
minus_exponent: bool,
|
||||||
pub exponent: EXP,
|
exponent: EXP,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<const SIZE: usize, EXP: PrimInt + Unsigned> Decimal<SIZE, 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() {
|
if !f.is_finite() {
|
||||||
return Err(DecimalError::NotANumber);
|
return Err(DecimalError::NotANumber);
|
||||||
}
|
}
|
||||||
@@ -57,10 +78,12 @@ impl<const SIZE: usize, EXP: PrimInt + Unsigned> Decimal<SIZE, EXP> {
|
|||||||
}
|
}
|
||||||
let mut significant = [0; SIZE];
|
let mut significant = [0; SIZE];
|
||||||
for i in 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(10).unwrap();
|
||||||
f = f - F::from(s * 10).ok_or(DecimalError::ExponentOverflow)?;
|
f = f - F::from(s * 10).ok_or(DecimalError::ExponentOverflow)?;
|
||||||
debug_assert!(s < 10);
|
|
||||||
significant[i] = s;
|
significant[i] = s;
|
||||||
}
|
}
|
||||||
Ok(Decimal {
|
Ok(Decimal {
|
||||||
|
|||||||
Reference in New Issue
Block a user