Skip to main content

ps_datachunk/encrypted/
mod.rs

1mod implementations;
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: Hash,
18    key: Hash,
19}
20
21impl EncryptedDataChunk {
22    /// Decrypts this `EncryptedDataChunk`.
23    pub fn decrypt(&self) -> Result<SerializedDataChunk> {
24        utils::decrypt(self.data_ref(), &self.key)
25    }
26
27    #[must_use]
28    pub const fn key(&self) -> Hash {
29        self.key
30    }
31
32    #[must_use]
33    pub const fn key_ref(&self) -> &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
46    /// Transforms this [`DataChunk`] into [`Bytes`].
47    fn into_bytes(self) -> Bytes {
48        Bytes::from_owner(SharedBuffer::from(self.data))
49    }
50
51    /// Transforms this chunk into an [`crate::OwnedDataChunk`]
52    fn into_owned(self) -> crate::OwnedDataChunk {
53        let Self { data, hash, key: _ } = self;
54
55        crate::OwnedDataChunk::from_data_and_hash_unchecked(data, hash)
56    }
57}
58
59impl From<Encrypted> for EncryptedDataChunk {
60    fn from(value: Encrypted) -> Self {
61        Self {
62            data: value.bytes,
63            hash: value.hash,
64            key: value.key,
65        }
66    }
67}