use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
pub struct DelayFuture {
duration: Duration,
start_time: Option<std::time::Instant>,
}
impl DelayFuture {
pub fn new(duration: Duration) -> Self {
DelayFuture {
duration,
start_time: None,
}
}
}
impl Future for DelayFuture {
type Output = ();
fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
let start_time = self.start_time.get_or_insert_with(std::time::Instant::now);
if start_time.elapsed() >= self.duration {
Poll::Ready(())
} else {
Poll::Pending
}
}
}
pub struct ComputeFuture {
value: Option<i32>,
}
impl ComputeFuture {
pub fn new(value: i32) -> Self {
ComputeFuture { value: Some(value) }
}
}
impl Future for ComputeFuture {
type Output = i32;
fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.value.take() {
Some(value) => {
let result = value * 2 + 1;
Poll::Ready(result)
}
None => Poll::Pending,
}
}
}
pub fn async_examples() {
println!("\nโก Async Examples");
println!("{}", "-".repeat(18));
println!("Async programming concepts demonstrated");
println!("Use tokio or async-std for real async code");
show_async_signatures();
demonstrate_future_creation();
show_async_patterns();
async_error_handling_concepts();
}
fn show_async_signatures() {
println!("\n๐ Async Function Signatures");
println!("{}", "-".repeat(30));
println!("async fn simple_async() -> i32 {{ 42 }}");
println!("async fn async_with_params(x: i32, y: i32) -> i32 {{ x + y }}");
println!("async fn async_with_result() -> Result<String, &'static str> {{ ... }}");
}
fn demonstrate_future_creation() {
println!("\n๐ง Future Creation");
println!("{}", "-".repeat(20));
let _delay_future = DelayFuture::new(Duration::from_millis(100));
let _compute_future = ComputeFuture::new(21);
println!("Created DelayFuture and ComputeFuture");
println!("In an async runtime, these would be awaited:");
println!(" delay_future.await;");
println!(" let result = compute_future.await;");
}
fn show_async_patterns() {
println!("\n๐ญ Async Patterns");
println!("{}", "-".repeat(20));
println!("1. Sequential execution:");
println!(" let a = first_async().await;");
println!(" let b = second_async(a).await;");
println!("\n2. Concurrent execution:");
println!(" let (a, b) = tokio::join!(first_async(), second_async());");
}
fn async_error_handling_concepts() {
println!("\nโ Async Error Handling");
println!("{}", "-".repeat(25));
println!("1. Result types in async functions:");
println!(" async fn may_fail() -> Result<i32, MyError> {{ ... }}");
println!("\n2. Using ? operator:");
println!(" let value = may_fail().await?;");
}
async fn fetch_data(id: u32) -> Result<String, &'static str> {
if id == 0 {
Err("Invalid ID")
} else {
Ok(format!("Data for ID: {}", id))
}
}
async fn process_items(items: Vec<u32>) -> Vec<Result<String, &'static str>> {
let mut results = Vec::new();
for item in items {
results.push(fetch_data(item).await);
}
results
}
async fn process_stream() {
println!("\n๐ Stream Processing Concepts");
println!("{}", "-".repeat(30));
println!("Streams are async iterators:");
println!("use futures::stream::{{self, StreamExt}};");
}
async fn channel_communication() {
println!("\n๐ก Channel Communication");
println!("{}", "-".repeat(25));
println!("Async channels for communication:");
println!("use tokio::sync::mpsc;");
}
fn async_traits_concepts() {
println!("\n๐ฏ Async Traits");
println!("{}", "-".repeat(15));
println!("Async traits (using async-trait crate):");
println!("#[async_trait]");
println!("trait AsyncProcessor {{");
println!(" async fn process(&self, data: &str) -> Result<String, Error>;");
println!("}}");
}
fn async_testing_concepts() {
println!("\n๐งช Async Testing");
println!("{}", "-".repeat(20));
println!("Testing async functions:");
println!("#[tokio::test]");
println!("async fn test_async_function() {{");
println!(" let result = my_async_function().await;");
println!(" assert_eq!(result, expected_value);");
println!("}}");
}
fn real_world_patterns() {
println!("\n๐ Real-World Async Patterns");
println!("{}", "-".repeat(35));
println!("1. HTTP Client:");
println!(" let response = reqwest::get(\"https://api.example.com\")");
println!(" .await?");
println!(" .json::<MyStruct>()");
println!(" .await?;");
}