ps_datachunk/owned/
mod.rs

1mod implementations;
2
3use crate::DataChunk;
4use crate::Result;
5use bytes::Bytes;
6use ps_hash::Hash;
7
8#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
9/// represents an owned chunk of data
10pub struct OwnedDataChunk {
11    hash: Hash,
12    data: Bytes,
13}
14
15impl OwnedDataChunk {
16    #[must_use]
17    pub fn data_ref(&self) -> &[u8] {
18        &self.data
19    }
20
21    #[must_use]
22    pub const fn hash_ref(&self) -> &Hash {
23        &self.hash
24    }
25
26    #[must_use]
27    pub const fn hash(&self) -> Hash {
28        self.hash
29    }
30
31    /// Creates an [`OwnedDataChunk`] from its constituent parts
32    /// # Safety
33    /// - `hash` must be the hash of `data`
34    /// - use `from_data()` if you cannot ensure this
35    #[inline]
36    #[must_use]
37    pub const fn from_parts(data: Bytes, hash: Hash) -> Self {
38        Self { hash, data }
39    }
40
41    pub fn from_data_and_hash<D>(data: D, hash: Hash) -> Self
42    where
43        D: AsRef<[u8]> + Send + 'static,
44    {
45        Self::from_parts(Bytes::from_owner(data), hash)
46    }
47
48    /// calculates the hash of `data` and returns an `OwnedDataChunk`
49    pub fn from_bytes(data: Bytes) -> Result<Self> {
50        let hash = ps_hash::hash(&data)?;
51
52        Ok(Self::from_parts(data, hash))
53    }
54
55    /// calculates the hash of `data` and returns an `OwnedDataChunk`
56    pub fn from_data<D>(data: D) -> Result<Self>
57    where
58        D: AsRef<[u8]> + Send + 'static,
59    {
60        Self::from_bytes(Bytes::from_owner(data))
61    }
62}
63
64impl DataChunk for OwnedDataChunk {
65    fn data_ref(&self) -> &[u8] {
66        self.data_ref()
67    }
68    fn hash_ref(&self) -> &Hash {
69        self.hash_ref()
70    }
71    fn hash(&self) -> Hash {
72        self.hash()
73    }
74
75    /// Transforms this [`DataChunk`] into [`Bytes`].
76    fn into_bytes(self) -> Bytes {
77        self.data
78    }
79
80    /// Transforms this chunk into an [`OwnedDataChunk`]
81    fn into_owned(self) -> Self {
82        self
83    }
84}