backblaze_b2_client/util/
callback.rs1use std::{future::Future, sync::Arc};
2
3use futures::{future::BoxFuture, FutureExt};
4
5pub enum B2Callback<T: Sync + Send + 'static> {
6 Fn(Box<dyn Fn(T) + Send + Sync>),
7 AsyncFn(Box<dyn Fn(T) -> BoxFuture<'static, ()> + Send + Sync>),
8}
9
10impl<T: Sync + Send + 'static> B2Callback<T> {
11 pub fn from_fn<F>(fun: F) -> Self
13 where
14 F: Fn(T) + Send + Sync + 'static,
15 {
16 B2Callback::Fn(Box::new(fun))
17 }
18
19 pub fn from_async_fn<F, R>(fun: F) -> Self
21 where
22 F: Fn(T) -> R + Send + Sync + 'static,
23 R: Future<Output = ()> + Send + 'static,
24 {
25 let fun = Arc::new(fun);
26 B2Callback::AsyncFn(Box::new(move |bytes| {
27 let fun = fun.clone();
28 async move {
29 let fun = fun.clone();
30 fun(bytes).await;
31 }
32 .boxed()
33 }))
34 }
35}