quant_primitives/
fraction.rs1use std::fmt;
10
11use rust_decimal::Decimal;
12use serde::{Deserialize, Serialize};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
19pub struct Fraction(pub(crate) Decimal);
20
21#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
23pub enum FractionError {
24 #[error("fraction {0} out of range [0, 1]")]
26 OutOfRange(Decimal),
27}
28
29impl Fraction {
30 pub fn new(value: Decimal) -> Result<Self, FractionError> {
32 if value < Decimal::ZERO || value > Decimal::ONE {
33 return Err(FractionError::OutOfRange(value));
34 }
35 Ok(Self(value))
36 }
37
38 pub fn value(&self) -> Decimal {
40 self.0
41 }
42
43 pub fn zero() -> Self {
45 Self(Decimal::ZERO)
46 }
47
48 pub fn one() -> Self {
50 Self(Decimal::ONE)
51 }
52}
53
54impl fmt::Display for Fraction {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 write!(f, "{}", self.0.normalize())
57 }
58}
59
60#[cfg(test)]
61#[path = "fraction_tests.rs"]
62mod tests;