1#![allow(clippy::missing_errors_doc)]
2#![allow(clippy::module_name_repetitions)]
3pub mod aligned;
4pub mod borrowed;
5pub mod cow;
6pub mod encrypted;
7pub mod error;
8pub mod mbuf;
9pub mod owned;
10pub mod serialized;
11pub mod shared;
12pub mod typed;
13pub mod utils;
14pub use aligned::AlignedDataChunk;
15pub use borrowed::BorrowedDataChunk;
16pub use bytes::Bytes;
17pub use cow::CowDataChunk;
18pub use encrypted::EncryptedDataChunk;
19pub use error::PsDataChunkError;
20pub use error::Result;
21pub use mbuf::MbufDataChunk;
22pub use owned::OwnedDataChunk;
23pub use ps_hash::Hash;
24pub use ps_mbuf::Mbuf;
25pub use serialized::SerializedDataChunk;
26pub use shared::SharedDataChunk;
27pub use typed::ToDataChunk;
28pub use typed::ToTypedDataChunk;
29pub use typed::TypedDataChunk;
30
31use std::sync::Arc;
32
33pub trait DataChunk
35where
36 Self: Sized,
37{
38 fn data_ref(&self) -> &[u8];
39 fn hash_ref(&self) -> &Hash;
40
41 fn hash(&self) -> Arc<Hash>;
42
43 fn encrypt(&self) -> Result<EncryptedDataChunk> {
44 self.serialize()?.encrypt()
45 }
46
47 fn decrypt(&self, key: &[u8]) -> Result<SerializedDataChunk> {
48 utils::decrypt(self.data_ref(), key)
49 }
50
51 fn borrow(&self) -> BorrowedDataChunk<'_> {
52 BorrowedDataChunk::from_parts(self.data_ref(), self.hash())
53 }
54
55 fn serialize(&self) -> Result<SerializedDataChunk> {
56 SerializedDataChunk::from_parts(self.data_ref(), self.hash())
57 }
58
59 fn into_bytes(self) -> Bytes {
61 Bytes::from_owner(Arc::from(self.data_ref()))
62 }
63
64 fn into_owned(self) -> OwnedDataChunk {
66 OwnedDataChunk::from_data_and_hash(Arc::from(self.data_ref()), self.hash())
67 }
68
69 fn try_as<T: rkyv::Archive>(self) -> Result<TypedDataChunk<Self, T>>
70 where
71 T::Archived:
72 for<'a> rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'a, rancor::Error>>,
73 {
74 TypedDataChunk::<Self, T>::from_data_chunk(self)
75 }
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81
82 #[test]
83 fn test_encryption_decryption() -> Result<()> {
84 let original_data = "Neboť tak Bůh miluje svět, že dal [svého] jediného Syna, aby žádný, kdo v něho věří, nezahynul, ale měl život věčný. Vždyť Bůh neposlal [svého] Syna na svět, aby svět odsoudil, ale aby byl svět skrze něj zachráněn.".as_bytes().to_owned();
85
86 let data_chunk = BorrowedDataChunk::from_data(&original_data)?;
87
88 let encrypted_chunk = data_chunk.encrypt()?;
89 let decrypted_chunk = encrypted_chunk.decrypt()?;
90
91 assert_eq!(decrypted_chunk.data_ref(), original_data);
92
93 Ok(())
94 }
95
96 #[test]
97 fn test_serialization() -> Result<()> {
98 let original_data = vec![1, 2, 3, 4, 5];
99 let hash = ps_hash::hash(&original_data)?.into();
100 let data_chunk = OwnedDataChunk::from_data_and_hash(original_data.clone(), hash);
101
102 let serialized = data_chunk.serialize()?;
103
104 assert_eq!(serialized.data_ref(), original_data);
105
106 Ok(())
107 }
108}