use std::collections::HashMap;
use wasm_bindgen::prelude::*;
pub struct InMemoryBlockStore {
blocks: HashMap<String, Vec<u8>>,
total_bytes_cached: usize,
}
impl InMemoryBlockStore {
pub fn new() -> Self {
Self {
blocks: HashMap::new(),
total_bytes_cached: 0,
}
}
pub fn put(&mut self, cid: impl Into<String>, data: Vec<u8>) {
let key = cid.into();
let new_len = data.len();
if let Some(old) = self.blocks.insert(key, data) {
self.total_bytes_cached = self
.total_bytes_cached
.saturating_sub(old.len())
.saturating_add(new_len);
} else {
self.total_bytes_cached = self.total_bytes_cached.saturating_add(new_len);
}
}
pub fn get(&self, cid: &str) -> Option<&[u8]> {
self.blocks.get(cid).map(|v| v.as_slice())
}
pub fn has(&self, cid: &str) -> bool {
self.blocks.contains_key(cid)
}
pub fn delete(&mut self, cid: &str) -> bool {
if let Some(removed) = self.blocks.remove(cid) {
self.total_bytes_cached = self.total_bytes_cached.saturating_sub(removed.len());
true
} else {
false
}
}
pub fn len(&self) -> usize {
self.blocks.len()
}
pub fn is_empty(&self) -> bool {
self.blocks.is_empty()
}
pub fn keys(&self) -> Vec<String> {
let mut keys: Vec<String> = self.blocks.keys().cloned().collect();
keys.sort();
keys
}
pub fn total_bytes(&self) -> usize {
self.total_bytes_cached
}
pub fn clear(&mut self) {
self.blocks.clear();
self.total_bytes_cached = 0;
}
pub fn export_entries(&self) -> Vec<(String, Vec<u8>)> {
let mut entries: Vec<(String, Vec<u8>)> = self
.blocks
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
entries.sort_by(|a, b| a.0.cmp(&b.0));
entries
}
pub fn import_entries(&mut self, entries: Vec<(String, Vec<u8>)>) {
for (cid, data) in entries {
self.put(cid, data);
}
}
}
impl Default for InMemoryBlockStore {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen]
pub struct WasmBlockStore {
inner: InMemoryBlockStore,
}
#[wasm_bindgen]
impl WasmBlockStore {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
Self {
inner: InMemoryBlockStore::new(),
}
}
pub fn put(&mut self, cid: &str, data: &[u8]) {
self.inner.put(cid, data.to_vec());
}
pub fn get(&self, cid: &str) -> Option<Vec<u8>> {
self.inner.get(cid).map(|s| s.to_vec())
}
pub fn has(&self, cid: &str) -> bool {
self.inner.has(cid)
}
pub fn delete(&mut self, cid: &str) -> bool {
self.inner.delete(cid)
}
pub fn len(&self) -> usize {
self.inner.len()
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn keys(&self) -> Vec<String> {
self.inner.keys()
}
pub fn total_bytes(&self) -> usize {
self.inner.total_bytes()
}
pub fn clear(&mut self) {
self.inner.clear();
}
}
impl Default for WasmBlockStore {
fn default() -> Self {
Self::new()
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::InMemoryBlockStore;
fn store_with_entries() -> (InMemoryBlockStore, String, String) {
let mut store = InMemoryBlockStore::new();
let cid_a = "bafkreia".to_string();
let cid_b = "bafkreib".to_string();
store.put(cid_a.clone(), b"hello".to_vec());
store.put(cid_b.clone(), b"world!".to_vec());
(store, cid_a, cid_b)
}
#[test]
fn test_put_and_get() {
let mut store = InMemoryBlockStore::new();
let cid = "bafkreitest1".to_string();
let data = b"roundtrip data".to_vec();
store.put(cid.clone(), data.clone());
let retrieved = store.get(&cid).expect("block must be present");
assert_eq!(retrieved, data.as_slice());
}
#[test]
fn test_has() {
let mut store = InMemoryBlockStore::new();
let cid = "bafkreihas1".to_string();
assert!(!store.has(&cid), "store must be empty initially");
store.put(cid.clone(), b"data".to_vec());
assert!(store.has(&cid), "block must be found after put");
assert!(
!store.has("bafkreinonexistent"),
"absent CID must return false"
);
}
#[test]
fn test_delete() {
let mut store = InMemoryBlockStore::new();
let cid = "bafkreidel1".to_string();
store.put(cid.clone(), b"to delete".to_vec());
assert!(
store.delete(&cid),
"delete must return true for existing key"
);
assert!(!store.has(&cid), "block must be gone after delete");
assert!(
!store.delete(&cid),
"delete of absent key must return false"
);
assert!(
!store.delete("bafkreinonexistent"),
"delete of never-inserted key must return false"
);
}
#[test]
fn test_len_and_is_empty() {
let mut store = InMemoryBlockStore::new();
assert!(store.is_empty(), "new store must be empty");
assert_eq!(store.len(), 0);
store.put("bafkreic1".to_string(), b"a".to_vec());
assert!(!store.is_empty());
assert_eq!(store.len(), 1);
store.put("bafkreic2".to_string(), b"b".to_vec());
assert_eq!(store.len(), 2);
store.delete("bafkreic1");
assert_eq!(store.len(), 1);
store.clear();
assert!(store.is_empty());
assert_eq!(store.len(), 0);
}
#[test]
fn test_keys() {
let (store, cid_a, cid_b) = store_with_entries();
let keys = store.keys();
assert_eq!(keys.len(), 2);
let mut expected = vec![cid_a, cid_b];
expected.sort();
assert_eq!(keys, expected, "keys() must return sorted CID strings");
}
#[test]
fn test_total_bytes() {
let mut store = InMemoryBlockStore::new();
assert_eq!(store.total_bytes(), 0, "empty store has 0 bytes");
store.put("cid1".to_string(), b"abc".to_vec()); assert_eq!(store.total_bytes(), 3);
store.put("cid2".to_string(), b"defgh".to_vec()); assert_eq!(store.total_bytes(), 8);
store.delete("cid1");
assert_eq!(store.total_bytes(), 5);
}
#[test]
fn test_clear() {
let (mut store, _, _) = store_with_entries();
assert!(!store.is_empty(), "store must have entries before clear");
assert!(store.total_bytes() > 0);
store.clear();
assert!(store.is_empty(), "store must be empty after clear");
assert_eq!(store.total_bytes(), 0, "total_bytes must be 0 after clear");
assert_eq!(store.len(), 0);
}
#[test]
fn test_export_import_roundtrip() {
let (original, cid_a, cid_b) = store_with_entries();
let exported = original.export_entries();
let mut expected_cids: Vec<&str> = vec![cid_a.as_str(), cid_b.as_str()];
expected_cids.sort();
let exported_cids: Vec<&str> = exported.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(exported_cids, expected_cids);
let mut restored = InMemoryBlockStore::new();
restored.import_entries(exported);
assert_eq!(restored.len(), original.len());
assert_eq!(restored.total_bytes(), original.total_bytes());
assert_eq!(
restored.get(&cid_a).map(|s| s.to_vec()),
original.get(&cid_a).map(|s| s.to_vec())
);
assert_eq!(
restored.get(&cid_b).map(|s| s.to_vec()),
original.get(&cid_b).map(|s| s.to_vec())
);
}
#[test]
fn test_overwrite_existing() {
let mut store = InMemoryBlockStore::new();
let cid = "bafkreioverwrite".to_string();
store.put(cid.clone(), b"first value".to_vec());
assert_eq!(store.total_bytes(), 11);
store.put(cid.clone(), b"second".to_vec()); assert_eq!(store.len(), 1, "must not create a duplicate entry");
assert_eq!(
store.total_bytes(),
6,
"total_bytes must reflect the overwritten value"
);
assert_eq!(
store.get(&cid).map(|s| s.to_vec()),
Some(b"second".to_vec()),
"get must return the most recently written value"
);
}
}