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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use crux_core::{
capability::{CapabilityContext, Operation},
Capability,
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum KeyValueOperation {
Read(String),
Write(String, Vec<u8>),
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum KeyValueOutput {
Read(Option<Vec<u8>>),
Write(bool),
}
impl Operation for KeyValueOperation {
type Output = KeyValueOutput;
}
pub struct KeyValue<Ev> {
context: CapabilityContext<KeyValueOperation, Ev>,
}
impl<Ev> KeyValue<Ev>
where
Ev: 'static,
{
pub fn new(context: CapabilityContext<KeyValueOperation, Ev>) -> Self {
Self { context }
}
pub fn read<F>(&self, key: &str, make_event: F)
where
F: Fn(KeyValueOutput) -> Ev + Send + Sync + 'static,
{
let ctx = self.context.clone();
let key = key.to_string();
self.context.spawn(async move {
let output = ctx.request_from_shell(KeyValueOperation::Read(key)).await;
ctx.update_app(make_event(output))
});
}
pub fn write<F>(&self, key: &str, value: Vec<u8>, make_event: F)
where
F: Fn(KeyValueOutput) -> Ev + Send + Sync + 'static,
{
self.context.spawn({
let context = self.context.clone();
let key = key.to_string();
async move {
let resp = context
.request_from_shell(KeyValueOperation::Write(key, value))
.await;
context.update_app(make_event(resp))
}
});
}
}
impl<Ef> Capability<Ef> for KeyValue<Ef> {
type Operation = KeyValueOperation;
type MappedSelf<MappedEv> = KeyValue<MappedEv>;
fn map_event<F, NewEvent>(&self, f: F) -> Self::MappedSelf<NewEvent>
where
F: Fn(NewEvent) -> Ef + Send + Sync + Copy + 'static,
Ef: 'static,
NewEvent: 'static,
{
KeyValue::new(self.context.map_event(f))
}
}