cfxcore/transaction_pool/nonce_pool/
weight.rs

1use cfx_types::U256;
2use malloc_size_of_derive::MallocSizeOf;
3
4use treap_map::ConsoliableWeight;
5
6use super::TxWithReadyInfo;
7
8/// Accumulable weight for Nonce Pool Treap
9#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, MallocSizeOf)]
10pub(super) struct NoncePoolWeight {
11    /// number of unpacked transactions
12    pub unpacked_size: u32,
13    /// sum of cost of transactions
14    pub cost: U256,
15    /// number of transactions
16    pub size: u32,
17    /// max unpacked nonce
18    pub max_unpackd_nonce: Option<U256>,
19}
20
21impl ConsoliableWeight for NoncePoolWeight {
22    #[inline]
23    fn empty() -> Self { Self::default() }
24
25    #[inline]
26    fn consolidate(a: &Self, b: &Self) -> Self {
27        if a == &Self::empty() {
28            return *b;
29        }
30        Self {
31            unpacked_size: a.unpacked_size + b.unpacked_size,
32            cost: a.cost + b.cost,
33            size: a.size + b.size,
34            max_unpackd_nonce: consolidate_max_nonce(
35                a.max_unpackd_nonce,
36                b.max_unpackd_nonce,
37            ),
38        }
39    }
40
41    #[inline]
42    fn accure(&mut self, other: &Self) {
43        self.unpacked_size += other.unpacked_size;
44        self.cost += other.cost;
45        self.size += other.size;
46        self.max_unpackd_nonce = consolidate_max_nonce(
47            self.max_unpackd_nonce,
48            other.max_unpackd_nonce,
49        );
50    }
51}
52
53impl NoncePoolWeight {
54    pub fn from_tx_info(tx_info: &TxWithReadyInfo) -> Self {
55        if tx_info.packed {
56            Self {
57                unpacked_size: 0,
58                cost: tx_info.get_tx_cost(),
59                size: 1,
60                max_unpackd_nonce: None,
61            }
62        } else {
63            Self {
64                unpacked_size: 1,
65                cost: tx_info.get_tx_cost(),
66                size: 1,
67                max_unpackd_nonce: Some(*tx_info.transaction.nonce()),
68            }
69        }
70    }
71}
72
73#[inline]
74fn consolidate_max_nonce(a: Option<U256>, b: Option<U256>) -> Option<U256> {
75    match (a, b) {
76        (None, None) => None,
77        (None, Some(b)) => Some(b),
78        (Some(a), None) => Some(a),
79        (Some(a), Some(b)) => Some(U256::max(a, b)),
80    }
81}