Skip to content

14c · head

Released Fri Sep 25, in class

This is the README OSlings gives every student for 14c_head (oslings lesson shows it). The starter code is not published here: it reaches you through OSlings, in class on the class network. It is extra credit, +0.5: see Extra Credit. Back to All Exercises.

Extra credit. Not scheduled in class. Prerequisites: 11c_cat, 12c_wc. Nothing later depends on the code you write here: the command exercises are self-contained, and 53k ships head only if you finished it.

Learn → Understand → Implement. Parse an argument by hand, walk a file one line at a time without ever allocating, and — the part that makes head head — stop reading the moment you have enough.

Learn

head is an optional fourth Unix command, and the first one that takes an option. echo prints its arguments, cat copies bytes, wc and grep read everything they are given. head reads an option, converts text into a number, and then deliberately does less work than it is asked to.

What the real command does

$ head lines.txt          # first 10 lines of lines.txt
$ head -n 3 lines.txt     # first 3 lines
$ head -n 3               # first 3 lines of standard input
$ sort big.log | head -n 5

The rules, precisely:

  • Default 10. With no -n, head prints the first ten lines.
  • -n COUNT replaces that ten. -n 0 prints nothing at all, and is not an error.
  • No file arguments means standard input. This is the convention every filter follows, and it is why the last example above works: sort writes into a pipe, head reads out of it.
  • A short file is not padded. head -n 10 on a two-line file prints two lines and exits happily.
  • A last line with no trailing newline is still a line, and head prints it with a newline added.

Real head also prints ==> name <== banners when given several files. Ours does not — that formatting is noise for what this exercise is about, and the tests do not ask for it.

The vocabulary

Some of these you have seen; all of them get used below.

  • Standard input / output / error are the three file descriptors every program starts with: 0, 1, 2, spelled STDIN, STDOUT, STDERR in ulib. A file descriptor is just a small integer the kernel uses to look up an open file in a per-process table. You will write that table yourself in exercise 50k.
  • argv is the list of arguments the program was started with, argv[0] being the program's own name. ulib::Args is a view over it: args.len() is argc, and args.get(i) returns Option<&[u8]>.
  • Arguments are &[u8], bytes, not &str, because that is literally what exec pushes onto the new program's stack: NUL-terminated bytes. Insisting on &str would mean UTF-8 validation tables in every program image.
  • b"-n" is a byte-string literal — a &[u8; 2], not a &str. That is what you compare argv against.
  • The exit status is the i32 your run returns. 0 means success; any other value means failure, and the shell you write in exercise 46k will read it.

Why this file is written so strangely

Every command in this part of the course is compiled twice.

Today it is compiled for your laptop, std and all, and graded by cargo test. In December you will run oslings ship, and this same source file, unchanged, will be cross-compiled for riscv64gc-unknown-none-elf as a no_std, no_main binary, linked with user.ld, and written into the rv6 filesystem image. Your shell (exercise 46k) will find it, exec it (exercise 49k), and the reads and writes it makes will land in the file-descriptor table and console driver you wrote (exercises 50k and 45k). Nothing in this file gets edited in between.

Two lines do all of that work:

#![cfg_attr(target_os = "none", no_std, no_main)]
ulib::main!(run);

The first opts out of the standard library, but only for the bare-metal target. The second expands to a normal fn main on your laptop and to the _start symbol rv6's exec jumps to on the kernel. There are no other cfgs anywhere in the file.

That promise is where the rules of the command exercises come from:

  • No allocator. No Vec, no String, no format!. rv6 user programs have no heap, so anything you need has to be a fixed-size array you declare up front — [0u8; 1024], and the size of your program's memory is visible in one glance.
  • No core::fmt. write! drags 12–18 KiB of formatting machinery into the image. ulib gives you write_all and write_usize instead.
  • Bytes, not strings, for the reason above.

Test code is exempt — #[cfg(test)] blocks never cross-compile, so the tests use Vec freely.

ulib::Lines, given to you

Splitting a stream into lines without a heap is fiddly: a read returns whatever the kernel felt like giving you, lines straddle the boundaries, and you have to shuffle the leftovers forward. ulib::Lines does that, so this exercise can be about head and not about ring buffers:

let mut buf = [0u8; 1024];              // your storage, on the stack
let mut lines = Lines::new(fd, &mut buf);
while let Some(line) = lines.next_line() {
    // `line` has NO trailing newline
}

Lines::new borrows your buffer mutably for as long as the iterator lives. That is not ceremony — the returned line points into buf, so touching buf yourself would move the ground under a live reference. In C this is the classic dangling-pointer bug and nobody catches it; here the compiler simply refuses. Note that next_line reads from the file only when it needs to. Stop calling it and the reading stops with you.

Turning "3" into 3

You cannot use str::parse here — it pulls in core::fmt machinery and it wants a &str. Doing it by hand is six lines and worth understanding once:

ASCII digits '0' through '9' are the ten consecutive byte values 48–57, so b - b'0' converts a digit byte into the number it names. Then you fold the digits left to right — n = n * 10 + digit — which is exactly what "place value" means. checked_mul and checked_add return Option, so an absurd count like 99999999999999999999 yields None rather than a silently wrapped number.

Stopping early is the whole point

head -n 5 /var/log/huge.log must not read a gigabyte to print five lines, and some_slow_program | head -n 1 must not wait for the slow program to finish. head is fast because it stops. If you write the loop as "read every line, print the first limit", every test still passes and the program is wrong in the way that matters. Write the stopping into the loop condition.

Understand

Open commands/src/bin/head.rs — your working copy, staged there from this exercise's skeleton by oslings. It is one file, and it has four pieces.

At the bottom is #[cfg(test)] mod tests — the contract. You never edit it, and it is byte-identical to the one the solution satisfies. Read it first: eight tests, one for each rule in the list above plus the two error paths, and they are a crisper spec than this README is.

fn run(args: Args) -> i32 is given to you complete. Read it and notice how little there is:

  • It checks whether args.get(1) is b"-n", and if so parses args.get(2) with your parse_usize, setting first_file = 3 so the count is not later mistaken for a filename. A bad count writes to STDERR and returns 1.
  • If there are no filenames left, it heads STDIN. Otherwise it loops over the remaining arguments, opens each one, and calls head_fd on it.
  • It closes every descriptor it opened, and returns 1 if anything failed while still processing the other files. That is head's real behavior and it is the shape almost every Unix filter has.

The two functions you write are parse_usize and head_fd. Everything head_fd needs is a Fd and a limit; it does not know or care whether the descriptor is a file, a pipe, or the console.

Implement

Fill in the three IMPLEMENT markers in commands/src/bin/head.rs:

  1. parse_usize — bytes of decimal digits in, Option<usize> out. None for empty input, for any non-digit, and for overflow.
  2. head_fd, part one — a fixed [0u8; 1024] buffer and a Lines::new(fd, &mut buf) over it.
  3. head_fd, part two — the loop: print lines with a \n after each, stop at limit lines, stop at end of file, and do not read past either.

Delete the let _ = ...; placeholder lines as you go; they exist only to keep the stub compiling.

Check your work:

oslings run 14c_head

That is plain cargo test on your own machine — no QEMU, no kernel, nothing to boot. Green tests mean you are done today, and mean this file will run on your own kernel in December.

Stuck? oslings hint.