ipld_block_builder/
batch.rs

1use crate::codec::Encoder;
2use libipld::block::Block;
3use libipld::cid::Cid;
4use libipld::codec::Encode;
5use libipld::error::Result;
6
7/// Batch of blocks to insert atomically.
8pub struct Batch<C> {
9    codec: C,
10    blocks: Vec<Block>,
11}
12
13impl<C> Batch<C> {
14    /// Creates a new batch.
15    pub fn new(codec: C) -> Self {
16        Self {
17            codec,
18            blocks: Default::default(),
19        }
20    }
21
22    /// Creates a new batch with capacity.
23    pub fn with_capacity(codec: C, capacity: usize) -> Self {
24        Self {
25            codec,
26            blocks: Vec::with_capacity(capacity),
27        }
28    }
29
30    /// Returns an iterator of `Block`.
31    pub fn into_vec(self) -> Vec<Block> {
32        self.blocks
33    }
34}
35
36impl<C: Encoder> Batch<C> {
37    /// Inserts a block into the batch.
38    pub fn insert<T: Encode<C::Codec>>(&mut self, value: &T) -> Result<&Cid> {
39        let block = self.codec.encode(value)?;
40        self.blocks.push(block);
41        Ok(&self.blocks.last().unwrap().cid)
42    }
43}