atrium_repo/blockstore/
diff.rs

1use std::collections::HashSet;
2
3use ipld_core::cid::Cid;
4
5use super::{AsyncBlockStoreRead, AsyncBlockStoreWrite, Error};
6
7/// An extremely simple differencing blockstore layer. This tracks all CIDs that are created.
8pub struct DiffBlockStore<S> {
9    inner: S,
10    blocks: HashSet<Cid>,
11}
12
13impl<S> DiffBlockStore<S> {
14    pub fn wrap(inner: S) -> Self {
15        Self { inner, blocks: HashSet::new() }
16    }
17
18    pub fn into_inner(self) -> S {
19        self.inner
20    }
21
22    /// Return the CIDs of the blocks that have been written so far.
23    pub fn blocks(&self) -> impl Iterator<Item = Cid> + '_ {
24        self.blocks.iter().cloned()
25    }
26}
27
28impl<S: AsyncBlockStoreRead> AsyncBlockStoreRead for DiffBlockStore<S> {
29    async fn read_block_into(&mut self, cid: Cid, contents: &mut Vec<u8>) -> Result<(), Error> {
30        self.inner.read_block_into(cid, contents).await
31    }
32}
33
34impl<S: AsyncBlockStoreWrite> AsyncBlockStoreWrite for DiffBlockStore<S> {
35    async fn write_block(&mut self, codec: u64, hash: u64, contents: &[u8]) -> Result<Cid, Error> {
36        let cid = self.inner.write_block(codec, hash, contents).await?;
37        self.blocks.insert(cid);
38        Ok(cid)
39    }
40}