07r · Traits and Generics¶
Released Thu Sep 17, in class
This is the README OSlings gives every student for 07r_traits (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. One name for a behavior, many types that provide it, and code written once against the name. Today you build both of the kernel abstractions this course leans on hardest.
Learn¶
Two problems wait for you later in the semester, and they are the same problem. In exercise 36k the kernel's scheduler loop picks a process, runs it, and picks again. Which process is a policy, and policies change — round-robin this week, priorities the next — but the loop must not change with them. In exercise 46k the shell's commands print things: to the UART when rv6 boots for real, to a buffer when the automatic test runs the same commands. The commands must not have to know which.
Both are code that must call a method without knowing the type it is calling it on. Rust's answer is the trait.
Defining a trait¶
A trait is a named list of methods a type promises to provide:
That is the whole declaration. write_str has a signature and a semicolon
instead of a body: a required method, which a type must supply before it
implements Out. A trait holds no data and you never build a value of it; it
is a promise about types, not a type.
Java or Go interfaces are this idea; C's version is the struct full of
function pointers, except that the compiler checks this one.
Implementing it for several types¶
pub struct StringOut { pub text: String }
impl Out for StringOut {
fn write_str(&mut self, s: &str) {
self.text.push_str(s);
}
}
Read impl Out for StringOut as "StringOut implements Out". Unlike the plain
impl StringOut of 04r, which held the type's own methods, this block
supplies the trait's — all of them, or the compiler says which.
The point only appears with the second implementer. A CountingOut that keeps
no text at all — it just adds up how many bytes went past — is every bit as good
an Out. Nothing about Out says "buffer". It says "can be handed a &str".
Default methods¶
A trait method may have a body:
That is a default method: written once, in the trait, and inherited free by
every implementer. It calls write_str without knowing which type self is —
that is the whole trick, and it is why write_line costs each new sink exactly
zero lines. It is also how a small trait stays small: Out requires one method
and gives two; Scheduler below requires pick_next and hands back a whole
scheduling loop, run_for.
Generic functions, and the bound that makes them useful¶
A generic function takes a type as a parameter, the way Option<T> and
Vec<T> (05r) do: T stands in for a type the caller chooses. But inside
fn shout<T>(v: T) you can do almost nothing with v — T could be anything,
so you cannot add it, print it, or call a method on it. A trait bound fixes
that:
<O: Out> reads "for any type O that implements Out". Now the body may call
write_line, because the bound proves every possible O has one. That is the
deal generics make: the bound is exactly the set of things you are allowed to
assume. When the compiler says "no method named write_line found for type
parameter O", you forgot the bound.
Two other spellings mean the same thing: a where clause when the list gets
long, and impl Trait in argument position when the parameter is used once:
pub fn log_all<O>(out: &mut O, lines: &[&str]) where O: Out { ... }
pub fn log_all(out: &mut impl Out, lines: &[&str]) { ... }
Two kinds of dispatch¶
The compiler does not turn log_all into one clever function for every O.
It emits a separate, specialized copy for each type actually used — one
for StringOut, one for CountingOut — with the method calls resolved at
compile time and usually inlined away. That is monomorphization ("make it
single-shaped"), also called static dispatch, and it is why a Rust kernel
can put a trait on the scheduling path for free.
The alternative, &mut dyn Out, keeps one copy of the function and finds the
right write_str at run time through a hidden table of function pointers (a
vtable): dynamic dispatch. It costs a pointer hop per call, but a
&mut dyn Out can live in a struct field or a Vec where a generic parameter
cannot, which is why exercise 46k's exec takes one. Today's file has both:
the given write_banner takes &mut dyn Out, the given write_listing takes
&mut impl Out, and one test drives each through both sinks.
Understand¶
Open warmup/src/lib.rs: three sections. On a first read, skip the body of
run_for and the #[cfg(test)] mod tests block at the bottom; come back to a
test when it fails and names what it expected.
Section 1 declares Out and two implementers for you to finish: StringOut
keeps everything written to it in a String; CountingOut keeps only bytes
and writes, and stores nothing. Underneath sit the given write_banner
(&mut dyn Out) and write_listing (&mut impl Out).
Section 2 declares Scheduler: the required pick_next and a given run_for
that calls it over and over — the kernel's scheduler loop in miniature. Two
policies implement it:
RoundRobin— yours. A cursor,next; each call scans forward from it, wrapping around the end of the table, takes the firstRunnableslot, and moves the cursor past it. No slot is starved: the rotation always comes back around.Priority— given; read it. One priority number per slot, lower meaning more urgent; each call takes the runnable slot with the lowest number, ties to the lower index. It remembers nothing and will happily starve a slot forever.
Both answer None when nothing is runnable, including for an empty table.
Section 3 is trace, one generic function with two bounded type parameters,
driving any Scheduler and writing the chosen slots' names through any Out.
Implement¶
Fill in the four IMPLEMENT markers in warmup/src/lib.rs:
Out for StringOut—write_strappendsstoself.text.Out for CountingOut—write_straddss.len()toself.bytesand one toself.writes.Scheduler for RoundRobin—pick_nextscans forward fromself.next, wrapping, for the firstRunnableslot; it advances the cursor past that slot and returns its index, orNone.trace— run the policy forturnsdecisions and write each chosen slot's name throughout, one per line.
Scheduler for Priority is given. Read it before you write marker 3: it shows
one way to walk states and answer with an Option<usize>. Leave it alone.
Check your work:
Stuck? oslings hint.