ps_datachunk/encrypted/
mod.rs

1use std::sync::Arc;
2
3use crate::utils;
4use crate::DataChunk;
5use crate::Result;
6use crate::SerializedDataChunk;
7use bytes::Bytes;
8use ps_buffer::Buffer;
9use ps_buffer::SharedBuffer;
10use ps_cypher::Encrypted;
11use ps_hash::Hash;
12
13#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
14/// represents an encrypted chunk of data and the key needed to decrypt it
15pub struct EncryptedDataChunk {
16    data: Buffer,
17    hash: Arc<Hash>,
18    key: Arc<Hash>,
19}
20
21impl EncryptedDataChunk {
22    /// Decrypts this `EncryptedDataChunk`.
23    pub fn decrypt(&self) -> Result<SerializedDataChunk> {
24        utils::decrypt(self.data_ref(), self.key.as_bytes())
25    }
26
27    #[must_use]
28    pub fn key(&self) -> Arc<Hash> {
29        self.key.clone()
30    }
31
32    #[must_use]
33    pub const fn key_ref(&self) -> &Arc<Hash> {
34        &self.key
35    }
36}
37
38impl DataChunk for EncryptedDataChunk {
39    fn data_ref(&self) -> &[u8] {
40        &self.data
41    }
42    fn hash_ref(&self) -> &Hash {
43        &self.hash
44    }
45    fn hash(&self) -> Arc<Hash> {
46        self.hash.clone()
47    }
48
49    /// Transforms this [`DataChunk`] into [`Bytes`].
50    fn into_bytes(self) -> Bytes {
51        Bytes::from_owner(SharedBuffer::from(self.data))
52    }
53
54    /// Transforms this chunk into an [`OwnedDataChunk`]
55    fn into_owned(self) -> crate::OwnedDataChunk {
56        let Self { data, hash, key: _ } = self;
57
58        crate::OwnedDataChunk::from_data_and_hash(data, hash)
59    }
60}
61
62impl From<Encrypted> for EncryptedDataChunk {
63    fn from(value: Encrypted) -> Self {
64        Self {
65            data: value.bytes,
66            hash: value.hash,
67            key: value.key,
68        }
69    }
70}