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 DataChunk for BorrowedDataChunk<'_> {
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 borrow(&self) -> BorrowedDataChunk {
38 Self {
39 data: self.data,
40 hash: self.hash(),
41 }
42 }
43
44 fn into_owned(self) -> crate::OwnedDataChunk {
46 let Self { data, hash } = self;
47
48 crate::OwnedDataChunk::from_data_and_hash(Arc::from(data), hash)
49 }
50}
51
52impl<'lt, T: DataChunk> From<&'lt T> for BorrowedDataChunk<'lt> {
53 fn from(chunk: &'lt T) -> Self {
54 Self::from_parts(chunk.data_ref(), chunk.hash())
55 }
56}