Skip to content

12c · wc

Released Fri Sep 25, in class

This is the README OSlings gives every student for 12c_wc (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. Count lines, words, and bytes in a single pass, remembering exactly one bit about the past. This is the first program in the course whose shape is dictated by the machine it will eventually run on.

Learn

You have spent nine exercises learning Rust. This is the third of the four core command exercises (head, 14c, is extra credit), and the deal they make with you is worth restating:

The file you are about to edit is the file that runs on your own kernel in December.

Not a port of it: the same wc.rs, recompiled for riscv64gc-unknown-none-elf with #![no_std], shipped onto the rv6 disk image by oslings ship, and run by the exec (exercise 49k), file descriptors (50k), console driver (45k), and shell (46k) you will write. The constraints are the ones echo and cat already had — no allocator, bytes, not &str, no core::fmt — and for the same reason: in December there is no heap under this file and no room in its size budget for UTF-8 tables or formatting machinery (ulib::write_usize prints a number in about 20 lines instead). ulib's read is a std call on your laptop and an ecall into your kernel on rv6; your source never mentions either.

What the real wc does

wc (word count) prints lines, words, bytes, in that order, right-aligned:

$ wc README
      42     317    2104 README

The definitions matter, because the tests check them:

  • A line is a newline byte (\n): a last line with no trailing newline is not counted.
  • A word is a maximal run of non-whitespace bytes (whitespace is whatever is_space in the file says). Any run of whitespace, however long, separates exactly one pair of words: a b is two words.
  • A byte is a byte, whitespace included — not a character.

With no file arguments wc reads standard input; with files it counts each one, labels each row with the file's name, and prints a total row only when there is more than one file.

Streaming, and why you cannot just split

The obvious way to count words — read the whole input, split it on whitespace, count the pieces — hits the wall immediately: split it into what? There is no Vec to hold the pieces and no heap to grow one on, and the input itself does not fit anywhere: a file can be larger than all the memory rv6 gives a process.

So you stream. You pull the input through a small fixed buffer, look at each byte as it goes past, and never look back:

let mut buf = [0u8; 512];          // 512 bytes, on the stack, forever
loop {
    let n = ulib::read(fd, &mut buf)?;
    if n == 0 { return Ok(c); }    // 0 means end of file
    for &b in &buf[..n] { /* ... */ }
}

Two things to notice. read may return fewer bytes than you asked for at any time — that is normal, not an error — so the chunk boundaries are arbitrary and a word can be split across two iterations. And whatever state you keep must be O(1): a fixed number of variables whose size does not grow with the input. Here that is three usize counters and one bool, whether the input is 14 bytes or 14 gigabytes — which is exactly how the kernel counts things, since on the trap path there is no allocator to call.

Counting words with one bit of memory

Instead of finding words, count the transitions from whitespace into non-whitespace: every word has exactly one, its first byte. To spot a transition you need to know what the previous byte was, and one bool captures everything you need about it: in_word.

input:     ' '   ' '   'a'   ' '   ' '   'b'   '\n'
in_word:    f     f     t     f     f     t      f
words:      0     0     1     1     1     2      2
                        ^                 ^
                        transitions: +1 each

Rules, in full:

  • byte is whitespace → in_word = false. Nothing counted.
  • byte is not whitespace and in_word is already true → do nothing; this word was counted when it started.
  • byte is not whitespace and in_word is false → a word just began: set in_word = true and add one to the word count.

Start with in_word = false, as if the input were preceded by whitespace. Notice what falls out for free: a run of ten spaces still counts as one separator, and a final word with no trailing newline is counted the moment it starts, so it needs no special case at end of file.

This shape — one variable summarizing everything you need from the past — is a state machine, and you will meet it again wherever data arrives a piece at a time: the UART driver (exercise 45k), the shell's tokenizer (46k), the ELF parser (49k).

Understand

Open commands/src/bin/wc.rs — that is your working copy, staged there from this exercise's skeleton by oslings and built and tested in place.

Read the whole file before you write anything. Most of it is already there:

  • Counts — a #[derive(Default, Clone, Copy)] struct of three usize fields: passed by value like an integer, and Counts::default() is all zeros.
  • is_space — the definition of whitespace, written with matches!.
  • report — prints one row with write_usize(STDOUT, n, 8) (right-aligned in 8 columns) plus an optional file-name label.
  • run — the argument handling: standard input when there are no file arguments, otherwise open/count/close each file, a total row when there is more than one, and a non-zero exit if any file failed.

At the bottom is the #[cfg(test)] mod tests block. You never edit it. It is the contract, and a better spec than this README because it is executable:

Test What it pins down
counts_lines_words_and_bytes "one two\nthree\n" → 2, 3, 14
runs_of_whitespace_count_as_one_separator " a b \n" → 2 words
a_file_without_a_trailing_newline_still_counts_its_words "no newline here" → 0 lines, 3 words
empty_input_is_all_zeros "" → 0, 0, 0
names_each_file_and_prints_a_total labels and the total row

The tests call your run directly with writes diverted into a buffer, so the source under test is byte-identical to the source that runs on rv6.

Implement

Everything you write lives inside the for &b in &buf[..n] loop in count_fd; the in_word bool just above it is already declared, and your loop body updates it. Three markers:

  1. IMPLEMENT (1) — count the byte. One line. Every byte counts.
  2. IMPLEMENT (2) — count the line. One line, guarded by b == b'\n'.
  3. IMPLEMENT (3) — the word state machine. Use is_space(b) and the three rules above.

Delete the let _ = (b, &mut c, &mut in_word, is_space); placeholder at the top of the loop once all three markers are done; it exists only to keep the untouched skeleton warning-free.

Check your work:

oslings run 12c_wc
# or leave it watching and it re-runs every time you save:
oslings watch

That is plain cargo test on your own machine — no QEMU, nothing to boot. Green tests mean you are done for today; in December, oslings ship cross-compiles this exact file for RISC-V and you run it for real.

Stuck? oslings hint.