05r · Enums, Option, and Exhaustive match¶
Released Fri Sep 11, in class
This is the README OSlings gives every student for 05r_enums_match (oslings
lesson shows it). The starter code is not published here: it reaches you
through OSlings, in class on the class network. Back to
All Exercises.
Learn → Understand → Implement. The type that says "exactly one of these, and nothing else", and the
matchthe compiler will not let you leave unfinished. This is how the kernel tracks what a process is doing.
Learn¶
A process is always doing exactly one thing: absent, waiting for a CPU, on a CPU, blocked waiting for the disk, or finished and waiting to be cleaned up. Never two at once, and never something off the list. xv6 — the C kernel this course is modeled on — writes that as integers:
#define UNUSED 0
#define RUNNABLE 1 /* ...and three more */
p->state = 47; /* compiles fine. runs fine. means nothing. */
Two things go wrong. Nothing stops 47, and nothing reminds you that adding a
sixth state means revisiting the twelve places that switch on p->state.
Both have shipped as real kernel bugs; Rust's enum closes both holes.
An enum is a fixed set of named values¶
Each name is a variant. A value of type ProcState is one of those three —
written ProcState::Runnable — and the type has no other values at all. There
is no ProcState equal to 47.
The #[derive(...)] line has the compiler write four routine implementations:
Debug prints the value when an assertion fails, Clone and Copy make a
state a cheap value copied rather than moved (recall 02r), PartialEq/Eq
compare states with ==.
Variants can carry data¶
A variant may also hold fields, and that is where enums stop being #defines
with better manners:
pub enum ProcState {
Unused,
Runnable,
Running,
Sleeping { channel: u64 }, // named fields, like a struct
Zombie { exit_status: i32 },
}
A sleeping process is sleeping on something: a channel, an arbitrary
number that is usually the address of whatever it waits for. When the disk
finishes a read its driver wakes everyone sleeping on the disk's address and
leaves the rest alone. A Zombie likewise carries the exit status its parent
collects. Build these with struct syntax, ProcState::Sleeping { channel:
0x1000 }; a variant with unnamed fields looks like a call instead, so
Exit(i32) is built as Event::Exit(3).
(Exercise 34k's real ProcState has bare variants and keeps the channel in a
field of the process control block, following xv6; folding data into the
variant, as here, is what InodeKind looks like in exercise 40k.)
match looks at which variant you have¶
let priority = match state {
ProcState::Unused => 0,
ProcState::Runnable | ProcState::Running => 1,
ProcState::Sleeping { .. } => 2,
ProcState::Zombie { exit_status } => exit_status,
};
Read it as a table. Each line is an arm: a pattern, =>, and the value it
produces. match is an expression, evaluating to whichever arm matched,
which is why it can sit on the right of a let. Four pattern features appear
there, and you need all four today:
|matches either pattern, so one arm covers two variants.{ .. }says "this variant has fields and I do not care about them".{ exit_status }binds the field to a name usable in that arm._on its own matches anything; it is the catch-all.
Exhaustiveness is the safety property¶
Delete the Zombie arm above and the code does not compile:
The compiler checks that your arms cover every value of the type — a nuisance
today and an enormous help in the kernel, because it runs in reverse: add a
variant and the compiler hands you every place in the kernel that now needs a
decision, all of them, before the kernel boots. That is why ProcState and
InodeKind are enums and not integers.
The catch: _ => ... switches the check off forever, since a catch-all covers
variants that do not exist yet. Use _ where "everything else" is genuinely
the rule you mean — the table below is exactly that — and avoid it when
classifying variants one at a time.
Option<T> is how Rust says "maybe nothing"¶
Rust has no null. A value that might be absent is wrapped in Option, an enum
the standard library already wrote:
T stands for any type you like (Option<i32>, Option<ProcState>); you use
that machinery long before writing your own in 07r. Some(x) holds a value,
None holds nothing, and both names are in scope without a prefix. Unlike
null, Option<ProcState> is a different type from ProcState, so the
compiler makes you handle the empty case before reaching the value: a function
with no answer to give — "what does an illegal transition lead to?" — returns
Option<ProcState>, and callers cannot forget. To reach inside one variant,
use if let:
if let PATTERN = VALUE { ... } runs the block only when the pattern matches,
binding what the pattern names; else is optional. It is a one-arm match.
Guards add a condition to an arm¶
match (state, event) {
(ProcState::Sleeping { channel: c }, Event::Wake { channel: w }) if c == w
=> Some(ProcState::Runnable),
_ => None,
}
Three things at once. You can match on a tuple, testing two values in one
pattern. channel: c binds a field under a shorter name. And if c == w is a
guard: the arm applies only when it holds, and when it does not, matching
continues with the next arm rather than leaving the match — which is how a
wakeup on the wrong channel falls through to _ => None. Guarded arms do not
count toward exhaustiveness, so a match resting on one needs a fallback.
Understand¶
Open warmup/src/lib.rs. You are given two enums, ProcState and Event, the
function apply, and the tests. An Event is something that happens to a
process: the scheduler picks it, the timer preempts it, the disk puts it to
sleep. The legal transitions — the whole specification of next_state — are:
| From | Event | To |
|---|---|---|
Unused |
Alloc |
Runnable |
Runnable |
Schedule |
Running |
Running |
Preempt |
Runnable |
Running |
Sleep { channel } |
Sleeping { channel } |
Sleeping { channel: c } |
Wake { channel: w }, only when c == w |
Runnable |
Running |
Exit(status) |
Zombie { exit_status: status } |
Zombie { .. } |
Reap |
Unused |
Read it as one loop: a slot is allocated, runs, maybe sleeps and wakes a few
times, exits, and is reaped back to Unused. Every pair not in the table gives
None: a process cannot be scheduled out of the grave, and a wakeup on the
disk's channel must not wake one waiting on the console.
apply is given: read how it consumes the Option that next_state hands
back. It is a match with two arms — Some(new_state) yields the new state,
None gives back state untouched — and the shorthand for exactly that match
is .unwrap_or(state). Every None your next_state returns is what lets
apply leave an illegal move alone.
At the bottom of the file is the #[cfg(test)] mod tests block. As always it
is given, it is the contract, you never edit it, and you should read it first:
the tests name the exact channels and exit statuses they expect.
Implement¶
Fill in the three IMPLEMENT markers in warmup/src/lib.rs:
ProcState::can_run— true when the process can execute instructions now or as soon as the scheduler reaches it, false when absent, blocked, or dead. Onematcharm per variant.next_state— the table above, as amatchon the tuple(state, event), givingSome(new_state)orNone.exit_status— the status out of aZombie,Noneotherwise.if let.
Check your work:
oslings run 05r_enums_match
# or leave it watching and it re-runs every time you save:
oslings watch
Stuck? oslings hint.