Skip to content

Commit

Permalink
feat(chain, file_store): add is_empty method to PersistBackend trait
Browse files Browse the repository at this point in the history
  • Loading branch information
evanlinjin committed Oct 27, 2023
1 parent 2d3f22d commit 848909f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
13 changes: 13 additions & 0 deletions crates/chain/src/persist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,15 @@ pub trait PersistBackend<C> {

/// Return the aggregate changeset `C` from persistence.
fn load_from_persistence(&mut self) -> Result<C, Self::LoadError>;

/// Returns whether the persistence backend contains no data.
fn is_empty(&mut self) -> Result<bool, Self::LoadError>
where
C: Append,
{
self.load_from_persistence()
.map(|changeset| changeset.is_empty())
}
}

impl<C: Default> PersistBackend<C> for () {
Expand All @@ -94,4 +103,8 @@ impl<C: Default> PersistBackend<C> for () {
fn load_from_persistence(&mut self) -> Result<C, Self::LoadError> {
Ok(C::default())
}

fn is_empty(&mut self) -> Result<bool, Self::LoadError> {
Ok(true)
}
}
21 changes: 21 additions & 0 deletions crates/file_store/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ where
let (changeset, result) = self.aggregate_changesets();
result.map(|_| changeset)
}

fn is_empty(&mut self) -> Result<bool, Self::LoadError> {
let init_pos = self.db_file.stream_position()?;
let stream_len = self.db_file.seek(io::SeekFrom::End(0))?;
let magic_len = self.magic.len() as u64;
self.db_file.seek(io::SeekFrom::Start(init_pos))?;
Ok(stream_len == magic_len)
}
}

impl<'a, C> Store<'a, C>
Expand Down Expand Up @@ -182,6 +190,19 @@ mod test {
#[derive(Debug)]
struct TestTracker;

#[test]
fn is_empty() {
let mut file = NamedTempFile::new().unwrap();
file.write_all(&TEST_MAGIC_BYTES).expect("should write");

let mut db = Store::<TestChangeSet>::new(&TEST_MAGIC_BYTES, file.reopen().unwrap())
.expect("must open");
assert!(db.is_empty().expect("must read"));
db.write_changes(&vec!["hello".to_string(), "world".to_string()])
.expect("must write");
assert!(!db.is_empty().expect("must read"));
}

#[test]
fn new_fails_if_file_is_too_short() {
let mut file = NamedTempFile::new().unwrap();
Expand Down

0 comments on commit 848909f

Please sign in to comment.