Use Cow for checkpoint cache (#775)

This commit is contained in:
Paul Hauner 2020-01-08 11:09:27 +11:00 committed by GitHub
parent 8e1e6838d2
commit 26dde26c48
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 6 deletions

View File

@ -23,6 +23,7 @@ use state_processing::per_block_processing::{
use state_processing::{
per_block_processing, per_slot_processing, BlockProcessingError, BlockSignatureStrategy,
};
use std::borrow::Cow;
use std::fs;
use std::io::prelude::*;
use std::sync::Arc;
@ -1411,12 +1412,12 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
//
// A block that was just imported is likely to be referenced by the next block that we
// import.
self.checkpoint_cache.insert(&CheckPoint {
self.checkpoint_cache.insert(Cow::Owned(CheckPoint {
beacon_block_root: block_root,
beacon_block: block,
beacon_state_root: state_root,
beacon_state: state,
});
}));
metrics::stop_timer(full_timer);
@ -1626,7 +1627,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
// Store the head in the checkpoint cache.
//
// The head block is likely to be referenced by the next imported block.
self.checkpoint_cache.insert(&new_head);
self.checkpoint_cache.insert(Cow::Borrowed(&new_head));
// Update the checkpoint that stores the head of the chain at the time it received the
// block.

View File

@ -1,6 +1,7 @@
use crate::checkpoint::CheckPoint;
use crate::metrics;
use parking_lot::RwLock;
use std::borrow::Cow;
use types::{BeaconBlock, BeaconState, EthSpec, Hash256};
const CACHE_SIZE: usize = 4;
@ -34,7 +35,7 @@ impl<T: EthSpec> Default for CheckPointCache<T> {
}
impl<T: EthSpec> CheckPointCache<T> {
pub fn insert(&self, checkpoint: &CheckPoint<T>) {
pub fn insert(&self, checkpoint: Cow<CheckPoint<T>>) {
if self
.inner
.read()
@ -50,10 +51,10 @@ impl<T: EthSpec> CheckPointCache<T> {
let mut inner = self.inner.write();
if inner.checkpoints.len() < inner.limit {
inner.checkpoints.push(checkpoint.clone())
inner.checkpoints.push(checkpoint.into_owned())
} else {
let i = inner.oldest; // to satisfy the borrow checker.
inner.checkpoints[i] = checkpoint.clone();
inner.checkpoints[i] = checkpoint.into_owned();
inner.oldest += 1;
inner.oldest %= inner.limit;
}