fvm_ipld_encoding/
cbor_store.rs

1// Copyright 2021-2023 Protocol Labs
2// SPDX-License-Identifier: Apache-2.0, MIT
3use anyhow::anyhow;
4use cid::Cid;
5use fvm_ipld_blockstore::{Block, Blockstore};
6use serde::{de, ser};
7
8use crate::{CBOR, DAG_CBOR};
9
10/// Wrapper for database to handle inserting and retrieving ipld data with Cids
11pub trait CborStore: Blockstore + Sized {
12    /// Get typed object from block store by Cid.
13    fn get_cbor<T>(&self, cid: &Cid) -> anyhow::Result<Option<T>>
14    where
15        T: de::DeserializeOwned,
16    {
17        if !matches!(cid.codec(), CBOR | DAG_CBOR) {
18            return Err(anyhow!("{} is not CBOR or DagCBOR", cid.codec()));
19        }
20        match self.get(cid)? {
21            Some(bz) => {
22                let res = crate::from_slice(&bz)?;
23                Ok(Some(res))
24            }
25            None => Ok(None),
26        }
27    }
28
29    /// Put an object in the block store and return the Cid identifier.
30    fn put_cbor<S>(&self, obj: &S, code: multihash_codetable::Code) -> anyhow::Result<Cid>
31    where
32        S: ser::Serialize,
33    {
34        let bytes = crate::to_vec(obj)?;
35        self.put(
36            code,
37            &Block {
38                codec: DAG_CBOR,
39                data: &bytes,
40            },
41        )
42    }
43}
44
45impl<T: Blockstore> CborStore for T {}