forked from ucan-wg/rs-ucan
/
memory.rs
73 lines (66 loc) · 2.17 KB
/
memory.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use super::Store;
use crate::{crypto::varsig, did::Did, invocation::Invocation};
use libipld_core::{cid::Cid, codec::Codec};
use std::sync::{Arc, Mutex, MutexGuard};
use std::{collections::BTreeMap, convert::Infallible};
#[derive(Debug, Clone)]
pub struct MemoryStore<
T = crate::ability::preset::Preset,
DID: crate::did::Did = crate::did::preset::Verifier,
V: varsig::Header<C> = varsig::header::Preset,
C: Codec + TryFrom<u64> + Into<u64> = varsig::encoding::Preset,
> {
inner: Arc<Mutex<MemoryStoreInner<T, DID, V, C>>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MemoryStoreInner<
T = crate::ability::preset::Preset,
DID: crate::did::Did = crate::did::preset::Verifier,
V: varsig::Header<C> = varsig::header::Preset,
C: Codec + TryFrom<u64> + Into<u64> = varsig::encoding::Preset,
> {
store: BTreeMap<Cid, Arc<Invocation<T, DID, V, C>>>,
}
impl<T, DID: Did, V: varsig::Header<Enc>, Enc: Codec + Into<u64> + TryFrom<u64>>
MemoryStore<T, DID, V, Enc>
{
fn lock(&self) -> MutexGuard<'_, MemoryStoreInner<T, DID, V, Enc>> {
match self.inner.lock() {
Ok(guard) => guard,
Err(poison) => {
// There's no logic errors through lock poisoning in our case
poison.into_inner()
}
}
}
}
impl<T, DID: Did, V: varsig::Header<Enc>, Enc: Codec + Into<u64> + TryFrom<u64>> Default
for MemoryStore<T, DID, V, Enc>
{
fn default() -> Self {
Self {
inner: Arc::new(Mutex::new(MemoryStoreInner {
store: BTreeMap::new(),
})),
}
}
}
impl<T, DID: Did, V: varsig::Header<Enc>, Enc: Codec + Into<u64> + TryFrom<u64>>
Store<T, DID, V, Enc> for MemoryStore<T, DID, V, Enc>
{
type InvocationStoreError = Infallible;
fn get(
&self,
cid: Cid,
) -> Result<Option<Arc<Invocation<T, DID, V, Enc>>>, Self::InvocationStoreError> {
Ok(self.lock().store.get(&cid).cloned())
}
fn put(
&self,
cid: Cid,
invocation: Invocation<T, DID, V, Enc>,
) -> Result<(), Self::InvocationStoreError> {
self.lock().store.insert(cid, Arc::new(invocation));
Ok(())
}
}