Created
March 16, 2023 16:53
-
-
Save shtsoft/829e2f161fda0dd0892b521febe6624b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mod async_await { | |
use std::sync::mpsc::channel; | |
use std::sync::mpsc::Receiver; | |
use std::thread; | |
use std::time::Duration; | |
pub trait AsyncAwait<B, C> { | |
type Promise<X>; | |
fn asynchronous<K>(self, asynchronous_b: fn() -> B, k: K) -> C | |
where | |
K: FnOnce(Self::Promise<B>) -> C, | |
Self: Sized; | |
fn awaiting<K>(self, promise_b: Self::Promise<B>, k: K) -> C | |
where | |
K: FnOnce(B) -> C; | |
} | |
#[derive(Copy, Clone)] | |
pub struct Channel {} | |
impl<B: Send + 'static, C> AsyncAwait<B, C> for Channel { | |
type Promise<X> = Receiver<X>; | |
fn asynchronous<K>(self, asynchronous_b: fn() -> B, k: K) -> C | |
where | |
K: FnOnce(Self::Promise<B>) -> C, | |
{ | |
let (tx, rx) = channel(); | |
thread::spawn(move || { | |
tx.send(asynchronous_b()).unwrap(); | |
}); | |
k(rx) | |
} | |
fn awaiting<K>(self, promise_b: Self::Promise<B>, k: K) -> C | |
where | |
K: FnOnce(B) -> C, | |
{ | |
let b = promise_b.recv().unwrap(); | |
k(b) | |
} | |
} | |
pub fn download_doing_stuff(async_handler: impl AsyncAwait<usize, ()> + Copy) { | |
fn download() -> usize { | |
for i in 1..10 { | |
println!("Progress: {}", i * 10); | |
thread::sleep(Duration::from_millis(500)); | |
} | |
1000 | |
} | |
fn do_stuff() { | |
println!("Begin doing stuff."); | |
thread::sleep(Duration::from_millis(2000)); | |
println!("End doing stuff."); | |
} | |
fn do_other_stuff(size: usize) { | |
println!("Size: {size}"); | |
} | |
async_handler.asynchronous(download, |size_promise| { | |
do_stuff(); | |
async_handler.awaiting(size_promise, do_other_stuff); | |
}); | |
} | |
} | |
use async_await::*; | |
fn main() { | |
download_doing_stuff(Channel {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment