use std::str::FromStr as _;
use rust_decimal::{Decimal, RoundingStrategy};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RoundDirection {
TowardZero,
AwayFromZero,
NearestHalfEven,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Granularity {
#[serde(with = "rust_decimal::serde::str")]
step: Decimal,
direction: RoundDirection,
}
impl Granularity {
pub fn new(step: Decimal, direction: RoundDirection) -> Result<Self, QuantizeError> {
if step > Decimal::ZERO {
Ok(Self { step, direction })
} else {
Err(QuantizeError::InvalidStep(step))
}
}
#[must_use]
pub const fn step(&self) -> Decimal {
self.step
}
#[must_use]
pub const fn direction(&self) -> RoundDirection {
self.direction
}
}
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum QuantizeError {
#[error("non-finite planner value {0}")]
NonFinite(f64),
#[error("planner value {0} is outside the exact decimal range")]
OutOfRange(f64),
#[error("granularity step {0} must be positive")]
InvalidStep(Decimal),
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Quantized {
#[serde(with = "rust_decimal::serde::str")]
pub value: Decimal,
pub input: f64,
pub granularity: Granularity,
}
pub fn quantize(value: f64, granularity: Granularity) -> Result<Quantized, QuantizeError> {
if !value.is_finite() {
return Err(QuantizeError::NonFinite(value));
}
let exact = Decimal::from_str(&value.to_string())
.or_else(|_| Decimal::from_scientific(&format!("{value:e}")))
.map_err(|_| QuantizeError::OutOfRange(value))?;
let exact = if exact.is_zero() && value != 0.0 {
Decimal::new(if value < 0.0 { -1 } else { 1 }, 28)
} else {
exact
};
let steps = exact
.checked_div(granularity.step)
.ok_or(QuantizeError::OutOfRange(value))?;
let rounded = match granularity.direction {
RoundDirection::TowardZero => steps.trunc(),
RoundDirection::AwayFromZero => {
if steps == steps.trunc() {
steps
} else if steps.is_sign_negative() {
steps.floor()
} else {
steps.ceil()
}
}
RoundDirection::NearestHalfEven => {
steps.round_dp_with_strategy(0, RoundingStrategy::MidpointNearestEven)
}
};
let quantity = rounded
.checked_mul(granularity.step)
.ok_or(QuantizeError::OutOfRange(value))?
.normalize();
Ok(Quantized {
value: quantity,
input: value,
granularity,
})
}