Brainbotox · Lessons · Exams

Advanced Rust: Async, Unsafe, Macros and Performance

by lazizanie · Programming · Rust · English

Advanced Rust for senior developers: async and futures, unsafe code and FFI, advanced traits, declarative and procedural macros, memory layout, performance and atomics.

Study this lesson with its quizzes on Brainbotox →

Async Rust: futures, executors and Pin

An async fn in Rust returns a future: a state machine that does nothing until an executor polls it. The language provides the syntax; the runtime (Tokio, for example) comes from a crate.

The Future trait

trait Future {
    type Output;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
// Poll::Ready(value) or Poll::Pending

When a future returns Pending, it has stored the waker from the context. When the awaited event happens, the waker tells the executor to poll again.

Rust futures are lazy. Calling an async function runs no code. Work starts only when the future is awaited or spawned on a runtime.

Using a runtime

#[tokio::main]
async fn main() {
    let (a, b) = tokio::join!(load("a"), load("b"));   // concurrently
    let task = tokio::spawn(async move { compute().await });
    let result = task.await.unwrap();
}
ToolBehaviour
.awaitSuspends the current task until the future is ready
join!Runs futures concurrently and waits for all
select!Waits for the first to finish and drops the others
spawnStarts an independent task; needs a Send + 'static future on a multi-thread runtime

Cancellation by drop

Dropping a future cancels it: it simply stops at its last .await point. Code must tolerate being abandoned at any await (cancellation safety).

Do not block the executor

A blocking call such as std::thread::sleep or heavy CPU work inside an async task stalls every task on that worker thread. Use the async version (tokio::time::sleep) or spawn_blocking. Also avoid holding a std::sync::Mutex guard across an .await.

Pin

The state machine generated for an async block can contain references to its own fields. Moving it in memory would invalidate them. Pin<P> guarantees that the pointed value will not move again. Types that are safe to move anyway implement Unpin. In practice you meet it as Box::pin(future) or the pin! macro.

Check yourself

  1. What happens when you call an async fn without awaiting it?
  2. What does Future::poll return?
  3. Where does the async runtime in Rust come from?
  4. Why is std::thread::sleep harmful inside an async task?
  5. What does Pin guarantee?
  6. How is a Rust future cancelled?

Take the quiz on Brainbotox

Unsafe Rust, raw pointers and FFI

The unsafe keyword unlocks a small set of operations the compiler cannot verify, and makes the programmer responsible for upholding memory safety there. It does not switch off the borrow checker.

The five unsafe abilities

  1. Dereference a raw pointer (*const T, *mut T).
  2. Call an unsafe function or method.
  3. Access or modify a mutable static variable.
  4. Implement an unsafe trait (such as Send or Sync by hand).
  5. Access the fields of a union.
let mut x = 10;
let p = &mut x as *mut i32;      // creating a raw pointer is safe
unsafe {
    *p += 1;                     // dereferencing it is not
}

Undefined behaviour

Inside unsafe you must never cause undefined behaviour (UB): dereferencing a dangling or null pointer, creating two &mut to the same data, reading uninitialised memory, a data race, or producing an invalid value such as a bool that is neither 0 nor 1. UB can break code far from the unsafe block.

Safe abstractions

The Rust pattern: keep unsafe small, wrap it in a safe API whose invariants make misuse impossible, and document why each block is sound with a // SAFETY: comment. Vec, Mutex and Rc are built this way.
Run tests under Miri (cargo miri test) to detect many kinds of undefined behaviour.

FFI: calling C

#[repr(C)]
struct Point { x: f64, y: f64 }
unsafe extern "C" {
    fn abs(input: i32) -> i32;
}
fn main() {
    let n = unsafe { abs(-3) };
}
#[unsafe(no_mangle)]
pub extern "C" fn add(a: i32, b: i32) -> i32 { a + b }   // callable from C
  • extern "C" selects the C calling convention.
  • #[repr(C)] gives a struct the C field layout. Without it, Rust may reorder fields.
  • Use CString and CStr for C strings, which are null-terminated.
  • A panic must not unwind across an FFI boundary.

Check yourself

  1. An unsafe block disables the borrow checker.
  2. Which operation requires unsafe?
  3. What does #[repr(C)] do?
  4. What is the recommended way to use unsafe code?
  5. Which tool detects many cases of undefined behaviour in tests?
  6. Which of these is undefined behaviour?

Take the quiz on Brainbotox

Advanced Rust traits and the type system

Beyond basic traits, Rust offers associated types, const generics, blanket implementations, marker traits and trait objects with specific rules. Together they let you encode invariants in types at zero run-time cost.

Associated types versus generic parameters

trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; }
trait From<T> { fn from(value: T) -> Self; }
Associated typeGeneric parameter
Implementations per typeOneMany (From<u8>, From<&str>)
Chosen byThe implementorThe caller

Trait objects and dyn compatibility

A trait can be used as dyn Trait only if it is dyn compatible (historically "object safe"): its methods must not be generic and must not return Self, unless they are excluded with where Self: Sized. Clone is therefore not usable as dyn Clone.

Sized and ?Sized

Generic parameters are Sized by default: their size is known at compile time. str, [T] and dyn Trait are unsized and live behind a pointer. Write T: ?Sized to accept them.

Blanket implementations and the newtype pattern

impl<T: std::fmt::Display> ToString for T { /* ... */ }   // for every Display type
struct Meters(f64);              // newtype: a distinct type with no run-time cost
struct Wrapper(Vec<String>);     // lets you implement foreign traits on it

Const generics

fn sum<const N: usize>(xs: [i32; N]) -> i32 { xs.iter().sum() }

Marker traits and PhantomData

  • Send, Sync, Copy, Sized, Unpin have no methods: they mark a property.
  • PhantomData<T> is a zero-sized field that tells the compiler a type logically owns or uses T, for lifetimes, variance and the typestate pattern.
struct Connection<State> { _s: std::marker::PhantomData<State> }
struct Open; struct Closed;
impl Connection<Open> { fn send(&self) { } }   // send exists only when open
Typestate: represent states as types so that invalid operations do not compile.

Generic associated types

GATs allow an associated type to have its own generic parameters, typically a lifetime: type Item<'a> where Self: 'a;. They make lending iterators expressible.

Check yourself

  1. When should a trait use an associated type and not a generic parameter?
  2. Why can Clone not be used as dyn Clone?
  3. What does T: ?Sized allow?
  4. What is the newtype pattern?
  5. What is PhantomData<T>?
  6. What do const generics allow?

Take the quiz on Brainbotox

Rust macros: macro_rules and procedural macros

Macros are code that writes code at compile time. Rust has declarative macros, written with macro_rules!, and procedural macros, which are Rust functions that transform token streams.

Why macros exist

Functions take a fixed number of typed arguments. Macros can accept a variable number of arguments, new syntax, and generate items such as trait implementations. println!, vec! and #[derive(Debug)] are all macros.

Declarative macros

macro_rules! max {
    ($x:expr) => { $x };
    ($x:expr, $($rest:expr),+) => {
        { let a = $x; let b = max!($($rest),+); if a > b { a } else { b } }
    };
}
let m = max!(3, 9, 4);
FragmentMatches
$x:exprAn expression
$n:identAn identifier
$t:tyA type
$($x:expr),*Zero or more, separated by commas
macro_rules! macros are hygienic for local variables: a variable created inside the macro cannot clash with one of the same name at the call site.

Procedural macros

KindLooks likeExample
Derive#[derive(Serialize)]serde
Attribute#[tokio::main]Rewrites the item it decorates
Function-likesql!(SELECT ...)Custom syntax
#[proc_macro_derive(Hello)]
pub fn hello_derive(input: TokenStream) -> TokenStream {
    let ast: syn::DeriveInput = syn::parse(input).unwrap();
    let name = &ast.ident;
    quote::quote! {
        impl Hello for #name {
            fn hello() { println!("Hello from {}", stringify!(#name)); }
        }
    }.into()
}
  • They live in a separate crate with proc-macro = true in Cargo.toml.
  • They receive and return a TokenStream. The syn crate parses it and quote generates code.
  • They run inside the compiler, so they can do anything at build time, and they increase compile times.
Use cargo expand to see the code a macro generates. Prefer a function or a generic when one is enough: macros are harder to read and debug.

Check yourself

  1. When are Rust macros expanded?
  2. Which keyword defines a declarative macro?
  3. What does the fragment specifier $x:expr match?
  4. What do procedural macros operate on?
  5. Which crates are commonly used to write procedural macros?
  6. Why is println! a macro and not a function?

Take the quiz on Brainbotox

Rust memory layout and performance tuning

Rust gives precise control over where data lives and how it is laid out, and its abstractions compile away, but only optimised builds show that speed.

How common types are laid out

TypeSize on a 64-bit machineContents
&T, Box<T>8 bytesOne pointer
&[T], &str16 bytesPointer and length (fat pointer)
&dyn Trait, Box<dyn Trait>16 bytesData pointer and vtable pointer
Vec<T>, String24 bytesPointer, capacity, length
Option<Box<T>>, Option<&T>8 bytesNone is stored as the null pointer
Niche optimisation: when a type has unused bit patterns (a reference is never null), the compiler uses them to encode enum variants. Option<&T> costs nothing extra.

By default the compiler may reorder struct fields to reduce padding. #[repr(C)] fixes the declared order.

Build settings

[profile.release]
opt-level = 3
lto = "fat"
codegen-units = 1
panic = "abort"
Never benchmark a debug build. cargo build --release can be 10 to 100 times faster.

Reducing allocations and copies

  • Take &str and &[T] parameters, not String and Vec<T>, when you only read.
  • Avoid needless .clone(). Borrow, or share with Rc/Arc.
  • Preallocate with Vec::with_capacity(n).
  • Cow<'a, str> (clone on write) borrows when it can and allocates only when a change is needed.
  • Small collections: SmallVec or arrays avoid the heap.

Static versus dynamic dispatch

Generics are monomorphized and can be inlined, at the price of binary size and compile time. dyn Trait keeps one copy of the code with an indirect call. Choose dyn for cold paths and heterogeneous collections.

Measuring

  • Criterion for statistically sound benchmarks; wrap inputs in std::hint::black_box so the optimiser does not delete the work.
  • perf and cargo flamegraph to find hot spots.
  • Iterators let the compiler drop bounds checks that indexed loops keep.

Check yourself

  1. How large is Option<&T> compared with &T?
  2. What does a &dyn Trait pointer contain?
  3. What may the compiler do with struct fields without #[repr(C)]?
  4. What is Cow<'a, str> useful for?
  5. Which profile setting enables whole-program optimisation across crates?
  6. Why use std::hint::black_box in benchmarks?

Take the quiz on Brainbotox

Advanced Rust concurrency: atomics, lock-free code and variance

Below Mutex and channels, Rust exposes atomics with explicit memory orderings, scoped threads and the interior mutability primitive UnsafeCell. This chapter also covers two type-system topics that matter for such code: variance and higher-ranked lifetimes.

Atomics and memory ordering

use std::sync::atomic::{AtomicUsize, Ordering};
static HITS: AtomicUsize = AtomicUsize::new(0);
HITS.fetch_add(1, Ordering::Relaxed);
let swapped = HITS.compare_exchange(5, 0, Ordering::AcqRel, Ordering::Acquire);
OrderingGuaranteeTypical use
RelaxedThe operation is atomic, with no ordering relative to other memoryCounters, statistics
Acquire / ReleaseA Release store is seen, with everything before it, by an Acquire loadLocks, publishing data
SeqCstOne global order of all such operationsWhen in doubt; slowest

compare_exchange (compare and swap) is the building block of lock-free algorithms: retry in a loop until it succeeds.

Locks in detail

  • Poisoning: if a thread panics while holding a std::sync::Mutex, the mutex is poisoned and lock() returns Err afterwards.
  • RwLock: many readers or one writer.
  • OnceLock and LazyLock: thread-safe one-time initialisation of globals.

Scoped threads and Rayon

let mut data = vec![1, 2, 3, 4];
std::thread::scope(|s| {
    let (left, right) = data.split_at_mut(2);
    s.spawn(|| left[0] += 10);        // borrows local data: no Arc needed
    s.spawn(|| right[0] += 10);
});                                   // all threads joined here

The rayon crate turns iter() into par_iter() for data parallelism with work stealing.

UnsafeCell

UnsafeCell<T> is the only legal way to mutate data behind a shared reference. Cell, RefCell, Mutex and atomics are all built on it.

Variance

TypeVariance in T
&'a T, Box<T>, Vec<T>Covariant: a longer lifetime can be used where a shorter one is expected
&'a mut T, Cell<T>Invariant: the type must match exactly
fn(T)Contravariant in its argument

Invariance of &mut T stops you from storing a short-lived reference into a slot that expects a long-lived one.

Higher-ranked trait bounds

fn apply<F>(f: F) where F: for<'a> Fn(&'a str) -> &'a str { }

for<'a> means the closure must work for every lifetime, not one chosen by the caller.

Check yourself

  1. Which ordering is enough for a simple statistics counter?
  2. What is mutex poisoning?
  3. What do scoped threads (std::thread::scope) allow?
  4. What is UnsafeCell<T>?
  5. What is the variance of &mut T in T?
  6. What does for<'a> in a trait bound mean?

Take the quiz on Brainbotox