flexpool_core/
quantize.rs1use std::str::FromStr as _;
13
14use rust_decimal::{Decimal, RoundingStrategy};
15use serde::{Deserialize, Serialize};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
19#[serde(rename_all = "kebab-case")]
20pub enum RoundDirection {
21 TowardZero,
24 AwayFromZero,
26 NearestHalfEven,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
32pub struct Granularity {
33 #[serde(with = "rust_decimal::serde::str")]
34 step: Decimal,
35 direction: RoundDirection,
36}
37
38impl Granularity {
39 pub fn new(step: Decimal, direction: RoundDirection) -> Result<Self, QuantizeError> {
44 if step > Decimal::ZERO {
45 Ok(Self { step, direction })
46 } else {
47 Err(QuantizeError::InvalidStep(step))
48 }
49 }
50
51 #[must_use]
53 pub const fn step(&self) -> Decimal {
54 self.step
55 }
56
57 #[must_use]
59 pub const fn direction(&self) -> RoundDirection {
60 self.direction
61 }
62}
63
64#[derive(Debug, Clone, PartialEq, thiserror::Error)]
66pub enum QuantizeError {
67 #[error("non-finite planner value {0}")]
69 NonFinite(f64),
70 #[error("planner value {0} is outside the exact decimal range")]
72 OutOfRange(f64),
73 #[error("granularity step {0} must be positive")]
75 InvalidStep(Decimal),
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
80pub struct Quantized {
81 #[serde(with = "rust_decimal::serde::str")]
83 pub value: Decimal,
84 pub input: f64,
86 pub granularity: Granularity,
88}
89
90pub fn quantize(value: f64, granularity: Granularity) -> Result<Quantized, QuantizeError> {
95 if !value.is_finite() {
96 return Err(QuantizeError::NonFinite(value));
97 }
98 let exact = Decimal::from_str(&value.to_string())
101 .or_else(|_| Decimal::from_scientific(&format!("{value:e}")))
102 .map_err(|_| QuantizeError::OutOfRange(value))?;
103 let exact = if exact.is_zero() && value != 0.0 {
106 Decimal::new(if value < 0.0 { -1 } else { 1 }, 28)
107 } else {
108 exact
109 };
110 let steps = exact
111 .checked_div(granularity.step)
112 .ok_or(QuantizeError::OutOfRange(value))?;
113 let rounded = match granularity.direction {
114 RoundDirection::TowardZero => steps.trunc(),
115 RoundDirection::AwayFromZero => {
116 if steps == steps.trunc() {
117 steps
118 } else if steps.is_sign_negative() {
119 steps.floor()
120 } else {
121 steps.ceil()
122 }
123 }
124 RoundDirection::NearestHalfEven => {
125 steps.round_dp_with_strategy(0, RoundingStrategy::MidpointNearestEven)
126 }
127 };
128 let quantity = rounded
129 .checked_mul(granularity.step)
130 .ok_or(QuantizeError::OutOfRange(value))?
131 .normalize();
132 Ok(Quantized {
133 value: quantity,
134 input: value,
135 granularity,
136 })
137}