### Async Main Function with Pollster Macro Source: https://docs.rs/pollster/latest/pollster/index Illustrates using the `#[pollster::main]` attribute macro to mark an `async fn main()` function. This macro utilizes `pollster::block_on` internally, simplifying the execution of async main functions without requiring manual setup. ```rust #[pollster::main] async fn main() { let my_fut = async {}; my_fut.await; } ``` -------------------------------- ### Enable async main function with #[pollster::main] macro Source: https://docs.rs/pollster/latest/pollster This example shows how to use the `#[pollster::main]` attribute macro to define an asynchronous `main` function. This macro internally uses `pollster::block_on` to execute the async code. If the pollster crate is re-exported under a different name, the `crate` argument can specify the correct name. ```rust #[pollster::main] async fn main() { let my_fut = async {}; my_fut.await; } ``` ```rust #[pollster::main(crate = renamed_pollster)] async fn main() { let my_fut = async {}; my_fut.await; } ``` -------------------------------- ### Async Main Function with Renamed Pollster Crate Source: https://docs.rs/pollster/latest/pollster/index Shows how to specify a custom crate name when using the `#[pollster::main]` attribute macro, which is necessary if the pollster crate has been re-exported with a different name in the project. This ensures the macro correctly references the pollster functionality. ```rust #[pollster::main(crate = renamed_pollster)] async fn main() { let my_fut = async {}; my_fut.await; } ``` -------------------------------- ### Enable async tests with #[pollster::test] macro Source: https://docs.rs/pollster/latest/pollster This snippet illustrates the use of the `#[pollster::test]` attribute macro, which enables asynchronous test functions by leveraging `pollster::block_on`. ```rust #[pollster::test] async fn my_async_test() { // Your async test logic here assert!(true); } ``` -------------------------------- ### Async Test Function with pollster::test Macro Source: https://docs.rs/pollster/latest/index Demonstrates using the `pollster::test` attribute macro to enable asynchronous operations within Rust test functions. This allows testing async logic directly. ```Rust #[pollster::test] async fn my_async_test() { // async test logic here let future = async { 42 }; assert_eq!(future.await, 42); } ``` -------------------------------- ### Async Test Function with Pollster Macro Source: https://docs.rs/pollster/latest/pollster/index Demonstrates the usage of the `#[pollster::test]` attribute macro for enabling asynchronous execution within test functions. Similar to `#[pollster::main]`, this macro leverages `pollster::block_on` to allow async operations in tests. ```rust #[pollster::test] async fn my_async_test() { // async test logic here let fut = async {}; fut.await; } ``` -------------------------------- ### Rust: Blocking on a Future with FutureExt Source: https://docs.rs/pollster/latest/src/pollster/lib.rs Demonstrates how to use the `FutureExt` trait to block the current thread until a future is ready. This is useful for running asynchronous code in a synchronous context. It relies on the `pollster` crate. ```Rust #![doc = include_str!("../README.md")] #![cfg_attr(docsrs, feature(doc_auto_cfg))] use std::future::{Future, IntoFuture}; use std::sync::{Arc, Condvar, Mutex}; use std::task::{Context, Poll, Wake, Waker}; #[cfg(feature = "macro")] pub use pollster_macro::{main, test}; /// An extension trait that allows blocking on a future in suffix position. pub trait FutureExt: Future { /// Block the thread until the future is ready. /// /// # Example /// /// ``` /// use pollster::FutureExt as _; /// /// let my_fut = async {}; /// /// let result = my_fut.block_on(); /// ``` fn block_on(self) -> Self::Output where Self: Sized { block_on(self) } } impl FutureExt for F {} enum SignalState { Empty, Waiting, Notified, } struct Signal { state: Mutex, cond: Condvar, } impl Signal { fn new() -> Self { Self { state: Mutex::new(SignalState::Empty), cond: Condvar::new(), } } fn wait(&self) { let mut state = self.state.lock().unwrap(); match *state { // Notify() was called before we got here, consume it here without waiting and return immediately. SignalState::Notified => *state = SignalState::Empty, // This should not be possible because our signal is created within a function and never handed out to any // other threads. If this is the case, we have a serious problem so we panic immediately to avoid anything // more problematic happening. SignalState::Waiting => { unreachable!("Multiple threads waiting on the same signal: Open a bug report!"); } SignalState::Empty => { // Nothing has happened yet, and we're the only thread waiting (as should be the case!). Set the state // accordingly and begin polling the condvar in a loop until it's no longer telling us to wait. The // loop prevents incorrect spurious wakeups. *state = SignalState::Waiting; while let SignalState::Waiting = *state { state = self.cond.wait(state).unwrap(); } } } } fn notify(&self) { let mut state = self.state.lock().unwrap(); match *state { // The signal was already notified, no need to do anything because the thread will be waking up anyway SignalState::Notified => {} // // The signal wasn't notified but a thread isn't waiting on it, so we can avoid doing unnecessary work by // skipping the condvar and leaving behind a message telling the thread that a notification has already // occurred should it come along in the future. SignalState::Empty => *state = SignalState::Notified, // The signal wasn't notified and there's a waiting thread. Reset the signal so it can be wait()'ed on again // and wake up the thread. Because there should only be a single thread waiting, `notify_all` would also be // valid. SignalState::Waiting => { *state = SignalState::Empty; self.cond.notify_one(); } } } } impl Wake for Signal { fn wake(self: Arc) { self.notify(); } fn wake_by_ref(self: &Arc) { self.notify(); } } /// Block the thread until the future is ready. /// /// # Example /// /// ``` /// let my_fut = async {}; /// let result = pollster::block_on(my_fut); /// ``` pub fn block_on(fut: F) -> F::Output { let mut fut = core::pin::pin!(fut.into_future()); // Signal used to wake up the thread for polling as the future moves to completion. We need to use an `Arc` // because, although the lifetime of `fut` is limited to this function, the underlying IO abstraction might keep // the signal alive for far longer. `Arc` is a thread-safe way to allow this to happen. // TODO: Investigate ways to reuse this `Arc`... perhaps via a `static`? let signal = Arc::new(Signal::new()); // Create a context that will be passed to the future. let waker = Waker::from(Arc::clone(&signal)); let mut context = Context::from_waker(&waker); // Poll the future to completion loop { match fut.as_mut().poll(&mut context) { Poll::Pending => signal.wait(), Poll::Ready(item) => break item, } } } ``` -------------------------------- ### Rust: Manual Blocking on a Future using block_on Source: https://docs.rs/pollster/latest/src/pollster/lib.rs Shows the direct usage of the `pollster::block_on` function to execute a future to completion on the current thread. This is an alternative to using the `FutureExt` trait. ```Rust /// Block the thread until the future is ready. /// /// # Example /// /// ``` /// let my_fut = async {}; /// let result = pollster::block_on(my_fut); /// ``` pub fn block_on(fut: F) -> F::Output { let mut fut = core::pin::pin!(fut.into_future()); // Signal used to wake up the thread for polling as the future moves to completion. We need to use an `Arc` // because, although the lifetime of `fut` is limited to this function, the underlying IO abstraction might keep // the signal alive for far longer. `Arc` is a thread-safe way to allow this to happen. // TODO: Investigate ways to reuse this `Arc`... perhaps via a `static`? let signal = Arc::new(Signal::new()); // Create a context that will be passed to the future. let waker = Waker::from(Arc::clone(&signal)); let mut context = Context::from_waker(&waker); // Poll the future to completion loop { match fut.as_mut().poll(&mut context) { Poll::Pending => signal.wait(), Poll::Ready(item) => break item, } } } ``` -------------------------------- ### Block on a Future with Pollster Source: https://docs.rs/pollster/latest/pollster/index Demonstrates how to use the `block_on` method from the `FutureExt` trait to synchronously block a thread until an async future completes. This is the core functionality of the pollster crate for evaluating futures in synchronous code. ```rust use pollster::FutureExt as _; let my_fut = async {}; let result = my_fut.block_on(); ``` -------------------------------- ### FutureExt::block_on Source: https://docs.rs/pollster/latest/pollster/trait.FutureExt Blocks the current thread until the future is ready and returns its output. This method is available on any type that implements the Future trait. ```APIDOC ## fn block_on(self) -> Self::Output ### Description Block the thread until the future is ready. ### Method `block_on` (provided by `FutureExt` trait) ### Endpoint N/A (this is a trait method, not an HTTP endpoint) ### Parameters #### Self - **self** (Self) - Required - The future to block on. ### Request Example ```rust use pollster::FutureExt as _; let my_fut = async {{ /* some async work */ }}; let result = my_fut.block_on(); ``` ### Response #### Success Response - **Output** (Self::Output) - The output value of the future once it has completed. #### Response Example ```rust // Assuming the future resolves to a value of type T let value: T = result; ``` ``` -------------------------------- ### Rust: Implement FutureExt Trait for Blocking on Futures Source: https://docs.rs/pollster/latest/pollster/trait.FutureExt Defines the FutureExt trait in Rust, providing a `block_on` method that allows a future to be executed to completion on the current thread, blocking until the result is available. This is useful for scenarios where asynchronous code needs to be run from a synchronous context. It requires the `Future` trait from the standard library. ```Rust pub trait FutureExt: Future { // Provided method fn block_on(self) -> Self::Output where Self: Sized { // ... implementation details ... } } ``` ```Rust use pollster::FutureExt as _; let my_fut = async {}; let result = my_fut.block_on(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.