Module 19 Exercises — Macros, Unsafe & FFI
How to use this page
Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.
Before you start, be able to state:
- one thing a macro can do that a function cannot;
- the five things
unsafeunlocks — and what it does not affect; - two guarantees that stop at the FFI boundary.
Treat the unsafe drills as an exercise in writing the # Safety comment, not just in making it compile. If you cannot state the invariant a caller must uphold, the code is not finished — and that judgement is the real skill this module teaches.
Part A — Warm-Up Drills
Short reps on the mechanics. Do them until the syntax stops costing you any thought.
🟢 Exercise 19.1 — max! macro
Write a macro max! accepting one or more expressions and returning the largest.
Solution
macro_rules! max {
($x:expr) => { $x };
($x:expr, $($rest:expr),+) => {
{ let a = $x; let b = max!($($rest),+); if a > b { a } else { b } }
};
}
fn main() {
println!("{}", max!(3));
println!("{}", max!(3, 7, 2, 9, 4)); // 9
}Recursive macros — one base case, one step case — are the standard pattern for variadics.
🟢 Exercise 19.2 — Which are unsafe?
Which of these require an unsafe block?
let p = &x as *const i32; // A
let v = *p; // B
let s = "hi".as_bytes(); // C
static mut N: i32 = 0; N += 1; // D
std::mem::transmute::<u32, f32>(1); // EAnswers
B, D, and E. Creating a raw pointer (A) is safe; as_bytes (C) is a safe method.
Part B — Core Exercises
The real practice. Attempt each one fully — compiler errors included — before opening a solution.
🟡 Exercise 19.3 — Debug-print macro
Write dbg_vars!(a, b, c) that prints a = 1, b = 2, c = 3 using stringify!, and works
with any number of identifiers.
Solution
macro_rules! dbg_vars {
($($name:ident),+ $(,)?) => {
$( print!("{} = {:?}, ", stringify!($name), $name); )+
println!();
};
}
fn main() {
let a = 1;
let b = "two";
let c = vec![3];
dbg_vars!(a, b, c); // a = 1, b = "two", c = [3],
}🟡 Exercise 19.4 — Safe wrapper over unsafe
Implement fn swap_halves(v: &mut [i32]) that swaps the first and second halves in place,
using split_at_mut internally. Explain why the function is safe to expose even though it
uses unsafe machinery underneath.
Solution
fn swap_halves(v: &mut [i32]) {
let mid = v.len() / 2;
let (left, right) = v.split_at_mut(mid);
let n = left.len().min(right.len());
for i in 0..n {
std::mem::swap(&mut left[i], &mut right[i]);
}
}
fn main() {
let mut v = vec![1, 2, 3, 4, 5, 6];
swap_halves(&mut v);
assert_eq!(v, vec![4, 5, 6, 1, 2, 3]);
}split_at_mut uses unsafe internally but exposes a safe signature because it asserts
mid <= len and returns provably disjoint slices. Our function inherits that guarantee:
there is no argument a caller can pass that causes undefined behaviour.
Part C — Challenges
Longer builds. Expect to fight the borrow checker here; that fight is the lesson.
🔴 Exercise 19.5 — Minimal MyVec
Implement a growable vector over raw memory: struct MyVec<T> { ptr: *mut T, len: usize, cap: usize }
with new, push, pop, get, len, Drop, and Deref<Target = [T]>. Use
std::alloc. Then run it under Miri.
Solution
use std::alloc::{self, Layout};
use std::ops::{Deref, DerefMut};
use std::ptr;
pub struct MyVec<T> { ptr: *mut T, len: usize, cap: usize }
impl<T> MyVec<T> {
pub fn new() -> Self {
assert!(std::mem::size_of::<T>() != 0, "ZSTs unsupported");
MyVec { ptr: ptr::NonNull::<T>::dangling().as_ptr(), len: 0, cap: 0 }
}
fn grow(&mut self) {
let new_cap = if self.cap == 0 { 4 } else { self.cap * 2 };
let new_layout = Layout::array::<T>(new_cap).unwrap();
assert!(new_layout.size() <= isize::MAX as usize, "allocation too large");
let new_ptr = if self.cap == 0 {
unsafe { alloc::alloc(new_layout) }
} else {
let old_layout = Layout::array::<T>(self.cap).unwrap();
unsafe { alloc::realloc(self.ptr as *mut u8, old_layout, new_layout.size()) }
};
if new_ptr.is_null() { alloc::handle_alloc_error(new_layout); }
self.ptr = new_ptr as *mut T;
self.cap = new_cap;
}
pub fn push(&mut self, value: T) {
if self.len == self.cap { self.grow(); }
// SAFETY: len < cap, so ptr.add(len) is in the allocation and uninitialized.
unsafe { ptr::write(self.ptr.add(self.len), value); }
self.len += 1;
}
pub fn pop(&mut self) -> Option<T> {
if self.len == 0 { return None; }
self.len -= 1;
// SAFETY: the slot at len was initialized and is no longer considered live.
Some(unsafe { ptr::read(self.ptr.add(self.len)) })
}
pub fn len(&self) -> usize { self.len }
pub fn is_empty(&self) -> bool { self.len == 0 }
}
impl<T> Deref for MyVec<T> {
type Target = [T];
fn deref(&self) -> &[T] {
// SAFETY: the first `len` elements are initialized and contiguous.
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
}
}
impl<T> DerefMut for MyVec<T> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
}
}
impl<T> Drop for MyVec<T> {
fn drop(&mut self) {
while self.pop().is_some() {} // drop every element
if self.cap != 0 {
unsafe {
alloc::dealloc(self.ptr as *mut u8, Layout::array::<T>(self.cap).unwrap());
}
}
}
}
fn main() {
let mut v = MyVec::new();
for i in 0..10 { v.push(i); }
assert_eq!(v.len(), 10);
assert_eq!(v.pop(), Some(9));
assert_eq!(&v[..3], &[0, 1, 2]); // via Deref
assert_eq!(v.iter().sum::<i32>(), 36); // slice methods for free
let mut strings = MyVec::new();
strings.push(String::from("a"));
strings.push(String::from("b"));
drop(strings); // both Strings freed, no leak
}Run cargo +nightly miri run to verify there's no undefined behaviour. Key invariants
this code maintains, each of which Miri would catch you violating:
ptris valid forcapelements whenevercap > 0- exactly the first
lenslots are initialized Dropruns every element's destructor before deallocating
For real code, use Vec. This exercise exists so you understand what Vec is doing.
Self-check
- Name two things a macro can do that a function cannot.
- What five abilities does
unsafeunlock? - Does
unsafedisable the borrow checker? - Why must every
unsafe fnhave a# Safetydoc section? - Why is
CStringneeded for FFI instead ofString?
Answers
- Accept a variable number of arguments; generate items (impls, functions); validate arguments at compile time.
- Deref raw pointers, call unsafe functions, access mutable statics, implement unsafe traits, access union fields.
- No — it only adds those five abilities.
- Because callers must know which invariants they're responsible for upholding; the compiler can't check them.
- C strings are NUL-terminated with no length; Rust
Strings are length-prefixed UTF-8 and may contain interior NULs.
