ps_datachunk/owned/
mod.rs

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