ps_hkey/store/
mod.rs

1pub mod combined;
2pub mod in_memory;
3
4use ps_cypher::validate_ecc;
5use ps_datachunk::{BorrowedDataChunk, DataChunk, PsDataChunkError};
6use ps_hash::Hash;
7
8use crate::{
9    constants::{MAX_DECRYPTED_SIZE, MAX_ENCRYPTED_SIZE, MAX_SIZE_RAW},
10    Hkey, LongHkeyExpanded, PsHkeyError,
11};
12
13pub trait Store
14where
15    Self: Sized + Sync,
16{
17    type Chunk<'c>: DataChunk
18    where
19        Self: 'c;
20
21    type Error: From<PsDataChunkError> + From<PsHkeyError> + Send;
22
23    fn get<'a>(&'a self, hash: &Hash) -> Result<Self::Chunk<'a>, Self::Error>;
24
25    fn put_encrypted<C: DataChunk>(&self, chunk: C) -> Result<(), Self::Error>;
26
27    fn put(&self, data: &[u8]) -> Result<Hkey, Self::Error> {
28        if data.len() <= MAX_SIZE_RAW {
29            return Ok(Hkey::Raw(data.into()));
30        }
31
32        if data.len() <= MAX_ENCRYPTED_SIZE && validate_ecc(data) {
33            let chunk = BorrowedDataChunk::from_data(data)?;
34            let hash = chunk.hash();
35
36            self.put_encrypted(chunk)?;
37
38            Ok(Hkey::Direct(hash))
39        } else if data.len() <= MAX_DECRYPTED_SIZE {
40            let chunk = BorrowedDataChunk::from_data(data)?;
41            let encrypted = chunk.encrypt()?;
42            let hkey = Hkey::Encrypted(encrypted.hash(), encrypted.key());
43
44            self.put_encrypted(encrypted)?;
45
46            Ok(hkey)
47        } else {
48            LongHkeyExpanded::from_blob(self, data)?.shrink(self)
49        }
50    }
51}