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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
use async_once_cell::Lazy;
use async_trait::async_trait;
use std::future::Future;
use std::pin::Pin;
#[async_trait(?Send)]
pub trait AsyncAccessor {
type Value;
type Error;
async fn get_value(&self) -> Result<Self::Value, Self::Error>;
}
pub struct StaticValue<T, E> {
value: T,
__error: std::marker::PhantomData<E>,
}
impl<T, E> StaticValue<T, E> {
pub fn new(value: T) -> Self {
Self {
value,
__error: Default::default(),
}
}
}
#[async_trait(?Send)]
impl<T: Clone, E> AsyncAccessor for StaticValue<T, E> {
type Value = T;
type Error = E;
async fn get_value(&self) -> Result<Self::Value, Self::Error> {
Ok(self.value.clone())
}
}
type BoxedResultFuture<T, E> = Pin<Box<dyn Future<Output = Result<T, E>>>>;
pub struct LazyValue<T, E> {
value: Lazy<Result<T, E>, BoxedResultFuture<T, E>>,
}
impl<T, E> LazyValue<T, E> {
pub fn new(f: impl Future<Output = Result<T, E>> + 'static) -> Self {
Self {
value: Lazy::new(Box::pin(f)),
}
}
}
#[async_trait(?Send)]
impl<T: Clone + Unpin, E: Clone + Unpin> AsyncAccessor for LazyValue<T, E> {
type Value = T;
type Error = E;
async fn get_value(&self) -> Result<Self::Value, Self::Error> {
(*Lazy::get(Pin::new(&self.value)).await).clone()
}
}
#[async_trait(?Send)]
impl<T, E> AsyncAccessor for Box<dyn AsyncAccessor<Value = T, Error = E>> {
type Value = T;
type Error = E;
async fn get_value(&self) -> Result<Self::Value, Self::Error> {
(**self).get_value().await
}
}
#[cfg(test)]
mod tests {
use std::{
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use super::{AsyncAccessor, LazyValue};
#[tokio::test]
async fn test_lazy_value_only_runs_when_called() {
let called = Arc::new(AtomicBool::new(false));
let value: LazyValue<usize, ()> = LazyValue::new({
let called = called.clone();
async move {
called.store(true, Ordering::Relaxed);
Ok(10)
}
});
tokio::time::sleep(Duration::from_millis(10)).await;
assert_eq!(called.load(Ordering::Relaxed), false);
let value = value.get_value().await;
assert_eq!(value, Ok(10));
assert!(called.load(Ordering::Relaxed));
}
}