Skip to main content

snix_castore/chunkstore/chunk/
mod.rs

1//! Provides [Chunk], a wrapper around bytes and returned by `ChunkStore`.
2
3use crate::B3Digest;
4use bytes::Bytes;
5mod builder;
6pub use builder::ChunkBuilder;
7
8/// A Chunk returned from `ChunkStore`.
9///
10/// It's a newtype over its payload, stored as [Bytes], to allow sharing.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct Chunk(Bytes);
13
14impl Chunk {
15    /// Returns the length of the payload
16    pub fn len(&self) -> usize {
17        self.0.len()
18    }
19
20    /// Returns true if the payload is empty.
21    pub fn is_empty(&self) -> bool {
22        self.len() == 0
23    }
24
25    /// Returns the BLAKE3 digest of the payload.
26    pub fn digest(&self) -> B3Digest {
27        B3Digest::from(blake3::hash(self.0.as_ref()))
28    }
29
30    /// Constructs a new Chunk from a static byte slice as payload.
31    pub const fn from_static(bytes: &'static [u8]) -> Self {
32        Self(Bytes::from_static(bytes))
33    }
34
35    /// Copies the Chunk payload into a new `Vec<[u8]>`.
36    pub fn to_vec(self) -> Vec<u8> {
37        self.0.to_vec()
38    }
39
40    /// Returns a builder that can assemble a [Chunk] by concatenating one or more [bytes::Bytes].
41    pub fn builder() -> ChunkBuilder {
42        ChunkBuilder::default()
43    }
44}
45
46impl AsRef<[u8]> for Chunk {
47    fn as_ref(&self) -> &[u8] {
48        self.0.as_ref()
49    }
50}
51
52impl From<&[u8]> for Chunk {
53    fn from(value: &[u8]) -> Self {
54        Self(Bytes::copy_from_slice(value))
55    }
56}
57
58impl From<Vec<u8>> for Chunk {
59    fn from(value: Vec<u8>) -> Self {
60        Self(Bytes::from_owner(value))
61    }
62}
63
64impl From<bytes::Bytes> for Chunk {
65    fn from(value: bytes::Bytes) -> Self {
66        Self(value)
67    }
68}
69
70impl From<Chunk> for Vec<u8> {
71    fn from(value: Chunk) -> Self {
72        value.0.to_vec()
73    }
74}
75
76impl From<Chunk> for bytes::Bytes {
77    fn from(value: Chunk) -> Self {
78        value.0
79    }
80}