barter_data/books/
map.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use crate::books::OrderBook;
use derive_more::Constructor;
use fnv::FnvHashMap;
use parking_lot::RwLock;
use std::hash::Hash;
use std::sync::Arc;

/// Collection of shared-state Instrument [`OrderBook`]s. Manage the local books using
/// the [`super::manager`] module, and then clone the map for viewing the up to
/// date [`OrderBook`]s elsewhere.
///
/// See [`OrderBookMapSingle`] and [`OrderBookMapMulti`] for implementations.
pub trait OrderBookMap: Clone {
    type Key;

    /// Return an [`Iterator`] over the [`OrderBookMap`] Keys (eg/ InstrumentKey).
    fn keys(&self) -> impl Iterator<Item = &Self::Key>;

    /// Attempt to find the [`OrderBook`] associated with the provided Key.
    fn find(&self, key: &Self::Key) -> Option<Arc<RwLock<OrderBook>>>;
}

/// Single Instrument [`OrderBook`] wrapped in a shared-state lock.
#[derive(Debug, Clone, Constructor)]
pub struct OrderBookMapSingle<Key> {
    pub instrument: Key,
    pub book: Arc<RwLock<OrderBook>>,
}

impl<Key> OrderBookMap for OrderBookMapSingle<Key>
where
    Key: PartialEq + Clone,
{
    type Key = Key;

    fn keys(&self) -> impl Iterator<Item = &Self::Key> {
        std::iter::once(&self.instrument)
    }

    fn find(&self, key: &Self::Key) -> Option<Arc<RwLock<OrderBook>>> {
        if &self.instrument == key {
            Some(self.book.clone())
        } else {
            None
        }
    }
}

/// Multiple Instrument [`OrderBook`] wrapped in a shared-state lock.
#[derive(Debug, Clone, Constructor)]
pub struct OrderBookMapMulti<Key>
where
    Key: Eq + Hash,
{
    pub books: FnvHashMap<Key, Arc<RwLock<OrderBook>>>,
}

impl<Key> OrderBookMap for OrderBookMapMulti<Key>
where
    Key: Clone + Eq + Hash,
{
    type Key = Key;

    fn keys(&self) -> impl Iterator<Item = &Self::Key> {
        self.books.keys()
    }

    fn find(&self, key: &Self::Key) -> Option<Arc<RwLock<OrderBook>>> {
        self.books.get(key).cloned()
    }
}

impl<Key> OrderBookMapMulti<Key>
where
    Key: Eq + Hash,
{
    /// Insert a new [`OrderBook`] into the [`OrderBookMapMulti`].
    pub fn insert(&mut self, instrument: Key, book: Arc<RwLock<OrderBook>>) {
        self.books.insert(instrument, book);
    }
}