ps_datachunk/shared/
mod.rs

1use crate::{DataChunk, PsDataChunkError, Result};
2use bytes::Bytes;
3use ps_hash::Hash;
4use std::sync::Arc;
5
6pub struct SharedDataChunk {
7    data: Arc<[u8]>,
8    hash: Arc<Hash>,
9}
10
11impl SharedDataChunk {
12    #[must_use]
13    pub fn data(&self) -> Arc<[u8]> {
14        self.data.clone()
15    }
16
17    #[must_use]
18    pub fn hash(&self) -> Arc<Hash> {
19        self.hash.clone()
20    }
21}
22
23impl DataChunk for SharedDataChunk {
24    fn data_ref(&self) -> &[u8] {
25        &self.data
26    }
27
28    fn hash_ref(&self) -> &Hash {
29        &self.hash
30    }
31
32    fn hash(&self) -> Arc<Hash> {
33        self.hash.clone()
34    }
35
36    /// Transforms this [`DataChunk`] into [`Bytes`].
37    fn into_bytes(self) -> Bytes {
38        Bytes::from_owner(self.data)
39    }
40
41    /// Transforms this chunk into an [`OwnedDataChunk`]
42    fn into_owned(self) -> crate::OwnedDataChunk {
43        let Self { data, hash } = self;
44
45        crate::OwnedDataChunk::from_data_and_hash(data, hash)
46    }
47}
48
49impl SharedDataChunk {
50    #[must_use]
51    pub const fn from_data_and_hash(data: Arc<[u8]>, hash: Arc<Hash>) -> Self {
52        Self { data, hash }
53    }
54
55    pub fn from_data(data: Arc<[u8]>) -> Result<Self> {
56        let hash = Arc::from(ps_hash::hash(&data)?);
57
58        Ok(Self::from_data_and_hash(data, hash))
59    }
60}
61
62impl TryFrom<Arc<[u8]>> for SharedDataChunk {
63    type Error = PsDataChunkError;
64
65    fn try_from(data: Arc<[u8]>) -> Result<Self> {
66        Self::from_data(data)
67    }
68}
69
70impl TryFrom<&Arc<[u8]>> for SharedDataChunk {
71    type Error = PsDataChunkError;
72
73    fn try_from(data: &Arc<[u8]>) -> Result<Self> {
74        Self::from_data(data.clone())
75    }
76}