Skip to main content

ps_hkey/store/
in_memory.rs

1use std::{
2    collections::HashMap,
3    sync::{Arc, Mutex, PoisonError},
4};
5
6use ps_datachunk::{DataChunk, DataChunkError, OwnedDataChunk};
7use ps_hash::{Hash, HashError};
8
9use crate::HkeyError;
10
11use super::Store;
12
13#[derive(Clone, Debug, Default)]
14pub struct InMemoryStore {
15    hashmap: Arc<Mutex<HashMap<Hash, OwnedDataChunk>>>,
16}
17
18#[derive(thiserror::Error, Debug)]
19pub enum InMemoryStoreError {
20    #[error(transparent)]
21    DataChunk(#[from] DataChunkError),
22    #[error(transparent)]
23    Hash(#[from] HashError),
24    #[error(transparent)]
25    Hkey(#[from] HkeyError),
26    #[error("The internal mutex was poisoned.")]
27    MutexPoison,
28    #[error("The data with this hash was not found.")]
29    NotFound,
30}
31
32impl<T> From<PoisonError<T>> for InMemoryStoreError {
33    fn from(_: PoisonError<T>) -> Self {
34        Self::MutexPoison
35    }
36}
37
38impl Store for InMemoryStore {
39    type Chunk<'c> = OwnedDataChunk;
40    type Error = InMemoryStoreError;
41
42    fn get<'a>(&'a self, hash: &Hash) -> Result<Self::Chunk<'a>, Self::Error> {
43        self.hashmap
44            .lock()?
45            .get(hash)
46            .cloned()
47            .ok_or(InMemoryStoreError::NotFound)
48    }
49
50    fn put_encrypted<C: DataChunk>(&self, chunk: C) -> Result<(), Self::Error> {
51        let chunk = chunk.into_owned();
52        let hash = *chunk.hash_ref();
53
54        self.hashmap.lock()?.insert(hash, chunk);
55
56        Ok(())
57    }
58}