barter_data/books/
map.rs

1use crate::books::OrderBook;
2use derive_more::Constructor;
3use fnv::FnvHashMap;
4use parking_lot::RwLock;
5use std::{hash::Hash, sync::Arc};
6
7/// Collection of shared-state Instrument [`OrderBook`]s. Manage the local books using
8/// the [`super::manager`] module, and then clone the map for viewing the up to
9/// date [`OrderBook`]s elsewhere.
10///
11/// See [`OrderBookMapSingle`] and [`OrderBookMapMulti`] for implementations.
12pub trait OrderBookMap: Clone {
13    type Key;
14
15    /// Return an [`Iterator`] over the [`OrderBookMap`] Keys (eg/ InstrumentKey).
16    fn keys(&self) -> impl Iterator<Item = &Self::Key>;
17
18    /// Attempt to find the [`OrderBook`] associated with the provided Key.
19    fn find(&self, key: &Self::Key) -> Option<Arc<RwLock<OrderBook>>>;
20}
21
22/// Single Instrument [`OrderBook`] wrapped in a shared-state lock.
23#[derive(Debug, Clone, Constructor)]
24pub struct OrderBookMapSingle<Key> {
25    pub instrument: Key,
26    pub book: Arc<RwLock<OrderBook>>,
27}
28
29impl<Key> OrderBookMap for OrderBookMapSingle<Key>
30where
31    Key: PartialEq + Clone,
32{
33    type Key = Key;
34
35    fn keys(&self) -> impl Iterator<Item = &Self::Key> {
36        std::iter::once(&self.instrument)
37    }
38
39    fn find(&self, key: &Self::Key) -> Option<Arc<RwLock<OrderBook>>> {
40        if &self.instrument == key {
41            Some(self.book.clone())
42        } else {
43            None
44        }
45    }
46}
47
48/// Multiple Instrument [`OrderBook`] wrapped in a shared-state lock.
49#[derive(Debug, Clone, Constructor)]
50pub struct OrderBookMapMulti<Key>
51where
52    Key: Eq + Hash,
53{
54    pub books: FnvHashMap<Key, Arc<RwLock<OrderBook>>>,
55}
56
57impl<Key> OrderBookMap for OrderBookMapMulti<Key>
58where
59    Key: Clone + Eq + Hash,
60{
61    type Key = Key;
62
63    fn keys(&self) -> impl Iterator<Item = &Self::Key> {
64        self.books.keys()
65    }
66
67    fn find(&self, key: &Self::Key) -> Option<Arc<RwLock<OrderBook>>> {
68        self.books.get(key).cloned()
69    }
70}
71
72impl<Key> OrderBookMapMulti<Key>
73where
74    Key: Eq + Hash,
75{
76    /// Insert a new [`OrderBook`] into the [`OrderBookMapMulti`].
77    pub fn insert(&mut self, instrument: Key, book: Arc<RwLock<OrderBook>>) {
78        self.books.insert(instrument, book);
79    }
80}