Skip to main content

ps_datachunk/borrowed/
mod.rs

1mod implementations;
2
3use std::sync::Arc;
4
5use ps_hash::Hash;
6
7use crate::{DataChunk, Result};
8
9#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
10pub struct BorrowedDataChunk<'lt> {
11    data: &'lt [u8],
12    hash: Hash,
13}
14
15impl<'lt> BorrowedDataChunk<'lt> {
16    #[must_use]
17    pub const fn from_parts_unchecked(data: &'lt [u8], hash: Hash) -> Self {
18        Self { data, hash }
19    }
20
21    pub fn from_data(data: &'lt [u8]) -> Result<Self> {
22        let hash = ps_hash::hash(data)?;
23
24        Ok(Self::from_parts_unchecked(data, hash))
25    }
26}
27
28impl DataChunk for BorrowedDataChunk<'_> {
29    fn data_ref(&self) -> &[u8] {
30        self.data
31    }
32    fn hash_ref(&self) -> &Hash {
33        &self.hash
34    }
35
36    fn borrow(&self) -> BorrowedDataChunk<'_> {
37        Self {
38            data: self.data,
39            hash: self.hash(),
40        }
41    }
42
43    /// Transforms this chunk into an [`crate::OwnedDataChunk`]
44    fn into_owned(self) -> crate::OwnedDataChunk {
45        let Self { data, hash } = self;
46
47        crate::OwnedDataChunk::from_data_and_hash_unchecked(Arc::from(data), hash)
48    }
49}
50
51impl<'lt, T: DataChunk> From<&'lt T> for BorrowedDataChunk<'lt> {
52    fn from(chunk: &'lt T) -> Self {
53        Self::from_parts_unchecked(chunk.data_ref(), chunk.hash())
54    }
55}