Skip to content

Commit

Permalink
Fix memoryblockstore serde issue
Browse files Browse the repository at this point in the history
  • Loading branch information
appcypher committed Aug 1, 2023
1 parent 34bd152 commit 9f6bf3b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
6 changes: 5 additions & 1 deletion wnfs-common/src/blockstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<HashMap<Cid, Bytes>>);
pub struct MemoryBlockStore(
#[serde(serialize_with = "crate::utils::serialize_cid_map")]
#[serde(deserialize_with = "crate::utils::deserialize_cid_map")]
pub(crate) RefCell<HashMap<Cid, Bytes>>,
);

impl MemoryBlockStore {
/// Creates a new in-memory block store.
Expand Down
41 changes: 38 additions & 3 deletions wnfs-common/src/utils/common.rs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -107,3 +108,37 @@ pub fn to_hash_output(bytes: &[u8]) -> HashOutput {
pub fn u64_to_ipld(value: u64) -> Result<IpldCodec> {
Ok(value.try_into()?)
}

pub(crate) fn serialize_cid_map<S>(
map: &RefCell<HashMap<Cid, Bytes>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let map = map
.borrow()
.iter()
.map(|(cid, bytes)| (cid.to_string(), bytes.to_vec()))
.collect::<HashMap<_, _>>();

map.serialize(serializer)
}

pub(crate) fn deserialize_cid_map<'de, D>(
deserializer: D,
) -> Result<RefCell<HashMap<Cid, Bytes>>, D::Error>
where
D: serde::Deserializer<'de>,
{
let map = HashMap::<String, Vec<u8>>::deserialize(deserializer)?;
let map = map
.into_iter()
.map(|(cid, bytes)| {
let cid = cid.parse::<Cid>().map_err(serde::de::Error::custom)?;
Ok((cid, bytes.into()))
})
.collect::<Result<_, _>>()?;

Ok(RefCell::new(map))
}

0 comments on commit 9f6bf3b

Please sign in to comment.