use reth_primitives::{BlockHash, BlockNumHash, BlockNumber};
use std::collections::BTreeMap;
#[derive(Debug, Clone, Default)]
pub(crate) struct CanonicalChain {
chain: BTreeMap<BlockNumber, BlockHash>,
}
impl CanonicalChain {
pub(crate) const fn new(chain: BTreeMap<BlockNumber, BlockHash>) -> Self {
Self { chain }
}
#[inline]
pub(crate) fn replace(&mut self, chain: BTreeMap<BlockNumber, BlockHash>) {
self.chain = chain;
}
#[inline]
pub(crate) fn canonical_hash(&self, number: &BlockNumber) -> Option<BlockHash> {
self.chain.get(number).copied()
}
#[inline]
pub(crate) fn canonical_number(&self, block_hash: &BlockHash) -> Option<BlockNumber> {
self.chain.iter().find_map(
|(number, hash)| {
if hash == block_hash {
Some(*number)
} else {
None
}
},
)
}
#[inline]
pub(crate) fn extend(&mut self, blocks: impl Iterator<Item = (BlockNumber, BlockHash)>) {
self.chain.extend(blocks)
}
#[inline]
pub(crate) fn retain<F>(&mut self, f: F)
where
F: FnMut(&BlockNumber, &mut BlockHash) -> bool,
{
self.chain.retain(f)
}
#[inline]
pub(crate) const fn inner(&self) -> &BTreeMap<BlockNumber, BlockHash> {
&self.chain
}
#[inline]
pub(crate) fn tip(&self) -> BlockNumHash {
self.chain
.last_key_value()
.map(|(&number, &hash)| BlockNumHash { number, hash })
.unwrap_or_default()
}
#[inline]
pub(crate) fn iter(&self) -> impl Iterator<Item = (BlockNumber, BlockHash)> + '_ {
self.chain.iter().map(|(&number, &hash)| (number, hash))
}
#[inline]
pub(crate) fn into_iter(self) -> impl Iterator<Item = (BlockNumber, BlockHash)> {
self.chain.into_iter()
}
}