oddsidizer/
config.rs

1use rust_decimal::RoundingStrategy;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum FractionStrategy {
5    /// Plain method (less precise, but faster, f. ex. 1.33 gives 33/100 instead of 1/3).
6    ///
7    /// Note that using None method but leaving lookup enabled can still return simplified fractions (f. ex. 1.33 -> 1/3) from the lookup tables (see README.md)
8    Plain,
9    /// Use a continued fraction algorithm for better precision and simple fractions. (1.33 gives 1/3 instead of 33/100)
10    Simplify,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum LookupVariant {
15    /// No lookup
16    None,
17    /// Basic lookup for common values usually matching closely the original value
18    Basic,
19    /// Extended lookup - covers more values but also gives more rounded results, f. ex. 1.0013 -> 1/750 instead of 1/768
20    Extended,
21}
22
23/// Configuration for conversion functions.
24#[derive(Debug, Clone, Copy)]
25pub struct ConversionConfig {
26    /// Use lookup tables first for conversion, then fallback to regular computations
27    /// Note: When using lookup tables feature, conversion from 1.67 or -150 gives 4/6 instead of 2/3 (see README.md)
28    pub lookup_tables_variant: LookupVariant,
29    /// Fractions computing strategy
30    pub fraction_strategy: FractionStrategy,
31    /// Rounding method for Decimal type
32    pub rounding_strategy: RoundingStrategy,
33}
34
35impl Default for ConversionConfig {
36    /// Provides standard settings.
37    ///
38    /// - lookup enabled
39    /// - fractions simplified
40    /// - MidpointAwayFromZero (RoundHalfUp) rounding strategy
41    fn default() -> Self {
42        DEFAULT_CONVERSION_CONFIG
43    }
44}
45
46static DEFAULT_CONVERSION_CONFIG: ConversionConfig = ConversionConfig {
47    lookup_tables_variant: LookupVariant::Basic,
48    fraction_strategy: FractionStrategy::Simplify,
49    rounding_strategy: RoundingStrategy::MidpointAwayFromZero, // former RoundHalfUp
50};
51
52impl ConversionConfig {
53    pub fn no_lookup(mut self) -> Self {
54        self.lookup_tables_variant = LookupVariant::None;
55        self
56    }
57
58    pub fn extended_lookup(mut self) -> Self {
59        self.lookup_tables_variant = LookupVariant::Extended;
60        self
61    }
62
63    pub fn plain_fraction_strategy(mut self) -> Self {
64        self.fraction_strategy = FractionStrategy::Plain;
65        self
66    }
67
68    pub fn fraction_strategy(mut self, strategy: FractionStrategy) -> Self {
69        self.fraction_strategy = strategy;
70        self
71    }
72
73    pub fn rounding_strategy(mut self, strategy: RoundingStrategy) -> Self {
74        self.rounding_strategy = strategy;
75        self
76    }
77}