### Rust Tokio Mini-Redis Client Example Source: https://rust-lang.github.io/async-book/part-guide/async-await An example demonstrating interaction with a mini-redis server using Rust and Tokio. It shows connecting to the server, setting a key-value pair, and retrieving the value, utilizing `.await` for asynchronous operations and `?` for error handling. ```rust use mini_redis_project::client; use std::io::{self, Result}; #[tokio::main] async fn main() -> Result<()> { let mut client = client::connect("127.0.0.1:6379").await?; client.set("hello", "world".into()).await?; let result = client.get("hello").await?; println!("got value from the server; result={:?}", result); Ok(()) } ``` -------------------------------- ### Rust Async Timer Future Setup Source: https://rust-lang.github.io/async-book/02_execution/03_wakeups Sets up the necessary imports for creating an asynchronous timer future in Rust. Includes standard library components for futures, concurrency, and time. ```Rust #![allow(unused)] fn main() { use std::{ future::Future, pin::Pin, sync::{Arc, Mutex}, task::{Context, Poll, Waker}, thread, time::Duration, }; } ``` -------------------------------- ### Rust Async Function and Await Example Source: https://rust-lang.github.io/async-book/part-guide/async-await Demonstrates basic Rust async functions, one that performs immediate addition and another that simulates a delay using `sleep` before adding. The `await` keyword is used to get the result from these futures. This example requires the `sleep` function to be available in the scope, typically from an async runtime. ```Rust #![allow(unused)] fn main() { // An async function, but it doesn't need to wait for anything. async fn add(a: u32, b: u32) -> u32 { a + b } async fn wait_to_add(a: u32, b: u32) -> u32 { sleep(1000).await; // Assuming sleep is available and takes milliseconds a + b } } ``` -------------------------------- ### Async Function Variable Pinning Example (Rust) Source: https://rust-lang.github.io/async-book/part-reference/pinning Illustrates how variables within an async function might be captured and saved across await points, potentially forming fields of a generated future struct. This example shows a simple async function `foo` with local variables `a` and `b`, where `b` is a reference to `a`. ```rust #![allow(unused)] fn main() { async fn foo() { let a = ...; let b = &a; bar().await; // use b } } ``` -------------------------------- ### Sequential Execution Example in Rust Source: https://rust-lang.github.io/async-book/part-guide/concurrency Demonstrates a basic sequential code execution flow in Rust. Each statement completes before the next begins, illustrating a common programming pattern but highlighting potential inefficiencies due to waiting for I/O operations. ```rust do_a_thing(); println!("hello!"); do_another_thing(); ``` -------------------------------- ### Rust Tokio Sequential Async Sleep Example Source: https://rust-lang.github.io/async-book/part-guide/async-await Illustrates sequential execution in asynchronous Rust using Tokio. The example defines two async functions, `say_hello` and `say_world`, separated by a one-second sleep, showing that awaiting tasks does not introduce concurrency on its own. ```rust use std::io::{stdout, Write}; use tokio::time::{sleep, Duration}; async fn say_hello() { print!("hello, "); stdout().flush().unwrap(); } async fn say_world() { println!("world!"); } #[tokio::main] async fn main() { say_hello().await; sleep(Duration::from_millis(1000)).await; say_world().await; } ``` -------------------------------- ### Example Usage of Futures Executor with async/await Source: https://rust-lang.github.io/async-book/02_execution/04_executor The `main` function demonstrates how to use the custom futures executor. It creates an executor and spawner, spawns an asynchronous task that prints messages and awaits a `TimerFuture`, and then runs the executor until all tasks are completed. Dropping the spawner signals the executor to finish. ```rust fn main() { let (executor, spawner) = new_executor_and_spawner(); // Spawn a task to print before and after waiting on a timer. spawner.spawn(async { println!("howdy!"); // Wait for our timer future to complete after two seconds. TimerFuture::new(Duration::new(2, 0)).await; println!("done!"); }); // Drop the spawner so that our executor knows it is finished and won't // receive more incoming tasks to run. drop(spawner); // Run the executor until the task queue is empty. // This will print "howdy!", pause, and then print "done!". executor.run(); } ``` -------------------------------- ### Hello World Async Function in Rust Source: https://rust-lang.github.io/async-book/intro A basic example demonstrating how to define and call an asynchronous function in Rust. It uses `async fn` to define the function and `.await` to execute it. The `#[tokio::main]` attribute is used as boilerplate to enable an async main function, which will be explained later in the book. This snippet assumes the `tokio` runtime. ```rust // Define an async function. async fn say_hello() { println!("hello, world!"); } #[tokio::main] // Boilerplate which lets us write `async fn main`, we'll explain it later. async fn main() { // Call an async function and await its result. say_hello().await; } ``` -------------------------------- ### Rust mpsc Channel Stream Example Source: https://rust-lang.github.io/async-book/05_streams/01_chapter Demonstrates the usage of a multi-producer, single-consumer (mpsc) channel in Rust as a `Stream`. This example shows sending values, dropping the sender, and receiving values until the stream completes. ```rust async fn send_recv() { const BUFFER_SIZE: usize = 10; let (mut tx, mut rx) = mpsc::channel::(BUFFER_SIZE); tx.send(1).await.unwrap(); tx.send(2).await.unwrap(); drop(tx); // `StreamExt::next` is similar to `Iterator::next`, but returns a // type that implements `Future>`. assert_eq!(Some(1), rx.next().await); assert_eq!(Some(2), rx.next().await); assert_eq!(None, rx.next().await); } ``` -------------------------------- ### Rust Projection Method Signatures for Pinning Source: https://rust-lang.github.io/async-book/part-reference/pinning Demonstrates the two possible signatures for projection methods used with Rust's `Pin` type. The choice of signature depends on whether the field exhibits 'structural pinning'. Implementing these requires `unsafe` code due to safety implications. ```rust /// Structurally pinned field fn get_field(self: Pin<&mut Self>) -> Pin<&mut Field>; /// Non-structurally pinned field fn get_field(self: Pin<&mut Self>) -> &mut Field; ``` -------------------------------- ### Unit Test Async Code with Tokio Source: https://rust-lang.github.io/async-book/part-guide/more-async-await Demonstrates how to unit test asynchronous Rust code using the `#[tokio::test]` attribute. This allows for the use of `await` within test functions, simplifying the testing of async logic. Configuration options are available in the Tokio documentation. ```rust #![allow(unused)] fn main() { #[tokio::test] async fn test_something() { // Write a test here, including all the `await`s you like. } } ``` -------------------------------- ### Sequentially Block on Futures in Rust Source: https://rust-lang.github.io/async-book/print Illustrates a less efficient way to execute asynchronous tasks by sequentially calling `block_on` for each `Future`. This approach does not allow for concurrent execution, as each task must complete before the next one starts. ```rust fn main() { let song = block_on(learn_song()); block_on(sing_song(song)); block_on(dance()); } ``` -------------------------------- ### Rust Async Hello World with Tokio Source: https://rust-lang.github.io/async-book/part-guide/async-await A basic asynchronous 'hello, world!' program in Rust using the Tokio runtime. It defines an async function `say_hello` and calls it within an async `main` function, demonstrating the use of `.await`. ```rust #[tokio::main] async fn main() { say_hello().await; } async fn say_hello() { println!("hello, world!"); } ``` -------------------------------- ### Rust: select! with streams using next() Source: https://rust-lang.github.io/async-book/06_multiple_futures/03_select Shows how to use the `select!` macro with streams. It processes items from two streams concurrently, summing their values until both streams are exhausted. This example highlights the use of `FusedStream` and `Unpin` traits. ```rust #![allow(unused)] fn main() { use futures::{ stream::{Stream, StreamExt, FusedStream}, select, }; // Function to add elements from two streams using select! async fn add_two_streams( mut s1: impl Stream + FusedStream + Unpin, // First stream, must be Fused and Unpin mut s2: impl Stream + FusedStream + Unpin, // Second stream, must be Fused and Unpin ) -> u8 { let mut total = 0; loop { // Select the next item from either stream or break if both are complete let item = select! { x = s1.next() => x, // Get next item from s1, assign to x x = s2.next() => x, // Get next item from s2, assign to x complete => break, // Break the loop when both streams are exhausted }; if let Some(next_num) = item { total += next_num; // Add the received number to the total } } total // Return the accumulated total } } ``` -------------------------------- ### Concurrent Await with futures::join! in Rust Source: https://rust-lang.github.io/async-book/06_multiple_futures/02_join Shows the correct method for concurrently awaiting multiple futures in Rust using the `futures::join!` macro. This ensures that operations start and run in parallel, significantly improving performance. ```rust use futures::join; async fn get_book_and_music() -> (Book, Music) { let book_fut = get_book(); let music_fut = get_music(); join!(book_fut, music_fut) } ``` -------------------------------- ### Download Two Sites Concurrently (Rust Threads) Source: https://rust-lang.github.io/async-book/01_getting_started/02_why_async Spawns two separate threads to concurrently download two web pages. This method is suitable for CPU-bound tasks but can be inefficient for small I/O-bound tasks like downloading webpages due to thread creation overhead. ```rust fn get_two_sites() { // Spawn two threads to do work. let thread_one = thread::spawn(|| download("https://www.foo.com")); let thread_two = thread::spawn(|| download("https://www.bar.com")); // Wait for both threads to complete. thread_one.join().expect("thread one panicked"); thread_two.join().expect("thread two panicked"); } ``` -------------------------------- ### Using Select Macro with Streams and Timeouts in Rust Source: https://rust-lang.github.io/async-book/part-guide/concurrency-primitives Shows a practical example of using `select!` within a loop to process items from a stream until the stream is exhausted or a timeout occurs. This pattern is common for handling asynchronous data sources with built-in cancellation. ```rust async fn main() { let mut stream = ...; // Assume stream is initialized elsewhere loop { tokio::select! { result = stream.next() => { match result { Some(x) => println!("received: {}", x), None => break, } } _ = timeout() => { println!("time out!"); break; } } } } ``` -------------------------------- ### Download Two Sites Asynchronously (Rust Async) Source: https://rust-lang.github.io/async-book/01_getting_started/02_why_async Downloads two web pages concurrently using Rust's asynchronous programming features without creating extra threads. This approach is highly efficient for I/O-bound tasks, avoiding thread overhead and heap allocations. ```rust async fn get_two_sites_async() { // Create two different "futures" which, when run to completion, // will asynchronously download the webpages. let future_one = download_async("https://www.foo.com"); let future_two = download_async("https://www.bar.com"); // Run both futures to completion at the same time. join!(future_one, future_two); } ``` -------------------------------- ### Async Write Operation with Tokio TcpStream Source: https://rust-lang.github.io/async-book/part-guide/io Demonstrates how to perform an asynchronous write operation to a TCP stream using Tokio. This example connects to a server, writes data, and handles potential errors. It relies on the `tokio` crate for asynchronous networking and IO utilities. ```rust #![allow(unused)] fn main() { use tokio::{io::AsyncWriteExt, net::TcpStream}; async fn write_hello() -> Result<(), Box> { let mut stream = TcpStream::connect("127.0.0.1:8080").await?; stream.write_all(b"hello world!").await?; Ok(()) } } ``` -------------------------------- ### HTML Content for Web Server Responses Source: https://rust-lang.github.io/async-book/09_example/00_intro These HTML files provide the content served by the Rust TCP server. 'hello.html' is served for successful requests, displaying a greeting message. '404.html' is served for unrecognized requests, showing an error message. ```html Hello!

Hello!

Hi from Rust

``` ```html Hello!

Oops!

Sorry, I don't know what you're asking for.

``` -------------------------------- ### Async Function and Block Examples in Rust Source: https://rust-lang.github.io/async-book/03_async_await/01_chapter Demonstrates the usage of `async fn` and `async` blocks in Rust. `async fn` defines an asynchronous function, while `async` blocks create futures lazily. Both return types implementing the `Future` trait. These futures execute only when `.await`ed. ```rust // `foo()` returns a type that implements `Future`. // `foo().await` will result in a value of type `u8`. async fn foo() -> u8 { 5 } fn bar() -> impl Future { // This `async` block results in a type that implements // `Future`. async { let x: u8 = foo().await; x + 5 } } ``` -------------------------------- ### Control Flow in Async Blocks (Rust) Source: https://rust-lang.github.io/async-book/print Illustrates control flow within async blocks. Unlike regular blocks, `break` and `continue` cannot directly exit async blocks; `return` must be used. The example shows how `return` within an async block can be used to signal continuation of the surrounding loop. ```rust #![allow(unused)] fn main() { loop { { if false { // ok continue; } } async { if false { // not ok // continue; // ok - continues with the next execution of the `loop`, though note that if there was // code in the loop after the async block that would be executed. return; } }.await } } ``` -------------------------------- ### Sequential Await in Rust Source: https://rust-lang.github.io/async-book/06_multiple_futures/02_join Demonstrates a sequential approach to awaiting futures, which leads to slower execution as operations are not performed concurrently. This is the naive approach before understanding concurrent execution. ```rust async fn get_book_and_music() -> (Book, Music) { let book = get_book().await; let music = get_music().await; (book, music) } ``` -------------------------------- ### Define an Asynchronous Function in Rust Source: https://rust-lang.github.io/async-book/01_getting_started/04_async_await_primer This example demonstrates the basic syntax for defining an asynchronous function in Rust using `async fn`. Asynchronous functions return a `Future`, which represents a value that may not be ready yet. The `#![allow(unused)]` attribute is used here to suppress unused function warnings. ```rust #![allow(unused)] fn main() { async fn do_something() { /* ... */ } } ```