mirror of
https://github.com/guilhermewerner/mini-redis
synced 2025-06-16 23:15:06 +00:00
Implement Some Tokio Tutorials
This commit is contained in:
55
Tutorial/Future.rs
Normal file
55
Tutorial/Future.rs
Normal file
@ -0,0 +1,55 @@
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use futures::future::poll_fn;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
struct Delay {
|
||||
when: Instant,
|
||||
}
|
||||
|
||||
impl Future for Delay {
|
||||
type Output = &'static str;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<&'static str> {
|
||||
if Instant::now() >= self.when {
|
||||
println!("Hello world");
|
||||
Poll::Ready("done")
|
||||
} else {
|
||||
// Ignore this line for now.
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let when = Instant::now() + Duration::from_millis(10);
|
||||
let mut delay = Some(Delay { when });
|
||||
|
||||
poll_fn(move |cx| {
|
||||
let mut delay = delay.take().unwrap();
|
||||
let res = Pin::new(&mut delay).poll(cx);
|
||||
assert!(res.is_pending());
|
||||
tokio::spawn(async move {
|
||||
delay.await;
|
||||
});
|
||||
|
||||
Poll::Ready(())
|
||||
})
|
||||
.await;
|
||||
|
||||
/*
|
||||
let when = Instant::now() + Duration::from_millis(1000);
|
||||
let future = Delay { when };
|
||||
|
||||
let out = future.await;
|
||||
assert_eq!(out, "done");
|
||||
|
||||
let when = Instant::now() + Duration::from_millis(10);
|
||||
let mut delay = Some(Delay { when });
|
||||
*/
|
||||
}
|
Reference in New Issue
Block a user