ps_datachunk/borrowed/
mod.rs1mod 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: Arc<Hash>,
13}
14
15impl<'lt> BorrowedDataChunk<'lt> {
16 #[must_use]
17 pub const fn from_parts(data: &'lt [u8], hash: Arc<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(data, hash.into()))
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 fn hash(&self) -> Arc<Hash> {
36 self.hash.clone()
37 }
38
39 fn borrow(&self) -> BorrowedDataChunk<'_> {
40 Self {
41 data: self.data,
42 hash: self.hash(),
43 }
44 }
45
46 fn into_owned(self) -> crate::OwnedDataChunk {
48 let Self { data, hash } = self;
49
50 crate::OwnedDataChunk::from_data_and_hash(Arc::from(data), hash)
51 }
52}
53
54impl<'lt, T: DataChunk> From<&'lt T> for BorrowedDataChunk<'lt> {
55 fn from(chunk: &'lt T) -> Self {
56 Self::from_parts(chunk.data_ref(), chunk.hash())
57 }
58}