Skip to main content

snix_castore/chunkstore/chunk/
builder.rs

1//! Construction of chunks by appending one or more [bytes::Bytes]
2
3use super::Chunk;
4
5/// Allows assembling a [Chunk] from one or more [bytes::Bytes]
6/// If the Chunk is constructed from just one [bytes::Bytes], we reuse it zero-copy.
7#[derive(Default)]
8pub enum ChunkBuilder {
9    #[default]
10    Empty,
11    Single(bytes::Bytes),
12    Multiple(Vec<u8>),
13}
14
15impl ChunkBuilder {
16    /// Adds a bytes::Bytes
17    pub fn append_bytes(&mut self, b: bytes::Bytes) {
18        match std::mem::take(self) {
19            ChunkBuilder::Empty => *self = ChunkBuilder::Single(b),
20            ChunkBuilder::Single(old_buf) => {
21                *self = ChunkBuilder::Multiple({
22                    let mut v: Vec<u8> = old_buf.into();
23                    v.extend(b);
24                    v
25                })
26            }
27            ChunkBuilder::Multiple(mut v) => {
28                *self = ChunkBuilder::Multiple({
29                    v.extend(b);
30                    v
31                })
32            }
33        }
34    }
35
36    /// Returns a [Chunk] with all the data appended so far.
37    pub fn build(self) -> Chunk {
38        match self {
39            ChunkBuilder::Empty => Chunk::from_static(&[]),
40            ChunkBuilder::Single(b) => Chunk::from(b),
41            ChunkBuilder::Multiple(v) => Chunk::from(v),
42        }
43    }
44}