Skip to main content

chronicle_core/
config.rs

1//! Book configuration. Every capacity and the whole tick grid are fixed
2//! at construction (ARCHITECTURE.md section 3.2); nothing resizes later,
3//! which is what makes the zero steady-state allocation contract
4//! possible.
5
6use crate::error::BookError;
7use crate::types::StpPolicy;
8
9/// Static configuration for one [`crate::Book`].
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub struct BookConfig {
12    /// Arena capacity: the maximum number of simultaneously live orders.
13    /// At least 1 and at most 2^31 - 2, so slot indices can reserve
14    /// `u32::MAX` as NIL.
15    pub max_orders: u32,
16    /// Number of price ticks on the grid. A multiple of 64, at least 64,
17    /// at most 2^22.
18    pub grid_len: u32,
19    /// Quote units per tick, at least 1.
20    pub tick_size: u64,
21    /// Tick value of grid index 0. A price whose tick is `t` maps to grid
22    /// index `t - grid_start_tick`.
23    pub grid_start_tick: u64,
24    /// Self-trade prevention policy applied when a command does not name
25    /// one (executes from Milestone 2).
26    pub default_stp: StpPolicy,
27}
28
29impl BookConfig {
30    /// The tick value one past the last tick on the grid.
31    ///
32    /// # Errors
33    ///
34    /// Returns [`BookError::InvalidConfig`] if the grid end overflows
35    /// `u64` (the m9a construction bound, ARCHITECTURE.md section 3.2).
36    pub fn grid_end_tick(&self) -> Result<u64, BookError> {
37        self.grid_start_tick
38            .checked_add(u64::from(self.grid_len))
39            .ok_or(BookError::InvalidConfig {
40                field: "grid_start_tick + grid_len",
41                rule: "the grid end must fit in u64 (checked_add at construction)",
42            })
43    }
44
45    /// Validate every construction rule.
46    ///
47    /// # Errors
48    ///
49    /// Returns [`BookError::InvalidConfig`] naming the first field and
50    /// rule that fail.
51    pub fn validate(&self) -> Result<(), BookError> {
52        if self.max_orders == 0 || self.max_orders > (1 << 31) - 2 {
53            return Err(BookError::InvalidConfig {
54                field: "max_orders",
55                rule: "must be at least 1 and at most 2^31 - 2",
56            });
57        }
58        if self.grid_len < 64 || !self.grid_len.is_multiple_of(64) || self.grid_len > 1 << 22 {
59            return Err(BookError::InvalidConfig {
60                field: "grid_len",
61                rule: "must be a multiple of 64, at least 64, at most 2^22",
62            });
63        }
64        if self.tick_size == 0 {
65            return Err(BookError::InvalidConfig {
66                field: "tick_size",
67                rule: "must be at least 1",
68            });
69        }
70        let end = self.grid_end_tick()?;
71        // The largest raw price on the grid is (end - 1) * tick_size and
72        // must be representable, so price_of_tick can never overflow.
73        let highest_tick = end - 1;
74        if highest_tick.checked_mul(self.tick_size).is_none() {
75            return Err(BookError::InvalidConfig {
76                field: "grid end * tick_size",
77                rule: "the largest raw price on the grid must fit in u64",
78            });
79        }
80        Ok(())
81    }
82
83    /// Raw price (quote units) of an absolute tick value. Callers pass
84    /// only ticks inside the validated grid, so the multiplication
85    /// cannot overflow (see [`BookConfig::validate`]).
86    #[must_use]
87    pub(crate) const fn price_of_tick(&self, tick: u64) -> u64 {
88        tick * self.tick_size
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95
96    fn base() -> BookConfig {
97        BookConfig {
98            max_orders: 1024,
99            grid_len: 4096,
100            tick_size: 1,
101            grid_start_tick: 1,
102            default_stp: StpPolicy::CancelIncoming,
103        }
104    }
105
106    #[test]
107    fn valid_config_passes() {
108        assert!(base().validate().is_ok());
109    }
110
111    #[test]
112    fn grid_end_overflow_is_a_config_error() {
113        let mut cfg = base();
114        cfg.grid_start_tick = u64::MAX - 10;
115        cfg.grid_len = 64;
116        assert!(matches!(
117            cfg.validate(),
118            Err(BookError::InvalidConfig { .. })
119        ));
120    }
121
122    #[test]
123    fn grid_len_must_be_a_multiple_of_64() {
124        let mut cfg = base();
125        cfg.grid_len = 100;
126        assert!(matches!(
127            cfg.validate(),
128            Err(BookError::InvalidConfig { .. })
129        ));
130    }
131}