ps_datachunk/owned/
mod.rs

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