Crate smol_macros

source ·
Expand description

Macros for using smol-rs.

One of the advantages of smol is that it lets you set up your own executor, optimized for your own use cases. However, quick scaffolding is important for many organizational use cases. Especially when sane defaults are appreciated, setting up your own executor is a waste of time.

This crate provides macros for setting up an efficient smol runtime quickly and effectively. It provides sane defaults that are useful for most applications.

§Simple Executor

Just have an async main function, using the main macro.

use smol_macros::main;

main! {
    async fn main() {
        println!("Hello, world!");
    }
}

This crate uses declarative macros rather than procedural macros, in order to avoid needing to use heavy macro dependencies. If you want to use the proc macro syntax, you can use the macro_rules_attribute::apply function to emulate it.

The following is equivalent to the previous example.

use macro_rules_attribute::apply;
use smol_macros::main;

#[apply(main!)]
async fn main() {
    println!("Hello, world!");
}

§Task-Based Executor

This crate re-exports smol::Executor. If that is used as the first parameter in a function in main, it will automatically create the executor.

use macro_rules_attribute::apply;
use smol_macros::{main, Executor};

#[apply(main!)]
async fn main(ex: &Executor<'_>) {
    ex.spawn(async { println!("Hello world!"); }).await;
}

If the thread-safe smol::Executor is used here, a thread pool will be spawned to run the executor on multiple threads. For the thread-unsafe smol::LocalExecutor, no threads will be spawned.

See documentation for the main function for more details.

§Tests

Use the test macro to set up test cases that run self-contained executors.

use macro_rules_attribute::apply;
use smol_macros::{test, Executor};

#[apply(test!)]
async fn do_test(ex: &Executor<'_>) {
    ex.spawn(async {
        assert_eq!(1 + 1, 2);
    }).await;
}

Re-exports§

Macros§

  • Turn a main function into one that runs inside of a self-contained executor.
  • Wrap a test in an asynchronous executor.