use crate::error::BookError;
use crate::types::StpPolicy;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BookConfig {
pub max_orders: u32,
pub grid_len: u32,
pub tick_size: u64,
pub grid_start_tick: u64,
pub default_stp: StpPolicy,
}
impl BookConfig {
pub fn grid_end_tick(&self) -> Result<u64, BookError> {
self.grid_start_tick
.checked_add(u64::from(self.grid_len))
.ok_or(BookError::InvalidConfig {
field: "grid_start_tick + grid_len",
rule: "the grid end must fit in u64 (checked_add at construction)",
})
}
pub fn validate(&self) -> Result<(), BookError> {
if self.max_orders == 0 || self.max_orders > (1 << 31) - 2 {
return Err(BookError::InvalidConfig {
field: "max_orders",
rule: "must be at least 1 and at most 2^31 - 2",
});
}
if self.grid_len < 64 || !self.grid_len.is_multiple_of(64) || self.grid_len > 1 << 22 {
return Err(BookError::InvalidConfig {
field: "grid_len",
rule: "must be a multiple of 64, at least 64, at most 2^22",
});
}
if self.tick_size == 0 {
return Err(BookError::InvalidConfig {
field: "tick_size",
rule: "must be at least 1",
});
}
let end = self.grid_end_tick()?;
let highest_tick = end - 1;
if highest_tick.checked_mul(self.tick_size).is_none() {
return Err(BookError::InvalidConfig {
field: "grid end * tick_size",
rule: "the largest raw price on the grid must fit in u64",
});
}
Ok(())
}
#[must_use]
pub(crate) const fn price_of_tick(&self, tick: u64) -> u64 {
tick * self.tick_size
}
}
#[cfg(test)]
mod tests {
use super::*;
fn base() -> BookConfig {
BookConfig {
max_orders: 1024,
grid_len: 4096,
tick_size: 1,
grid_start_tick: 1,
default_stp: StpPolicy::CancelIncoming,
}
}
#[test]
fn valid_config_passes() {
assert!(base().validate().is_ok());
}
#[test]
fn grid_end_overflow_is_a_config_error() {
let mut cfg = base();
cfg.grid_start_tick = u64::MAX - 10;
cfg.grid_len = 64;
assert!(matches!(
cfg.validate(),
Err(BookError::InvalidConfig { .. })
));
}
#[test]
fn grid_len_must_be_a_multiple_of_64() {
let mut cfg = base();
cfg.grid_len = 100;
assert!(matches!(
cfg.validate(),
Err(BookError::InvalidConfig { .. })
));
}
}