debot_db/
counter.rs

1// counter.rs
2
3pub enum CounterType {
4    Position,
5    Price,
6    Pnl,
7}
8
9pub struct CounterData {
10    max: Option<u32>,
11    counter: std::sync::Mutex<u32>,
12}
13
14pub struct Counter {
15    position: CounterData,
16    price: CounterData,
17    pnl: CounterData,
18}
19
20impl Counter {
21    pub fn new(
22        max_position_counter: Option<u32>,
23        max_price_counter: Option<u32>,
24        max_pnl_counter: Option<u32>,
25        position_counter: u32,
26        price_counter: u32,
27        pnl_counter: u32,
28    ) -> Self {
29        Self {
30            position: CounterData {
31                max: max_position_counter,
32                counter: std::sync::Mutex::new(position_counter),
33            },
34            price: CounterData {
35                max: max_price_counter,
36                counter: std::sync::Mutex::new(price_counter),
37            },
38            pnl: CounterData {
39                max: max_pnl_counter,
40                counter: std::sync::Mutex::new(pnl_counter),
41            },
42        }
43    }
44
45    pub fn increment(&self, counter_type: CounterType) -> u32 {
46        let counter_data = match counter_type {
47            CounterType::Position => &self.position,
48            CounterType::Price => &self.price,
49            CounterType::Pnl => &self.pnl,
50        };
51
52        let mut counter = counter_data.counter.lock().unwrap();
53        *counter += 1;
54        let mut id = *counter;
55        if let Some(max_counter) = counter_data.max {
56            id = *counter % max_counter;
57            if id == 0 {
58                id = 1;
59            }
60            *counter = id;
61        }
62
63        drop(counter);
64        id
65    }
66}