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