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 typed;
11pub mod utils;
12pub use aligned::AlignedDataChunk;
13pub use borrowed::BorrowedDataChunk;
14pub use bytes::Bytes;
15pub use cow::CowDataChunk;
16pub use encrypted::EncryptedDataChunk;
17pub use error::DataChunkError;
18pub use error::Result;
19pub use mbuf::MbufDataChunk;
20pub use owned::OwnedDataChunk;
21pub use ps_hash::Hash;
22pub use ps_mbuf::Mbuf;
23pub use typed::ToDataChunk;
24pub use typed::ToTypedDataChunk;
25pub use typed::TypedDataChunk;
26
27use std::sync::Arc;
28
29pub trait DataChunk
41where
42 Self: Sized,
43{
44 fn data_ref(&self) -> &[u8];
46 fn hash_ref(&self) -> &Hash;
48
49 fn hash(&self) -> Hash {
50 *self.hash_ref()
51 }
52
53 fn encrypt(&self) -> Result<EncryptedDataChunk> {
54 Ok(ps_cypher::encrypt(self.data_ref())?.into())
55 }
56
57 fn decrypt(&self, key: &Hash) -> Result<OwnedDataChunk> {
58 utils::decrypt(self.data_ref(), key)
59 }
60
61 fn borrow(&self) -> BorrowedDataChunk<'_> {
62 BorrowedDataChunk::from_parts_unchecked(self.data_ref(), self.hash())
63 }
64
65 fn into_bytes(self) -> Bytes {
67 Bytes::from_owner(Arc::from(self.data_ref()))
68 }
69
70 fn into_owned(self) -> OwnedDataChunk {
72 OwnedDataChunk::from_data_and_hash_unchecked(Arc::from(self.data_ref()), self.hash())
73 }
74
75 fn try_as<T: rkyv::Archive>(self) -> Result<TypedDataChunk<Self, T>>
76 where
77 T::Archived:
78 for<'a> rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'a, rancor::Error>>,
79 {
80 TypedDataChunk::<Self, T>::from_data_chunk(self)
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 #[test]
90 fn test_encryption_decryption() -> Result<()> {
91 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();
92
93 let data_chunk = BorrowedDataChunk::from_data(&original_data)?;
94
95 let encrypted_chunk = data_chunk.encrypt()?;
96 let decrypted_chunk = encrypted_chunk.decrypt()?;
97
98 assert_eq!(decrypted_chunk.data_ref(), original_data);
99
100 Ok(())
101 }
102}