Skip to content

Commit

Permalink
feat: add missing store impls & add len (#21)
Browse files Browse the repository at this point in the history
* `InMemoryBlockstore`
  * Traits: add `Clone` and `Debug`
  * Functions: add `len`
* `LruBlockstore`
  * Traits: add `Debug`
  * Functions: add `len`
  • Loading branch information
expede authored Jun 27, 2024
1 parent 651c4f3 commit 26a33f3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/in_memory_blockstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use dashmap::DashMap;
use crate::{convert_cid, Blockstore, Result};

/// Simple in-memory blockstore implementation.
#[derive(Clone, Debug)]
pub struct InMemoryBlockstore<const MAX_MULTIHASH_SIZE: usize> {
map: DashMap<CidGeneric<MAX_MULTIHASH_SIZE>, Vec<u8>>,
}
Expand All @@ -16,6 +17,16 @@ impl<const MAX_MULTIHASH_SIZE: usize> InMemoryBlockstore<MAX_MULTIHASH_SIZE> {
}
}

/// Get the number of elements in the blockstore
pub fn len(&self) -> usize {
self.map.len()
}

/// Check if the blockstore is empty
pub fn is_empty(&self) -> bool {
self.len() == 0
}

fn get_cid(&self, cid: &CidGeneric<MAX_MULTIHASH_SIZE>) -> Result<Option<Vec<u8>>> {
Ok(self.map.get(cid).as_deref().cloned())
}
Expand Down
11 changes: 11 additions & 0 deletions src/lru_blockstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use lru::LruCache;
use crate::{convert_cid, Blockstore, Result};

/// An LRU cached [`Blockstore`].
#[derive(Debug)]
pub struct LruBlockstore<const MAX_MULTIHASH_SIZE: usize> {
cache: Mutex<LruCache<CidGeneric<MAX_MULTIHASH_SIZE>, Vec<u8>>>,
}
Expand All @@ -17,6 +18,16 @@ impl<const MAX_MULTIHASH_SIZE: usize> LruBlockstore<MAX_MULTIHASH_SIZE> {
cache: Mutex::new(LruCache::new(capacity)),
}
}

/// Get the number of elements in the blockstore
pub fn len(&self) -> usize {
self.cache.lock().expect("lock failed").len()
}

/// Check if the blockstore is empty
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}

impl<const MAX_MULTIHASH_SIZE: usize> Blockstore for LruBlockstore<MAX_MULTIHASH_SIZE> {
Expand Down

0 comments on commit 26a33f3

Please sign in to comment.