1use crate::error::BookError;
7use crate::types::StpPolicy;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub struct BookConfig {
12 pub max_orders: u32,
16 pub grid_len: u32,
19 pub tick_size: u64,
21 pub grid_start_tick: u64,
24 pub default_stp: StpPolicy,
27}
28
29impl BookConfig {
30 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 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 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 #[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}