1#![allow(clippy::missing_errors_doc)]
2#![allow(clippy::module_name_repetitions)]
3pub mod aligned;
4pub mod borrowed;
5pub mod encrypted;
6pub mod error;
7pub mod mbuf;
8pub mod owned;
9pub mod serialized;
10pub mod shared;
11pub mod typed;
12pub mod utils;
13pub use aligned::AlignedDataChunk;
14pub use borrowed::BorrowedDataChunk;
15pub use encrypted::EncryptedDataChunk;
16pub use error::PsDataChunkError;
17pub use error::Result;
18pub use mbuf::MbufDataChunk;
19pub use owned::OwnedDataChunk;
20pub use ps_hash::Hash;
21pub use ps_mbuf::Mbuf;
22pub use serialized::SerializedDataChunk;
23pub use shared::SharedDataChunk;
24pub use typed::ToDataChunk;
25pub use typed::ToTypedDataChunk;
26pub use typed::TypedDataChunk;
27
28use std::sync::Arc;
29
30pub trait DataChunk
32where
33 Self: Sized,
34{
35 fn data_ref(&self) -> &[u8];
36 fn hash_ref(&self) -> &Hash;
37
38 fn hash(&self) -> Arc<Hash>;
39
40 fn encrypt(&self) -> Result<EncryptedDataChunk> {
41 self.serialize()?.encrypt()
42 }
43
44 fn decrypt(&self, key: &[u8]) -> Result<SerializedDataChunk> {
45 utils::decrypt(self.data_ref(), key)
46 }
47
48 fn borrow(&self) -> BorrowedDataChunk {
49 BorrowedDataChunk::from_parts(self.data_ref(), self.hash())
50 }
51
52 fn serialize(&self) -> Result<SerializedDataChunk> {
53 SerializedDataChunk::from_parts(self.data_ref(), self.hash())
54 }
55
56 fn into_owned(self) -> OwnedDataChunk {
58 OwnedDataChunk::from_data_and_hash(Arc::from(self.data_ref()), self.hash())
59 }
60
61 fn try_as<T: rkyv::Archive>(self) -> Result<TypedDataChunk<Self, T>>
62 where
63 T::Archived:
64 for<'a> rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'a, rancor::Error>>,
65 {
66 TypedDataChunk::<Self, T>::from_data_chunk(self)
67 }
68}
69
70#[cfg(test)]
71mod tests {
72 use super::*;
73
74 #[test]
75 fn test_encryption_decryption() -> Result<()> {
76 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();
77
78 let data_chunk = BorrowedDataChunk::from_data(&original_data)?;
79
80 let encrypted_chunk = data_chunk.encrypt()?;
81 let decrypted_chunk = encrypted_chunk.decrypt()?;
82
83 assert_eq!(decrypted_chunk.data_ref(), original_data);
84
85 Ok(())
86 }
87
88 #[test]
89 fn test_serialization() -> Result<()> {
90 let original_data = vec![1, 2, 3, 4, 5];
91 let hash = ps_hash::hash(&original_data)?.into();
92 let data_chunk = OwnedDataChunk::from_data_and_hash(original_data.clone(), hash);
93
94 let serialized = data_chunk.serialize()?;
95
96 assert_eq!(serialized.data_ref(), original_data);
97
98 Ok(())
99 }
100}