use core::fmt::{self, Write};
use ethnum::U256;
use crate::FromF64Error;
use crate::ascii::{self, Dropped, Scratch};
use crate::consts::ONE_RAW;
use crate::round::{Round, decide};
const POW10_F64: [f64; 23] = [
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13,
1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22,
];
pub(crate) fn to_f64(negative: bool, magnitude: u128) -> f64 {
let value = to_f64_magnitude(magnitude);
if negative { -value } else { value }
}
fn to_f64_magnitude(magnitude: u128) -> f64 {
let (int, frac) = ascii::split(magnitude);
if frac == 0 {
return int as f64;
}
let mut frac = frac;
let mut digits = 19;
for (unit, n) in [(100_000_000, 8), (10_000, 4), (100, 2), (10, 1)] {
while frac.is_multiple_of(unit) {
frac /= unit;
digits -= n;
}
}
let whole = int.checked_mul(crate::consts::POW10[digits]);
if let Some(n) = whole.and_then(|w| w.checked_add(frac as u128))
&& n <= 1 << 53
{
return n as f64 / POW10_F64[digits];
}
let mut buf: Scratch = [0; 49];
let len = ascii::shortest(false, magnitude, &mut buf);
let text = core::str::from_utf8(&buf[..len]).expect("ASCII");
text.parse().expect("decimal text always parses as f64")
}
struct TextBuf {
buf: [u8; 80],
len: usize,
}
impl Write for TextBuf {
fn write_str(&mut self, s: &str) -> fmt::Result {
let end = self.len + s.len();
self
.buf
.get_mut(self.len..end)
.ok_or(fmt::Error)?
.copy_from_slice(s.as_bytes());
self.len = end;
Ok(())
}
}
pub(crate) fn from_f64(
x: f64,
step: u128,
mode: Round,
) -> Result<(bool, u128), FromF64Error> {
if !x.is_finite() {
return Err(FromF64Error::NotFinite);
}
let a = x.abs();
if a >= 1e20 {
return Err(FromF64Error::OutOfRange);
}
let negative = x < 0.0;
let (magnitude, dropped) = if a < 1e-20 {
let dropped = if a == 0.0 {
Dropped::Nothing
} else {
Dropped::BelowHalf
};
(0, dropped)
} else {
let mut text = TextBuf {
buf: [0; 80],
len: 0,
};
write!(text, "{a}").expect("fits in 80 bytes");
let text = &text.buf[..text.len];
if a >= 1e19 {
let whole = text.iter().fold(0u128, |n, &c| n * 10 + (c - b'0') as u128);
return round_whole_to_step(negative, whole, step, mode)
.map(|m| (negative, m))
.ok_or(FromF64Error::OutOfRange);
}
let parsed = ascii::parse(text, 0, text.len(), None)
.expect("plain decimal below 1e19");
(parsed.magnitude, parsed.dropped)
};
let magnitude = round_to_step(negative, magnitude, dropped, step, mode)
.ok_or(FromF64Error::OutOfRange)?;
Ok((negative, magnitude))
}
fn round_to_step(
negative: bool,
magnitude: u128,
dropped: Dropped,
step: u128,
mode: Round,
) -> Option<u128> {
let q = magnitude / step;
let r = magnitude % step;
let other = step - r;
let (above, at) = match dropped {
Dropped::Nothing => (r > other, r == other),
_ if r >= other => (true, false),
_ if other - r == 1 => (
matches!(dropped, Dropped::AboveHalf),
matches!(dropped, Dropped::Half),
),
_ => (false, false),
};
let inexact = r != 0 || !matches!(dropped, Dropped::Nothing);
let away = decide(mode, negative, q & 1 == 1, above, at, inexact);
q.checked_add(away as u128)?.checked_mul(step)
}
fn round_whole_to_step(
negative: bool,
whole: u128,
step: u128,
mode: Round,
) -> Option<u128> {
let stored = U256::from(whole) * U256::from(ONE_RAW);
let (q, r) = stored.div_rem(U256::from(step));
let (q_high, q) = q.into_words();
if q_high != 0 {
return None;
}
let (_, r) = r.into_words();
let other = step - r;
let away = decide(mode, negative, q & 1 == 1, r > other, r == other, r != 0);
q.checked_add(away as u128)?.checked_mul(step)
}