use crate::{Error, Layout, Result};
use num_bigint::BigUint;
use num_integer::Integer;
use num_traits::{ToPrimitive, Zero};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GridRounding {
Exact,
Nearest,
}
struct Ratio {
numerator: BigUint,
denominator: BigUint,
fast: Option<(u128, u128)>,
}
fn decimal(value: f64) -> Result<(BigUint, i32)> {
if !value.is_finite() || value <= 0.0 {
return Err(Error::invalid("database unit must be positive and finite"));
}
let repr = format!("{value:e}");
let (digits, exponent) = repr.split_once('e').expect("scientific formatting");
let places = digits
.split_once('.')
.map_or(0, |(_, frac)| frac.len() as i32);
let digits = digits.replace('.', "");
Ok((
digits.parse().expect("decimal coefficient"),
exponent.parse::<i32>().expect("decimal exponent") - places,
))
}
impl Ratio {
fn for_grids(from: f64, to: f64) -> Result<Self> {
let (mut numerator, from_exp) = decimal(from)?;
let (mut denominator, to_exp) = decimal(to)?;
let shift = from_exp - to_exp;
let ten = BigUint::from(10_u32);
if shift > 0 {
numerator *= ten.pow(shift as u32);
} else if shift < 0 {
denominator *= ten.pow(shift.unsigned_abs());
}
let common = numerator.gcd(&denominator);
numerator /= &common;
denominator /= common;
let fast = numerator.to_u128().zip(denominator.to_u128());
Ok(Self {
numerator,
denominator,
fast,
})
}
fn apply(&self, value: u64, field: &str, rounding: GridRounding) -> Result<u64> {
let off_grid = || Error::invalid(format!("{field} is off the requested database grid"));
let overflow = || Error::invalid(format!("{field} exceeds the target coordinate range"));
if let Some((n, d)) = self.fast
&& let Some(product) = u128::from(value).checked_mul(n)
{
let rem = product % d;
if rounding == GridRounding::Exact && rem != 0 {
return Err(off_grid());
}
let up = rounding == GridRounding::Nearest && rem >= d - rem;
return u64::try_from(product / d + u128::from(up)).map_err(|_| overflow());
}
let (q, r) = (&self.numerator * value).div_rem(&self.denominator);
if rounding == GridRounding::Exact && !r.is_zero() {
return Err(off_grid());
}
let up = rounding == GridRounding::Nearest && (r << 1) >= self.denominator;
(q + u32::from(up)).to_u64().ok_or_else(overflow)
}
}
impl Layout {
pub fn reinterpret_dbu(&self, dbu_meters: f64) -> Result<Self> {
if !dbu_meters.is_finite() || dbu_meters <= 0.0 {
return Err(Error::invalid("database unit must be positive and finite"));
}
let mut copy = self.clone();
copy.dbu_meters = dbu_meters;
Ok(copy)
}
pub fn resample(&self, dbu_meters: f64, rounding: GridRounding) -> Result<Self> {
self.resample_selection(dbu_meters, rounding, false)
}
pub(crate) fn resample_selection(
&self,
dbu_meters: f64,
rounding: GridRounding,
allow_external: bool,
) -> Result<Self> {
let ratio = Ratio::for_grids(self.dbu_meters, dbu_meters)?;
if self.dbu_meters == dbu_meters {
return Ok(self.clone());
}
let signed = |v: i64, field: &str| {
let magnitude = i128::from(ratio.apply(v.unsigned_abs(), field, rounding)?);
i64::try_from(if v < 0 { -magnitude } else { magnitude })
.map_err(|_| Error::invalid(format!("{field} exceeds i64")))
};
self.map_grid_dimensions(dbu_meters, allow_external, signed, |v, field| {
ratio.apply(v, field, rounding)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rational_rounding_handles_extreme_grids_and_ints() {
let ratio = Ratio::for_grids(1e-9, 2e-9).unwrap();
assert_eq!(
ratio.apply(u64::MAX, "x", GridRounding::Nearest).unwrap(),
1 << 63
);
assert!(ratio.apply(1, "x", GridRounding::Exact).is_err());
assert_eq!(
Ratio::for_grids(1e-300, 1e200)
.unwrap()
.apply(1, "x", GridRounding::Nearest)
.unwrap(),
0
);
assert!(
Ratio::for_grids(1e200, 1e-300)
.unwrap()
.apply(1, "x", GridRounding::Nearest)
.is_err()
);
}
}