diff --git a/wnfs-common/src/blockstore.rs b/wnfs-common/src/blockstore.rs index 6ddadec5..9c431a79 100644 --- a/wnfs-common/src/blockstore.rs +++ b/wnfs-common/src/blockstore.rs @@ -91,7 +91,11 @@ pub trait BlockStore: Sized { /// /// IPFS is basically a glorified HashMap. #[derive(Debug, Default, Clone, Serialize, Deserialize)] -pub struct MemoryBlockStore(pub(crate) RefCell>); +pub struct MemoryBlockStore( + #[serde(serialize_with = "crate::utils::serialize_cid_map")] + #[serde(deserialize_with = "crate::utils::deserialize_cid_map")] + pub(crate) RefCell>, +); impl MemoryBlockStore { /// Creates a new in-memory block store. diff --git a/wnfs-common/src/utils/common.rs b/wnfs-common/src/utils/common.rs index 490eba70..45f65408 100644 --- a/wnfs-common/src/utils/common.rs +++ b/wnfs-common/src/utils/common.rs @@ -1,10 +1,11 @@ use crate::HashOutput; use anyhow::Result; +use bytes::Bytes; use futures::{AsyncRead, AsyncReadExt}; -use libipld::IpldCodec; +use libipld::{Cid, IpldCodec}; use rand_core::CryptoRngCore; -use serde::de::Visitor; -use std::fmt; +use serde::{de::Visitor, Deserialize, Serialize, Serializer}; +use std::{cell::RefCell, collections::HashMap, fmt}; //-------------------------------------------------------------------------------------------------- // Type Definitions @@ -107,3 +108,37 @@ pub fn to_hash_output(bytes: &[u8]) -> HashOutput { pub fn u64_to_ipld(value: u64) -> Result { Ok(value.try_into()?) } + +pub(crate) fn serialize_cid_map( + map: &RefCell>, + serializer: S, +) -> Result +where + S: Serializer, +{ + let map = map + .borrow() + .iter() + .map(|(cid, bytes)| (cid.to_string(), bytes.to_vec())) + .collect::>(); + + map.serialize(serializer) +} + +pub(crate) fn deserialize_cid_map<'de, D>( + deserializer: D, +) -> Result>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let map = HashMap::>::deserialize(deserializer)?; + let map = map + .into_iter() + .map(|(cid, bytes)| { + let cid = cid.parse::().map_err(serde::de::Error::custom)?; + Ok((cid, bytes.into())) + }) + .collect::>()?; + + Ok(RefCell::new(map)) +}