Skip to main content

object_rainbow/
fn_fetch.rs

1use 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    async fn fetch_node(&self) -> Result<Node<F::T>>
30    where
31        F::T: Traversible,
32    {
33        let object = self.fetch().await?;
34        let resolve = object.to_resolve();
35        Ok((object, resolve))
36    }
37}
38
39impl<F: FetchFn<T: Traversible>> FetchBytes for FnFetch<F> {
40    fn fetch_bytes(&'_ self) -> FailFuture<'_, ByteNode> {
41        Box::pin(async move {
42            let (object, resolve) = self.fetch_node().await?;
43            let data = object.output();
44            Ok((data, resolve))
45        })
46    }
47
48    fn fetch_data(&'_ self) -> FailFuture<'_, Vec<u8>> {
49        Box::pin(async move { Ok(self.fetch().await?.output()) })
50    }
51}
52
53impl<F: FetchFn<T: Traversible>> Fetch for FnFetch<F> {
54    type T = F::T;
55
56    fn fetch(&'_ self) -> FailFuture<'_, Self::T> {
57        Box::pin(async move { self.fetch().await })
58    }
59}
60
61pub trait ClosureFn<'a, Closure: 'a>: Send + Sync + Fn(&'a Closure) -> Self::Fut {
62    type T;
63    type Fut: Send + Future<Output = Result<Self::T>>;
64    fn fetch(&'a self, closure: &'a Closure) -> Self::Fut;
65}
66
67impl<
68    'a,
69    Closure: 'a,
70    F: Send + Sync + Fn(&'a Closure) -> Fut,
71    Fut: Send + Future<Output = Result<T>>,
72    T,
73> ClosureFn<'a, Closure> for F
74{
75    type T = T;
76    type Fut = Fut;
77
78    fn fetch(&'a self, closure: &'a Closure) -> Self::Fut {
79        self(closure)
80    }
81}
82
83pub trait ClosureFetch<Closure>: Send + Sync {
84    type T;
85    fn fetch(&self, closure: &Closure) -> impl Send + Future<Output = Result<Self::T>>;
86}
87
88impl<Closure: Send + Sync, F: for<'a> ClosureFn<'a, Closure, T = T>, T> ClosureFetch<Closure>
89    for F
90{
91    type T = T;
92
93    async fn fetch(&self, closure: &Closure) -> Result<Self::T> {
94        self.fetch(closure).await
95    }
96}
97
98impl<Closure: Send + Sync, F: ClosureFetch<Closure>> FetchFn for (Closure, F) {
99    type T = F::T;
100
101    fn fetch(&self) -> impl Send + Future<Output = Result<Self::T>> {
102        self.1.fetch(&self.0)
103    }
104}
105
106pub fn closure_fetch<
107    Closure: Send + Sync,
108    F: ClosureFetch<Closure> + AsyncFn(&Closure) -> Result<F::T>,
109>(
110    closure: Closure,
111    f: F,
112) -> (Closure, F) {
113    (closure, f)
114}