object_rainbow/
fn_fetch.rs1use crate::*;
2
3pub struct FnFetch<F> {
4 fetch: F,
5}
6
7pub trait FetchFn: Send + Sync {
8 type T;
9 fn fetch(&self) -> impl Send + Future<Output = Result<Self::T>>;
10}
11
12impl<F: Send + Sync + Fn() -> Fut, Fut: Send + Future<Output = Result<T>>, T> FetchFn for F {
13 type T = T;
14
15 fn fetch(&self) -> impl Send + Future<Output = Result<Self::T>> {
16 self()
17 }
18}
19
20impl<F: FetchFn> FnFetch<F> {
21 pub fn new(fetch: F) -> Self {
22 Self { fetch }
23 }
24
25 pub async fn fetch(&self) -> Result<F::T> {
26 self.fetch.fetch().await
27 }
28}
29
30impl<F: FetchFn<T: Traversible>> FetchBytes for FnFetch<F> {
31 fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
32 Box::pin(async move { Ok(self.fetch().await?.byte_node()) })
33 }
34
35 fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
36 Box::pin(async move { Ok(self.fetch().await?.vec()) })
37 }
38}
39
40impl<F: FetchFn<T: Traversible>> Fetch for FnFetch<F> {
41 type T = F::T;
42
43 fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
44 Box::pin(async move { self.fetch().await })
45 }
46}
47
48pub trait ClosureFn<'a, Closure: 'a>: Send + Sync + Fn(&'a Closure) -> Self::Fut {
49 type T;
50 type Fut: Send + Future<Output = Result<Self::T>>;
51 fn fetch(&'a self, closure: &'a Closure) -> Self::Fut;
52}
53
54impl<
55 'a,
56 Closure: 'a,
57 F: Send + Sync + Fn(&'a Closure) -> Fut,
58 Fut: Send + Future<Output = Result<T>>,
59 T,
60> ClosureFn<'a, Closure> for F
61{
62 type T = T;
63 type Fut = Fut;
64
65 fn fetch(&'a self, closure: &'a Closure) -> Self::Fut {
66 self(closure)
67 }
68}
69
70pub trait ClosureFetch<Closure>: Send + Sync {
71 type T;
72 fn fetch(&self, closure: &Closure) -> impl Send + Future<Output = Result<Self::T>>;
73}
74
75impl<Closure: Send + Sync, F: for<'a> ClosureFn<'a, Closure, T = T>, T> ClosureFetch<Closure>
76 for F
77{
78 type T = T;
79
80 async fn fetch(&self, closure: &Closure) -> Result<Self::T> {
81 self.fetch(closure).await
82 }
83}
84
85impl<Closure: Send + Sync, F: ClosureFetch<Closure>> FetchFn for (Closure, F) {
86 type T = F::T;
87
88 fn fetch(&self) -> impl Send + Future<Output = Result<Self::T>> {
89 self.1.fetch(&self.0)
90 }
91}
92
93pub fn closure_fetch<
94 Closure: Send + Sync,
95 F: ClosureFetch<Closure> + AsyncFn(&Closure) -> Result<F::T>,
96>(
97 closure: Closure,
98 f: F,
99) -> (Closure, F) {
100 (closure, f)
101}