Preface
This book is about the distance between a program that runs and software someone installs.
It assumes you have read an introduction to Rust and can write a function, a
struct, an enum, and a match without looking them up. It does not re-teach
ownership. What it teaches is everything that comes after the language: how to
decide what to build, how to grow a program in stages that each work, how to
structure the parsing and the state, what to test and what not to, what a
program should say when it fails, and how a binary on your laptop becomes a
binary on someone else’s.
Most Rust material stops at a working program. That is roughly halfway. The
second half has its own decisions, and they are made badly by default: the
program prints raw Debug output at the user, the README is a paragraph, the
only way to install it is cargo install, and the argument parser accepts
things the help text never mentions. None of that is hard. It is just unwritten
down.
The example
The book builds one program the whole way through, and it is a real one.
ved is a clone of ed, the original Unix line editor. It is about 2,800
lines of Rust in five modules, it has no dependencies at all, it compiles in
half a second, and it ships on crates.io, in a Debian apt repository, and
through WinGet. Chapters 1 to 18 describe release 0.2.1, the code people
installed in the autumn of 2026. Chapter 19 is about 0.3.0, the release that
followed it, and chapters 20 to 22 about 0.4.0, the release that fixed what
this book found.
It was chosen for three reasons. It is small enough to show completely, so nothing is hand-waved. It is old enough in design to have a specification somebody else wrote, so the question “what should this do?” has an answer that is not a matter of taste. And it contains, in the middle, a regular expression engine — a genuinely hard piece of work that has to be built rather than imported, which is where a book about building applications ought to spend three chapters.
The constraint that shapes the whole program is that ved uses nothing but the standard library. That is not advice. Chapter 1 explains why the constraint was chosen and Chapter 19 explains the two features it has cost. But it means that every line in this book is a line you can read, including the argument parser and the regex engine, and there is no chapter where the answer is “add this crate and move on”.
How the program is built
ved was built in twelve slices. A slice adds one capability and leaves a
complete, working program behind it: slice one is a REPL that can quit, slice
two can hold text, slice three understands addresses, and so on to slice twelve.
This is not a retelling. It is how the program was actually written, and the
slice list in the repository’s PLAN.md was written before the code.
Each chapter here takes a slice or two and builds it. The code is the real code.
What the book found
Writing about a program means reading every line of it and checking every
claim against the program and against ed, and that is a code review. It found
bugs. The regex chapters found two crashes and a character-corrupting
substitution, chapter 4 found a feature the code had promised since slice
three, and the chapters after them found eighteen more, from a script ending
in wq that saves nothing to a tutorial that teaches a command ved does not
have.
They are part of the story, because finding what is wrong with a program you have shipped is part of building one. Each is told in the chapter that found it, at the point where it was found, with a link to the issue in ved’s tracker. Some were fixed before chapter 19 was written, and the chapters say so. Chapter 20 is about the rest, chapter 21 fixes them, and chapter 22 ships the fixes.
Running the code
The program at thirteen points in its history lives under examples/ in the
book’s repository,
one crate per checkpoint, and each one builds and runs:
cd examples
cargo run -q -p ch03-buffer
cargo run -q -p ch10-substitute -- -p '* '
cargo test
Not every chapter ends at a checkpoint, because some of the original commits
covered more than one slice. Where a chapter’s code is not its own crate, the
text says which crate to look in. ved is release 0.2.1, the program the first
eighteen chapters describe, ch19-living is release 0.3.0, and ch21-fixed
is release 0.4.0.
Type your own version alongside if you want to; that is the best way to read this. If yours stops compiling, diff it against the next checkpoint.
Conventions
Code that is a fragment of a larger file, which is most of it, is tagged so
that mdbook test does not try to compile it on its own. Terminal sessions
show what the program actually printed. Where the book states a number — a
binary size, a test count, a build time — it was measured on the machine this
was written on, not remembered.
Every chapter ends with exercises. They are the ones worth doing: most of them are open questions in ved’s own backlog.
The other two books
This is the third of three. Programming in Rust teaches the language to someone who already programs. The Rust Thought Process teaches the model behind it — ownership as a design question rather than a compiler rule. Either one is enough preparation for this book, as is any other careful introduction.
Where this one overlaps them it is deliberate: the same idea looks different when it shows up in a program you are shipping than it does in a chapter about the idea.
1. The Shape of a Project
A program starts as a sentence. The sentence for this one is: a clone of ed that explains itself.
That is enough to start, and it is not enough to build from. Between the sentence and the first line of code there is a short piece of work that decides most of what the program becomes, and it is the cheapest work in the project because nothing has been written yet. This chapter is that work, and then the mechanics of an empty Rust project.
1.1 Choosing something with an answer
ed is the original Unix line editor. It was written by Ken Thompson in 1969,
it is still in every POSIX system, and it is famous for being unusable: it
prints ? when something goes wrong and says nothing at all when something goes
right. grep is named after one of its commands (g/re/p), sed is its
non-interactive descendant, and vi was built on top of it.
ved keeps ed’s interface and replaces its silence. Where ed prints nothing, ved
prints deleted 3 lines (2-4). Where ed prints ?, ved prints ? no match.
Where ed has no help, ved has an H command that prints the command reference
without leaving the editor. The aim is that scripts written for ed run against
ved unchanged, and chapter 14 measures how close it came.
The useful property here is not the idea. It is that somebody else wrote the
specification. POSIX defines what ed does, GNU ed is sitting on the machine to
compare against, and every question of the form “what should happen if the user
types this?” has an answer that can be looked up or run. A first project that
invents its own semantics spends most of its time in design arguments with
itself. A clone spends that time writing code.
That is worth holding onto when picking something to build: a project with an external specification is dramatically easier than a project without one, and the specification does not have to be a document. It can be an existing program, a file format, a protocol, or a wire API.
1.2 Deciding the constraints first
Before any code, ved’s PLAN.md recorded a table of decisions. It is short, and
every row in it closed a question that would otherwise have been reopened
weekly:
| Decision | Choice |
|---|---|
| Language | Rust, edition 2024, pure stdlib (no dependencies, ever) |
| Interface | CLI, line-oriented. No TUI. |
| ed compatibility | Strict drop-in. Scripts written for real ed must work unchanged. |
| Long-form aliases | Long names for commands without inline delimited arguments |
| Errors | Full English replacing ed’s bare ? |
| Confirmations | Echo what each command did |
| Build output | Single static binary. No runtime, no shared libraries. |
The first row is the one that does the most work, so it is worth being precise about what it is and is not.
“No dependencies, ever” is not a recommendation. For most programs it is the
wrong call. Reaching for clap to parse arguments and regex to match patterns
is the correct default, and a book that told you otherwise would be teaching you
to waste your life. ved adopted the constraint for specific reasons: it was a
learning project, and code you import teaches you nothing; a regex engine is one
of the good exercises in computer science and ed needs a dialect (POSIX Basic
Regular Expressions) that the standard regex crate does not implement anyway;
and a text editor that might be installed as $EDITOR on a server has a real
argument for a zero supply-chain footprint.
What matters more than the specific choice is that the constraint was chosen and written down. A constraint you have decided on does work for you. It answers questions in advance, and it answers them the same way each time. Twice in ved’s history a feature was proposed that would have required a dependency, and the constraint decided both cases in a minute instead of a week. Chapter 19 covers what that cost.
Notice also the rows that are negative. “No TUI” and “no runtime” are not features; they are the absence of features, recorded so that the absence is a decision rather than a thing nobody got around to. A plan that lists only what a program will do is half a plan.
1.3 Slicing
The build plan was twelve slices:
| # | Slice |
|---|---|
| 1 | Cargo project, REPL loop, -p/--prompt flag |
| 2 | Buffer + a (append) + . + p + ,p |
| 3 | Addresses (1p, $p, 2,4p) + current-line tracking + n |
| 4 | w (write) and q (quit), with the double-q dance |
| 5a | BRE regex engine (src/bre.rs, hand-written) |
| 5b | Substitute: s/old/new/[g] wired to the engine |
| 6 | d (delete) and i (insert) |
| 7 | g/pattern/cmd and v/pattern/cmd |
| 8 | Long-form command aliases |
| 9 | Friendly errors, confirmations, Q (force quit) |
| 10 | H/help command reference |
| 11 | Open existing files, e (edit), r (read) |
| 12 | l (list) — visible rendering of non-printing characters |
The rule that makes this list useful is stated in the plan itself: each slice is a complete working program with one more capability than the previous.
This is not the same as a task list. “Write the buffer module”, “write the address parser”, “write the command dispatcher” is a decomposition by component, and the program does not run until the last one is finished. Slices are a decomposition by capability: at the end of slice 2 you can type text into a buffer and print it back, which is not an editor but is a program, and you can tell whether it works by using it.
Two things follow from that, and both of them are why the technique is worth the small awkwardness of building things you will replace.
You get feedback at the end of every slice instead of at the end of the project.
Slice 3 of ved discovered that the dispatcher needed &mut Buffer rather than
&Buffer, because printing a line changes ed’s notion of the current line. The
plan written during slice 2 had predicted that this would first be needed in
slice 6. Being wrong about that in slice 3, with two hundred lines written, cost
ten minutes.
And a slice that works can be abandoned. Not every project finishes. A project that stopped after slice 7 would still be a usable text editor with a regex engine, which is a far better outcome than seven finished components and no program.
The slices were also, deliberately, unequal. Slice 5a is a regex engine and took longer than slices 1 through 4 together. Slice 8 is a lookup table. Sizing slices evenly is an instinct worth resisting; the unit is “one more thing the program can do”, not “one afternoon”.
1.4 The empty project
$ cargo new ved
Creating binary (application) `ved` package
$ cd ved
That produces Cargo.toml, src/main.rs with a hello-world, and a git
repository with a .gitignore containing /target. Three of those four are
right.
Cargo.toml wants editing, and the fields matter more than they look:
[package]
name = "ved"
version = "0.2.0"
edition = "2024"
description = "The verbose ed — an ed clone with friendly errors and a built-in help system"
homepage = "https://excelano.com/ved/"
repository = "https://github.com/excelano/ved"
license = "MIT"
authors = ["David M. Anderson"]
keywords = ["ed", "editor", "line-editor", "regex", "bre"]
categories = ["command-line-utilities", "text-editors"]
[dependencies]
The name is the binary’s name, the crate’s name on crates.io, and the string
people will type forever. It is worth five minutes and a check that it is not
taken. edition selects a dialect of the language; 2024 is what this program
uses and it sets the minimum compiler version to 1.85.
Everything from description down is metadata, and none of it is needed to
build. It is needed to publish, it is read by cargo search, apt show, and
the crates.io page, and it is the only description of the program most people
will ever see. Chapter 17 comes back to it. Filling it in now costs nothing;
discovering at release time that license is missing costs a re-tag.
The empty [dependencies] section stays empty for the life of this program.
1.5 What goes in the repository
By the end, ved’s repository looks like this:
ved/
├── Cargo.toml the manifest
├── Cargo.lock committed, because this is a program
├── LICENSE MIT
├── README.md the primary interface for everyone who is not you
├── PLAN.md the design table and the slice list
├── BACKLOG.md what is not built, and why
├── RELEASING.md what to do to cut a release
├── SECURITY.md where to report a vulnerability
├── Makefile build and install from source
├── install.sh download the release binary
├── src/
│ ├── main.rs REPL, dispatch, the commands
│ ├── buffer.rs the text buffer
│ ├── address.rs the address parser
│ ├── bre.rs the regex engine
│ └── enc.rs encoding detection
└── .github/workflows/ CI, release, packaging
Most of that arrives in later chapters. Two decisions about it are worth making on day one.
Commit Cargo.lock. For a program, the lock file records the exact
dependency versions that were built and tested, so a build six months from now
is the same build. For a library, the convention is the opposite, because a
library’s lock file is ignored by anything that depends on it. ved has no dependencies, so its lock file is seven lines, and it is committed
anyway.
Use git from the first commit, and write commit messages as if someone will read them, because in this book somebody does: the example crates were extracted from ved’s history, commit by commit, and Appendix B lists which commit each one came from. Chapter 16 makes the case that commit messages are the right home for a particular kind of writing that otherwise pollutes the source.
1.6 Where the reasoning goes
One habit is worth adopting before there is any code to apply it to, because it is much harder to retrofit.
A repository documents what is true. A decision log records what changed. The two read identically and behave completely differently once time passes.
“Compare modification time, not bytes, because the server rewrites the file on upload” is a statement about how the world is. It belongs in the code or the README, and it stays correct until the world changes.
“Switched from byte comparison to modification time in May, after the hash proved unreliable” is a statement about a change. The moment a third approach arrives, that sentence is describing a dead decision in the present tense, sitting in a file where a reader — or a future you at two in the morning — will load it as current guidance.
The test is tense, not topic. Naming a former state, an alternative that was
rejected, or the date a decision was taken is the tell. Those sentences go in
commit messages, in a decision log outside the repository, or nowhere. The
PLAN.md shown above sits right on the line: its design table is present tense
and stays, and its slice-by-slice architectural notes are a decision log that
was published by accident and later trimmed.
1.7 What this chapter bought
There is still no code. What there is: a program with a specification that somebody else wrote, a constraint that will answer a dozen future questions identically, twelve slices each of which leaves a working program, a manifest that can be published without edits, and a rule about where sentences go.
That is a morning’s work, and it is the difference between a project and a directory.
Exercise 1-1. Pick something to build and write its one-sentence description. Then find its external specification: the existing program, the RFC, the file format document. If there isn’t one, pick something else for your first project.
Exercise 1-2. Write the decision table. Include at least two negative rows — things the program will not do — and one constraint you are choosing rather than being forced into.
Exercise 1-3. Slice it. The test for each slice is whether you can describe what the program does at the end of it in a sentence that does not contain the word “and then”. Aim for the first slice to be one day’s work and the second to be usable.
Exercise 1-4. Look at the last project you abandoned. Was it sliced by capability or by component? If it had been sliced by capability, what would have been left behind?
2. Slice One: A Program That Runs
Slice one is a hundred and twenty lines and does almost nothing. It accepts a flag, prints a prompt, reads lines, replies “unknown command” to all of them, and quits when told to. It is the whole skeleton of the finished editor, and every later slice hangs off it.
$ cargo run -q -p ch02-repl -- -p '* '
* hello
? unknown command: hello
* q
$
2.1 main returns an exit code
use std::env;
use std::io::{self, BufRead, Write};
use std::process::ExitCode;
fn main() -> ExitCode {
let args: Vec<String> = env::args().skip(1).collect();
let prompt = match parse_args(&args) {
Ok(p) => p,
Err(e) => {
eprintln!("ved: {e}");
eprintln!("try 'ved --help' for usage information");
return ExitCode::from(2);
}
};
run_repl(prompt.as_deref())
}
A command-line program has two outputs: what it prints, and the number it
returns. The second one is invisible until something depends on it, and then it
is the only thing that matters — a shell &&, a Makefile rule, a CI job, and
git deciding whether your commit message editor succeeded all read the exit
status and nothing else.
Rust offers three ways to produce one. main can return () and the program
exits 0. It can return Result<(), E>, and on Err the runtime prints the
error with its Debug formatting and exits 1. Or it can return ExitCode,
which is the choice here, because ved wants three distinct statuses and does not
want Debug output shown to a user.
The convention this program follows is the usual Unix one: 0 for success, 2 for
a usage error, 1 for a runtime failure. ExitCode::SUCCESS and
ExitCode::FAILURE cover the first and last, and ExitCode::from(2) covers the
middle.
The usage error also demonstrates the pattern for the rest of the program.
Diagnostics go to standard error with eprintln!, prefixed with the program’s
name, lower case, no trailing period. The second line points at --help rather
than reprinting the help, because a user who mistyped a flag wants to see their
mistake, not eighty lines of reference:
$ cargo run -q -p ch02-repl -- -x
ved: unknown argument: -x
try 'ved --help' for usage information
$ echo $?
2
env::args() yields the program’s own path as its first item, which .skip(1)
discards. Collecting into a Vec<String> costs an allocation per argument and
makes the parser below a plain loop over a slice, which is worth it.
2.2 Parsing arguments by hand
/// Parse command line arguments.
/// Returns the prompt string (if any) on success.
fn parse_args(args: &[String]) -> Result<Option<String>, String> {
let mut prompt: Option<String> = None;
let mut i = 0;
while i < args.len() {
let arg = &args[i];
match arg.as_str() {
"-p" | "--prompt" => {
i += 1;
if i >= args.len() {
return Err(format!("{arg} requires a value"));
}
prompt = Some(args[i].clone());
}
s if s.starts_with("--prompt=") => {
prompt = Some(s["--prompt=".len()..].to_string());
}
"-h" | "--help" => {
print_usage();
std::process::exit(0);
}
"-V" | "--version" => {
println!("ved {}", env!("CARGO_PKG_VERSION"));
std::process::exit(0);
}
other => {
return Err(format!("unknown argument: {other}"));
}
}
i += 1;
}
Ok(prompt)
}
This is thirty lines that clap would do in six, and for most programs clap
is the right answer. Writing it by hand once is still worth an hour, because
every argument parser makes the same four decisions and a generated one hides
them from you.
A flag that takes a value has two spellings. -p '* ' and --prompt='* '
are both idiomatic and users type both. The while loop with a manual index
exists so the -p arm can consume the next argument; an iterator works
equally well if you keep the iterator in scope, which is what Chapter 10 of
Programming in Rust does. The --prompt= form is a separate match arm with a
guard, because it arrives as one argument rather than two.
The value might be missing. ved -p with nothing after it has to produce
-p requires a value rather than a panic. The bounds check is the whole fix and
it is the single most commonly skipped line in hand-written parsers.
--help and --version exit immediately and successfully. They are not
errors, they do not fall through to the rest of the program, and they exit 0.
std::process::exit(0) inside the parser is a deliberate shortcut: it skips
every destructor between here and main, which at this point in the program is
nothing.
The version comes from the manifest. env!("CARGO_PKG_VERSION") reads
Cargo.toml’s version field at compile time. A version string typed into the
source is a version string that will be wrong after the next release, and the
only thing worse than no --version is one that lies.
The final other => arm rejects everything unrecognized. That is deliberately
strict, and it is what the finished ved changes first: by slice 11 a bare word
is a filename, not an error, and the arm becomes a s if s.starts_with('-')
guard so that unknown flags still fail while unknown words are accepted.
Start strict; loosening a parser later is easy, and tightening one is a breaking
change.
fn print_usage() {
println!("ved - the verbose ed");
println!();
println!("Usage: ved [OPTIONS] [FILE]");
println!();
println!("Options:");
println!(" -p, --prompt <STRING> Set the command prompt");
println!(" -h, --help Show this help message and exit");
println!(" -V, --version Show version information and exit");
}
Usage text goes to standard output, because the user asked for it, and it is
literally a series of println! calls. The [FILE] in the usage line is a
promise slice 11 will keep.
2.3 The loop
fn run_repl(prompt: Option<&str>) -> ExitCode {
let stdin = io::stdin();
let stdout = io::stdout();
let mut out = stdout.lock();
let mut reader = stdin.lock();
let mut line = String::new();
loop {
if let Some(p) = prompt {
if write!(out, "{p}").is_err() || out.flush().is_err() {
return ExitCode::FAILURE;
}
}
line.clear();
match reader.read_line(&mut line) {
Ok(0) => return ExitCode::SUCCESS, // EOF
Ok(_) => match dispatch(line.trim_end()) {
Action::Continue => {}
Action::Quit => return ExitCode::SUCCESS,
Action::Print(msg) => {
let _ = writeln!(out, "{msg}");
}
},
Err(e) => {
eprintln!("ved: read error: {e}");
return ExitCode::FAILURE;
}
}
}
}
Five things in that loop are doing specific work.
The handles are locked once. io::stdin() and io::stdout() return handles
wrapped in a mutex, and every println! acquires and releases it. Taking the
lock once, outside the loop, is both faster and — more usefully — gives a
StdinLock that implements BufRead, which is where read_line comes from.
The String is reused. line.clear() at the top of each iteration keeps the
allocation and drops the contents. read_line appends rather than replacing,
so forgetting the clear() produces a buffer that accumulates the entire
session, which is a genuinely confusing bug to read.
Ok(0) is end of input, not an error. read_line returns the number of
bytes read, and zero bytes means the stream closed: the user pressed Ctrl-D, or
the script being piped in ran out. Exiting successfully on EOF is what makes
printf 'a\nhello\n.\nw out.txt\nq\n' | ved work, and the ability to drive the
editor from a pipe is half of what makes it testable.
The prompt is written, not printed, and then flushed. Standard output is
line-buffered, and a prompt has no newline, so without the explicit flush()
the user stares at a blank line while their prompt sits in a buffer. This is the
most common bug in first REPLs. The is_err() checks turn a closed stdout into
a clean failure exit rather than a panic.
Reading fails separately from reaching the end. Err(e) is a real I/O
error, and it exits 1 with a message on stderr.
2.4 Why dispatch returns instead of acts
/// What the REPL should do after handling one input line.
/// Slice 2 will grow this to include buffer mutations.
enum Action {
Continue,
Quit,
Print(String),
}
fn dispatch(cmd: &str) -> Action {
match cmd {
"" => Action::Continue,
"q" | "quit" => Action::Quit,
other => Action::Print(format!("? unknown command: {other}")),
}
}
dispatch could have printed the message itself and returned a bool for
“should we keep going”. Returning a description of what should happen instead
costs an allocation per message and is the single most consequential design
decision in the program.
It means dispatch is a pure function from a string to a value. It does not
touch the terminal, so it can be called from a test with no I/O setup at all,
and the test asserts on a returned value rather than on captured output.
Chapter 15 shows what that is worth: ved’s entire command-language test suite
calls dispatch directly.
It also means there is exactly one place in the program that writes to the terminal, so a decision about output — a prefix on errors, a quiet flag, whether confirmations go to stdout or stderr — is made once, in the loop, rather than in forty command handlers.
The enum will grow. By the end it has six variants, one of which switches the loop into a second mode. The shape does not change.
Three things about this enum are worth noticing now. Action::Print(String)
carries an owned String rather than a &str, because the message is usually
constructed rather than borrowed from the input. There is no Action::Error
yet, so slice 1 formats the ? prefix into the message by hand; the next slice
splits the prefix out into its own variant, and the plan gave slice 9 the job
of rewriting the text that goes inside it, which Chapter 14 comes back to. And
Continue exists so that a bare Enter is a command that does nothing, rather
than a command that fails.
2.5 What slice one is for
A hundred and twenty lines that reply “unknown command” to everything is not an achievement. What it is, is a program: it builds, it runs, it accepts input, it has an exit status, and it can be piped into. Every subsequent slice is an edit to something that already works.
Compare the alternative, where the first day produces a Buffer struct with no
program around it. Both are a day’s work. Only one of them can be run.
Exercise 2-1. Add a -q/--quiet flag that suppresses the “unknown
command” reply. Decide where the flag’s value lives: threaded into dispatch,
or held by the loop and consulted when an Action comes back. Argue for one.
Exercise 2-2. ved -p with no value prints -p requires a value. Delete
the bounds check and find out what happens instead. Now write the same bug in
the --prompt= arm, which has a different failure.
Exercise 2-3. The other => arm rejects any unrecognized argument. Change
it to accept a bare word as a filename while still rejecting unknown flags, and
check how ved -- -p should behave. (The shipped ved does this; compare after
you have written yours.)
Exercise 2-4. Remove the out.flush() and run the program interactively.
Then run it with its input piped from printf. Explain why only one of the two
misbehaves.
3. A Buffer and a Second Mode
Slice two gives the program something to remember. It adds a text buffer, a command that puts text into it, two commands that print it back, and a second mode, in which the loop that has been reading commands starts reading data instead.
$ cargo run -q -p ch03-buffer -- -p '* '
* a
hello
world
.
* ,p
hello
world
* p
world
* q
$
That is two hundred and fifty lines in two files. It cannot save, it cannot delete, and the only line it can address is the last one. It is still an editor: text goes in, text comes out, and the structure holding the text is the one the shipped program is still using 2,800 lines later.
3.1 The second file
main.rs grows two lines at the top, and the program stops being a single
file:
mod buffer;
use buffer::Buffer;
Two hundred and fifty lines do not need splitting for length. The split is
here because Buffer has an invariant, and a module boundary is the only place
Rust lets you defend one.
The invariant is that lines and current agree: current is either 0,
meaning the buffer is empty or positioned before the first line, or a valid
1-indexed position in lines. Nothing else is allowed. With both fields
private and every mutation going through a method, the code that can violate
that rule is the sixty-two lines in buffer.rs, and it is sixty-two lines you
can read in one sitting. Had Buffer been a struct with pub fields declared
in main.rs, the rule would be a comment, and comments do not hold.
This is the general case for splitting a file, and it is not about size. A module is worth making when there is something to keep out.
3.2 Vec<String>, and what it costs
pub struct Buffer {
lines: Vec<String>,
current: usize, // 0 means empty buffer / before-first-line
}
A vector of owned strings, one per line, with the newlines stripped. It is the
first representation anyone would think of, and it has a real cost:
Vec::insert at position n moves every element after it, so inserting at the
top of a hundred-thousand-line file moves a hundred thousand String headers.
That cost is the reason serious editors use something else. A gap buffer keeps a movable hole at the cursor so that repeated edits in one place are free. A piece table never moves the original text at all and stores an edit list over it. A rope makes insertion logarithmic anywhere. Any of the three would be a defensible choice, and all three are more code than the rest of slice two put together.
ved uses the vector, and the shipped version still does. The reasoning is
worth being explicit about rather than leaving as an accident: a String
header is twenty-four bytes, so moving a hundred thousand of them is a single
memmove of 2.4 megabytes, which is faster than the terminal that requested
it. ed’s editing pattern is mostly append and mostly sequential. And the
program’s promise is to be small enough to read.
The general point is the one about representations, not the one about vectors.
The structure chosen on the second day of this project survived to release
unchanged, with four fields added around it and none of them touching lines.
That is the usual outcome of picking the simple thing, and it is a better bet
than the rope you write in week one against a profile you have not taken.
Chapter 15 is where the measuring happens.
3.3 One place where 1 becomes 0
ed’s addresses are 1-indexed: line 1 is the first line, $ is the last. Rust’s
vectors are 0-indexed. Somewhere the two have to meet, and the decision is how
many places that happens in.
/// Fetch a line by 1-indexed position. Returns None if the
/// address is out of range.
pub fn line(&self, n: usize) -> Option<&str> {
if n == 0 || n > self.lines.len() {
None
} else {
Some(self.lines[n - 1].as_str())
}
}
The n - 1 appears once in the program. Every other piece of code works in
ed’s coordinates and asks Buffer to do the conversion. Spread the subtraction
across a dozen command handlers instead and each new command is a fresh chance
to write it wrong, producing the off-by-one at a boundary that survives casual
testing and shows up in someone’s file.
The Option is the second half of the same decision. Addresses come from
users, so 1000p on a three-line buffer is a typo rather than a bug, and the
program owes it an answer rather than a crash. Indexing a Vec out of range
panics, and a panic in a text editor loses the buffer. Because the bounds check
and the conversion are the same function, there is no path through the program
that checks the range and then indexes separately, which is the arrangement
where the two drift apart.
3.4 An off-by-one that cancels
/// Insert `line` after 1-indexed position `after`. `after = 0`
/// means insert at the very start of the buffer (the case when
/// you run `a` on an empty buffer). Updates current to the
/// newly inserted line.
pub fn append_after(&mut self, after: usize, line: String) {
self.lines.insert(after, line);
self.current = after + 1;
}
after is 1-indexed, Vec::insert takes a 0-indexed position, and there is no
conversion between them. That looks like the bug the previous section was
about, and it is not.
Inserting after 1-indexed line n is inserting at 0-indexed position n. Line 1 lives at index 0, so the space after it is index 1. The coordinate systems differ by one, “after” and “at” differ by one, and the two differences cancel.
The sentinel falls out of the same arithmetic. after = 0 means “after the
position before the first line”, which is insertion at index 0, the front of
the buffer, which is what a on an empty buffer has to do. The zero in
current is not a special case in this function; it is a value that already
behaves correctly.
Code where two errors cancel is code that gets helpfully broken by the next
person to read it, which is why both this version and the shipped one carry a
doc comment stating what after = 0 means. A cancellation that is not written
down is a trap.
3.5 The current line
current is ed’s least visible piece of state and its most consequential.
Nearly every command has a default address, the default is nearly always “the
current line”, and nearly every command moves it to the last line it touched.
p with no address prints the current line. Bare Enter, below, advances it.
This is why ed sessions are short to type and impossible to read over someone’s
shoulder.
At slice two there are two writers. append_after leaves it on the line just
inserted, so typing three lines into an empty buffer leaves it at 3. And ,p
sets it to the last line printed:
buf.set_current(buf.len());
That single line is why dispatch takes &mut Buffer rather than &Buffer.
Printing is not a read-only operation in ed. It is the most surprising fact
about the command language, it is invisible until a command two slices later
defaults to the wrong line, and Chapter 1 told the story of discovering it.
3.6 The second mode
let mut buffer = Buffer::new();
let mut input_mode = false;
loop {
// ed shows the prompt only in command mode, never in input
// mode — input mode is meant to feel like raw typing.
if !input_mode {
if let Some(p) = prompt {
if write!(out, "{p}").is_err() || out.flush().is_err() {
return ExitCode::FAILURE;
}
}
}
line.clear();
match reader.read_line(&mut line) {
Ok(0) => return ExitCode::SUCCESS, // EOF
Ok(_) => {}
Err(e) => {
eprintln!("ved: read error: {e}");
return ExitCode::FAILURE;
}
}
let trimmed = line.trim_end_matches('\n').trim_end_matches('\r');
if input_mode {
if trimmed == "." {
input_mode = false;
} else {
buffer.append_after(buffer.current(), trimmed.to_string());
}
continue;
}
match dispatch(trimmed, &mut buffer) {
Action::Quit => return ExitCode::SUCCESS,
Action::EnterInputMode => input_mode = true,
Action::Print(msg) => {
let _ = writeln!(out, "{msg}");
}
Action::Error(msg) => {
let _ = writeln!(out, "? {msg}");
}
}
}
A modal editor is the thing ed is famous for being, by way of vi, and the
mechanism is a bool and an early continue.
The mode belongs to the loop. It is not a field on Buffer, because it is
not part of the text. It is not state inside dispatch, because dispatch is
a pure function from a command and a buffer to an Action, and chapter 2 spent
a section on why that is worth keeping. A dispatch that remembered whether it
was in input mode would have to be called in sequence to be tested, and ved’s
command-language tests call it in any order they like.
a describes, the loop acts. dispatch returns Action::EnterInputMode
and touches nothing. The one line that changes the program’s mode is in the
loop, next to the lines that read and write, where every other decision about
what the terminal is doing already lives.
The early continue keeps the two paths apart. Input mode is four lines
and then the iteration ends. The command path below it is not indented inside
an else and does not test the flag again. When slice 6 adds i and c, both
of which also enter input mode, nothing here changes.
The prompt is suppressed. ed prints no prompt while you are typing text,
because a prompt would end up interleaved with the document. The condition is
slice 1’s prompt block with one more if wrapped around it, and the nesting is
what it looks like: three levels of indentation to write one short string. It
stays that way for most of the program’s life. Chapter 17 is where continuous
integration arrives, runs clippy for the first time, and flattens it.
The terminator is a line that is the single character ., and nothing else is:
$ cargo run -q -p ch03-buffer
a
.hidden
..
.
,p
.hidden
..
q
A line consisting of one period therefore cannot be typed into the buffer. That is ed’s hole and not ved’s; real ed has it too, and there is no escape syntax. Files containing such a line load without trouble once chapter 13 adds file reading, so the limitation is on typing alone.
3.7 Two kinds of trimming
// Strip just the line terminator, not all trailing whitespace
// — a user typing " hello " into the buffer should keep
// their trailing spaces. trim_end() would eat them.
let trimmed = line.trim_end_matches('\n').trim_end_matches('\r');
Slice 1 called line.trim_end(), which was correct while every line was a
command. It becomes a data-loss bug the moment a line can be text.
Commands are syntax, and whitespace around syntax is noise. Buffer contents are
data, and whitespace inside data is content. An editor that quietly strips
trailing spaces from typed lines corrupts Makefiles, Markdown hard line breaks,
and any file whose tests compare bytes. The program cannot have one rule for
both, so it strips only the line terminator here and leaves dispatch to call
.trim() on what it receives. The leniency stays on the command path.
The two calls in sequence handle CRLF: strip the \n, then strip the \r
underneath it. The order is not interchangeable, since the reverse pair leaves
a CRLF line ending in \r. read_line returns at most one terminator, so the
fact that trim_end_matches would strip a repeated run never comes up.
3.8 The enum grows an error
enum Action {
Quit,
EnterInputMode,
Print(String),
Error(String),
}
Continue is gone and two variants have arrived.
Error is the split chapter 2 promised. Slice 1 wrote
format!("? unknown command: {other}"), with the marker baked into the text.
Now dispatch returns the message and the loop writes the ?. One place in
the program decides what an error looks like, which is what would make the
rewrite of every error message that the plan scheduled for slice 9 a contained
piece of work rather than a sweep. Chapter 14 is about what became of it.
Continue is gone because the empty line stopped being a command that does
nothing. In ed, bare Enter is shorthand for +1p: advance to the next line and
print it, which is how you walk through a file.
fn dispatch(cmd: &str, buf: &mut Buffer) -> Action {
let cmd = cmd.trim();
// Bare Enter is shorthand for "advance to the next line and
// print it". This is how you walk through a file in ed.
if cmd.is_empty() {
let next = buf.current() + 1;
if next > buf.len() {
return Action::Error("invalid address".to_string());
}
buf.set_current(next);
return match buf.line(next) {
Some(s) => Action::Print(s.to_string()),
None => Action::Error("invalid address".to_string()),
};
}
At slice two that branch can never print anything. append_after always
leaves current on the line it inserted, p does not move it, and ,p
sets it to the last line, so current is always the final line of the
buffer and next is always past the end. Every bare Enter in slice two
answers ? invalid address.
It is written now for two reasons. It is what ed does, and slice 3 is what
makes it reachable: once 1p can move the current line back to the top, Enter
walks down from there without another edit. The alternative was leaving Enter
out and letting it fall through to unknown command, which would have been a
regression from slice 1, where a bare Enter at least did nothing rude.
The rest of dispatch includes one piece of scaffolding worth labeling as
such:
",p" => {
if buf.is_empty() {
return Action::Error("invalid address".to_string());
}
let mut output = String::new();
for n in 1..=buf.len() {
if n > 1 {
output.push('\n');
}
if let Some(line) = buf.line(n) {
output.push_str(line);
}
}
buf.set_current(buf.len());
Action::Print(output)
}
,p is matched as a literal two-character string. In ed, , is shorthand for
the range 1,$ and ,p is an address followed by a command, so the general
form should work too; at slice two, 1,2p is an unknown command. The arm is a
placeholder sized to keep the program usable until slice 3 arrives, and slice 3
deletes it along with the p arm, replacing both with an address parser and
one print routine.
Most slices contain some of this. The part worth doing deliberately is marking
it, which here is the doc comment on dispatch saying that slice 3 replaces
the match. A placeholder nobody labelled is indistinguishable from a design
decision six months later.
Note also that the whole buffer is assembled into one String and returned as
a single Print, rather than printed line by line from inside dispatch. That
is the chapter 2 rule holding under its first real pressure: dispatch does
not get to touch the terminal, even when it has a thousand lines to emit. The
cost is a second copy of the buffer in memory for the duration of the command.
Chapter 13 revisits it when files get large enough for that to matter.
3.9 What slice two is for
Slice one was a program that ran. Slice two is a program that holds state, and it puts in place the three things every later slice rearranges: a data structure with an invariant behind a module boundary, a dispatcher that describes what should happen rather than doing it, and a loop that owns the terminal, the modes, and every byte that reaches the user.
The remaining ten slices add commands. None of them change that shape.
Exercise 3-1. Add i (insert before the current line) using the existing
append_after. Decide what it should do on an empty buffer, then check your
answer against GNU ed, which is almost certainly installed on the machine you
are reading this on.
Exercise 3-2. printf 'a\nstranded\n' | cargo run -q -p ch03-buffer exits 0
and the typed line is gone: EOF in input mode discards the buffer silently.
Decide what should happen instead, and find out what real ed does before you
implement it. (ved’s answer arrives in chapter 5, with w and the unsaved-buffer
guard.)
Exercise 3-3. Change the terminator handling so that a lone . can be
entered into the buffer. Then write down what your escape syntax costs: every
ed script ever written assumes the current rule.
Exercise 3-4. Put trim_end() back in place of the two
trim_end_matches calls and write the shortest session that demonstrates the
bug. Then decide whether the buffer should keep a trailing \r when the input
is a CRLF file, and what that means for a program that will one day write the
buffer back out.
Exercise 3-5. The chapter claims Vec<String> is fast enough. Measure it:
build a buffer of 100,000 lines, time 1,000 insertions at position 1, and time
1,000 at the end. Report both. If the first number does not bother you, the
representation is right.
4. Addresses: A Little Language
Slice three is where the command line gets a grammar. Until now p printed the
current line and ,p printed everything, and both were string literals in a
match. From here on, almost every command in ed accepts an address or a range
in front of it, the forms compose, and the program needs a parser.
$ cargo run -q -p ch04-addresses -- -p '* '
* a
alpha
beta
gamma
delta
.
* 1p
alpha
*
beta
* 2,4p
beta
gamma
delta
* $p
delta
* ,n
1 alpha
2 beta
3 gamma
4 delta
* q
$
The new file is address.rs, a hundred and ninety-four lines, and it is the
first piece of the program that is a language implementation rather than a
feature.
4.1 The grammar
ed’s address syntax is small enough to state completely:
| Form | Means |
|---|---|
5 | line 5 |
. | the current line |
$ | the last line |
+3, -2 | three lines after, two lines before, the current line |
+, - | the same with an implied 1 |
2,4 | the range from line 2 through line 4 |
, | shorthand for 1,$, the whole buffer |
; | shorthand for .,$, here to the end |
5, | shorthand for 5,$ |
An address prefixes a command letter, so 2,4p is a range and a print, $d
deletes the last line, and an address with no command letter at all means “go
there and print it”, which is why 5 on its own is a usable way to move
around.
Two forms in real ed are missing from that table, and section 4.8 is about why.
4.2 Parsing and resolving are two jobs
The module splits the work in half, and the split is the reason the rest of it stays small.
pub enum Address {
Number(usize),
Current,
Last,
Offset(isize),
}
pub struct Spec {
pub start: Option<Address>,
pub end: Option<Address>,
}
pub struct Range {
pub start: usize, // 1-indexed, inclusive
pub end: usize, // 1-indexed, inclusive
}
Spec is what the user typed. Range is what it turns out to mean. $ is an
Address::Last in a Spec and it is the number 4 in a Range, and which one
of those two it is depends on the buffer at the moment the command runs.
Keeping them apart matters because the same Spec resolves differently at
different times, and because parse errors and address errors are different
kinds of wrong. 2,4p typed against a two-line buffer parses cleanly and
resolves to an error; zp fails to parse as an address and is a command
problem, not an address problem. A single function doing both would have to
report both through one channel and the caller would have to sort them out.
Spec::parse says so in its own doc comment: this does NOT validate that the
addresses are in range — that’s resolve’s job. It just tokenizes.
One naming note, since the type will be read next to standard library code all
day. This Range is inclusive at both ends and 1-indexed, and std::ops::Range
is half-open and 0-indexed. They are opposite in both respects. The field
comments carry the convention, and the type is always written address::Range
at its use sites.
4.3 The dispatcher becomes two-stage
let (spec, rest) = match Spec::parse(cmd) {
Ok(parsed) => parsed,
Err(e) => return Action::Error(e),
};
// No command letter, just an address. ed treats this as
// "go to that line and print it" — so `5<Enter>` jumps to
// line 5 and prints it.
if rest.is_empty() {
return run_print(&spec, buf, false);
}
// Stage one: commands that take no arguments after the letter.
// Exact-match these so we don't have to deal with `q` matching
// the front of `quit`.
match rest {
"q" | "quit" => return Action::Quit,
"a" => return Action::EnterInputMode,
"p" => return run_print(&spec, buf, false),
"n" => return run_print(&spec, buf, true),
_ => {}
}
// Stage two, when there is one: commands that take arguments
// after the letter. Slice 4 adds the first of them.
Action::Error(format!("unknown command: {rest}"))
Peel the address, then look at what is left. Every command from here to slice 12 is added to one of those two matches, and none of them parse addresses themselves.
The comment on the first match is doing real work. The arms match the remainder
exactly, rather than testing its first character, because q and quit are
both commands and a first-character test makes quit a q with garbage after
it. Slice 8 adds long-form aliases for most of the command set, and exact
matching is what lets them be added as extra arms instead of as a prefix
problem.
The rest.is_empty() branch above it is ed’s bare-address rule, and it is what
finally makes chapter 3’s bare-Enter branch reachable. 1p moves the current
line to the top; Enter walks down from there.
4.4 Absence is not an error
/// Parse a single address atom. Returns `(maybe_address, rest)`.
/// `Ok((None, rest))` means "no address here, the rest is the
/// command letter" — used by callers that need to distinguish an
/// empty address from a parse error.
fn parse_one(input: &str) -> Result<(Option<Address>, &str), String> {
let bytes = input.as_bytes();
let Some(&first) = bytes.first() else {
return Ok((None, input));
};
match first {
b'.' => Ok((Some(Address::Current), &input[1..])),
b'$' => Ok((Some(Address::Last), &input[1..])),
// ... offsets and digits ...
_ => Ok((None, input)),
}
}
The return type is Result<Option<Address>, _> flattened into a tuple, and the
two layers mean different things. Err is “that was meant to be an address and
it is malformed”. Ok(None) is “there was no address here, and that is fine”.
The final arm is the one that makes the dispatcher work. When the input
is pq or zp or anything else that does not start with an address character,
parse_one consumes nothing, returns None, and hands the string back
untouched. The command matcher below then gets the full string and reports
unknown command: zp. Had that arm been an error instead, every unrecognized
command in the program would have been reported as a bad address, which is both
wrong and the kind of wrong that sends a user looking in the wrong place.
The rule generalizes past this parser: a component that can be handed input meant for someone else needs a way to decline that is not failure.
4.5 The parser hands back the rest of the string
pub fn parse(input: &str) -> Result<(Spec, &str), String>
The returned &str borrows from input, which the elided lifetime ties
together, and nothing is allocated to represent “the remainder”. The tokenizer
walks forward by slicing, take_digits finds the end of a digit run with
position and splits there, and the whole module allocates only when it builds
an error message.
/// Pull a run of ASCII digits off the front of `s`. Returns the
/// digit slice and the remainder.
fn take_digits(s: &str) -> (&str, &str) {
let end = s
.as_bytes()
.iter()
.position(|b| !b.is_ascii_digit())
.unwrap_or(s.len());
s.split_at(end)
}
This is the shape most hand-written parsers in Rust end up with, and it is pleasant for a reason that has nothing to do with performance: a function returning “what I understood, and where I stopped” composes with the next one without anybody owning a cursor. The alternative, a struct holding the input and a position, is what you reach for when the grammar gets big enough that threading the remainder through return types becomes noise. ed’s grammar never gets there, and chapter 8 is where the regex compiler does and takes the other option.
Working in bytes rather than characters is safe here because every character the grammar recognizes is ASCII, and the byte after a multi-byte character is never mistaken for one of them. Chapter 13 is where that assumption gets examined properly, because the buffer is a different question from the command language.
4.6 Every command brings its own default
An address can be omitted, and what it defaults to is the command’s business, not the parser’s.
/// Resolve with current-line as the default for an omitted
/// spec. Used by `p`, `n`, and most other commands.
pub fn resolve(&self, buf: &Buffer) -> Result<Range, String> {
self.resolve_with(buf, (Address::Current, Address::Current))
}
Bare p prints the current line, so p’s default is .,.. By the time the
program ships there are two more of these, and they are the reason the default
does not live inside resolve:
/// Resolve with the whole buffer (`1,$`) as the default for an
/// omitted spec. Used by `w` — typing `w foo.txt` with no
/// address writes the entire buffer, not just the current line.
pub fn resolve_or_whole(&self, buf: &Buffer) -> Result<Range, String> {
self.resolve_with(buf, (Address::Number(1), Address::Last))
}
/// Resolve with `.,.+1` as the default for an omitted spec.
/// Used by `j` (join) — bare `j` joins the current line with
/// the next one, matching ed.
pub fn resolve_or_pair_with_next(&self, buf: &Buffer) -> Result<Range, String> {
self.resolve_with(buf, (Address::Current, Address::Offset(1)))
}
A bare w that wrote only the current line would be a data-loss bug wearing
the costume of a sensible default. A bare j that joined the current line with
nothing would do nothing. Neither default is derivable from the address syntax,
because neither is a fact about addresses. resolve_with takes the pair as an
argument and each command picks.
This is worth recognizing as a shape, because the wrong version of it is common: a parser that helpfully fills in a default, and then one caller that needs a different one, and then a flag parameter, and then two. The default belongs to whoever knows the semantics.
4.7 A state the type allows and the parser never builds
let (start_addr, end_addr) = match (&self.start, &self.end) {
(None, None) => default,
(Some(s), None) => (clone_addr(s), clone_addr(s)),
(Some(s), Some(e)) => (clone_addr(s), clone_addr(e)),
(None, Some(_)) => unreachable!("parser never produces (None, Some)"),
};
Spec holds two Option<Address>, which is four combinations, and the parser
produces three of them. A spec with an end and no start is meaningless, cannot
be typed, and is representable.
The unreachable! is an honest way to write this and not the best one. It
states the invariant, it names the component responsible for it, and it turns a
violation into a panic with a message rather than a silently wrong answer. What
it does not do is prevent the state, and the compiler is not checking the claim
— it is taking the author’s word and generating a panic for the case.
The alternative is to make the state unrepresentable:
enum Spec {
Empty,
Single(Address),
Range(Address, Address),
}
Three variants, three cases, no fourth arm and no panic. The Rust Thought Process spends a chapter on this move, and it is the right one often enough that reaching for it should be automatic.
ved did not make it, and the reason is worth being straight about rather than
dressing up. Spec’s fields are read directly by parse_dest in the shipped
code, which checks spec.end.is_some() to reject a range where a single
address is required, and by is_empty, which checks that both are None. Both
would work against the enum. The structure stayed because it was written in
slice 3 and never caused a bug, which is the same reason most such structures
stay. The panic has never fired.
That is a real answer and it is not a defence. An invariant maintained by one function’s control flow is one refactor away from being maintained by nobody, and the compiler will not mention it.
4.8 Two things this code gets wrong
The first is small:
fn clone_addr(a: &Address) -> Address {
match a {
Address::Number(n) => Address::Number(*n),
Address::Current => Address::Current,
Address::Last => Address::Last,
Address::Offset(n) => Address::Offset(*n),
}
}
Twelve lines that #[derive(Clone, Copy)] on Address deletes. Every variant
carries either nothing or a plain integer, so the derive is available, correct,
and free. This function is in the shipped program.
The second is not small, and it is a comment:
// Search addresses (/foo/, ?foo?) wait for slice 5 when the regex
// engine arrives. Compound expressions like $-5 also wait.
Slice 5 built the regex engine. Neither of those arrived with it, and neither has arrived since. In the released program:
$ ved
a
alpha
beta
.
/beta/p
? unknown command: /beta/p
$-1p
? unknown command: -1p
GNU ed accepts both. The offsets that ved does have (+3, -2) always resolve
against the current line, because Address::Offset holds a number and nothing
to attach it to, so an offset cannot compose onto a preceding address. Search
addresses went into ved’s tracker as ved
#7 on the day this chapter was
written, and chapter 19 follows them into 0.3.0.
Chapter 1 made a distinction between a repository documenting what is true and a decision log recording what changed, and this comment is the third thing, which is a promise. It describes a future that did not happen. It has been wrong for longer than it was ever right, and it reads, to anyone opening the file, as a statement about work in progress rather than a permanent limitation of the program.
The fix is not to delete the knowledge. It is to move it to where the program’s
limitations are recorded and to state it in the present tense: addresses are
line numbers, ., $, and current-relative offsets; regex search addresses
and compound offsets are not implemented. Then the comment is true, and stays
true, and the backlog carries the intention. Chapter 19 is about the file where
that intention lives, and search addresses sit at the top of it.
4.9 What slice three bought
Two hundred and thirty lines of main.rs and a hundred and ninety-four of
address.rs, and the program can now name any line or span of lines in the
buffer. More importantly, the next eight commands do not have to think about
it. d, w, s, g, m, t, j and c all arrive as an arm in a match
and a call to resolve.
That is the return on building a small language early rather than adding
addressing to each command as it needs it. The alternative pattern — the one
where p learns about $ and then d learns about $ separately — is how
command-line programs end up with three subtly different notions of what -1
means.
Exercise 4-1. Add #[derive(Clone, Copy)] to Address and delete
clone_addr. Then find every place the borrow checker now lets you simplify,
and check whether resolve_with still needs to take its default by value.
Exercise 4-2. Implement $-5. The honest version restructures Address so
that an offset composes onto a base address rather than always onto the current
line; sketch the type before you write the parser, and check what it does to
resolve_one.
Exercise 4-3. 5,p means 5,$p. Find the three lines in Spec::parse that
implement it, then decide whether ,5p should mean 1,5p and whether ed
agrees with you.
Exercise 4-4. Replace Spec’s two Options with the three-variant enum
from section 4.7 and delete the unreachable!. Count the lines that changed.
If it was fewer than twenty, ask why it was not done.
Exercise 4-5. zp reports unknown command: zp rather than a bad address.
Change parse_one’s final arm to return an error and run the test suite for
chapter 4’s crate, then explain the failure to someone in one sentence.
5. Writing, Quitting, and the Unsaved Buffer
Slice four is the first time the program touches anything outside itself. Until now every failure was a typo and every consequence was a line of output. From here the program can create a file, overwrite one, and lose an afternoon of somebody’s work.
$ cargo run -q -p ch05-write -- -p '* '
* a
alpha
beta
.
* w out.txt
wrote 11 bytes to out.txt
* q
$
It also becomes, for the first time, a program that argues with the user:
* a
x
.
* q
? warning: buffer modified
* q
$
That exchange is ed’s, it is one boolean, and it is the reason this chapter is longer than the command deserves.
5.1 Commands that take arguments
Chapter 4’s dispatcher matched the remainder of the line exactly, which works
while every command is a single letter. w out.txt is a letter and an
argument, so the match needs a second stage:
// Stage two: commands with arguments. Match on the first byte
// and pass the rest as the argument string.
let first = rest.as_bytes()[0];
let args = &rest[1..];
match first {
b'w' => run_write(&spec, buf, args),
_ => Action::Error(format!("unknown command: {rest}")),
}
Four lines, and every command from here to slice 12 that carries an argument
lands in that match: s, g, v, m, t, r, e.
The indexing is safe from the empty case, because rest.is_empty() was checked
seventeen lines earlier and returned. It is not safe from anything else:
$ ved
a
x
.
é
thread 'main' panicked at src/main.rs:296:21:
start byte index 1 is not a char boundary; it is inside 'é' (bytes 0..2 of string)
rest[1..] slices a str at byte 1. When the first character is multi-byte,
byte 1 is inside it, and slicing a str at a position that is not a character
boundary panics. Any non-ASCII character typed as a command crashes the editor
and takes the buffer with it.
That panic was in ved from this slice until the chapter you are reading was written, which is the reason it is here rather than in a list of things to watch for. It went into the tracker that day as ved #8, and the fix shipped the next day in 0.2.1.
Chapter 3 argued that a panic in a text editor loses the buffer, as the reason
Buffer::line returns an Option instead of indexing. The argument was right,
and this is what it looks like when the same care is not taken twelve lines
further along in the same file.
Finding one of these is less work than it sounds, because the dangerous
operation is specific: a literal byte offset applied to a str. Most of the
program never performs one. run_substitute and run_global call as_bytes()
first and index the byte slice, where every offset is legal, and bre.rs works
in bytes from end to end. address.rs does slice a str at [1..], in five
places, but each one is reached only after matching an ASCII byte, so byte 1 is
always a boundary. That left the dispatcher: the one site that took a byte
offset into a string it had not inspected, and the site holding whatever the
user had typed.
The fix removes the arithmetic rather than correcting it:
let mut chars = rest.chars();
let first = match chars.next() {
Some(c) => c,
None => return Action::Error(format!("unknown command: {rest}")),
};
let args = chars.as_str();
match first {
'w' => run_write(&spec, buf, args),
// ...
}
Chars::as_str returns the rest of the string after the character just taken,
so there is no index to get wrong and no len_utf8 to add up. The arms become
character literals. The None arm is the part worth copying: it replaces an
invariant held seventeen lines away with a branch the compiler can see, and
costs three lines to stop needing to remember anything.
The bug survived for as long as it did because the tests drive the program with
ASCII, which is what the command language is made of, and because nobody types
é at an editor on purpose. That is the profile of most latent panics —
unreachable by intent, one paste away by accident — and chapter 15 comes back
to it as a question about what a suite built from valid input cannot tell you.
5.2 Where the filename lives
pub struct Buffer {
lines: Vec<String>,
current: usize,
modified: bool,
filename: Option<String>,
}
Two fields arrive together, and neither is text.
filename is what makes a bare w work after a w out.txt. ed remembers the
last file you wrote and reuses it, which is why an ed session reads as a series
of terse commands rather than a series of paths. run_write consults it only
when the argument is empty:
let filename: String = if filename_arg.is_empty() {
match buf.filename() {
Some(f) => f.to_string(),
None => return Action::Error("no current filename".to_string()),
}
} else {
filename_arg.to_string()
};
The failure case is the interesting one. A bare w with nothing remembered has
no sensible default, and the two wrong answers are both tempting: writing to a
name the program invents, and doing nothing quietly. ved says no current filename and changes nothing. A command that cannot do what was asked should
say so; the cost of that sentence is one Option and one match arm.
Putting the filename on Buffer rather than in the REPL loop is the choice
that looks arbitrary and is not. By slice 11 the buffer can be loaded from a
file, and at that point “which file is this” is a property of the text, not of
the session. Had it lived in run_repl, slice 11 would have moved it.
5.3 What modified means
pub fn append_after(&mut self, after: usize, line: String) {
self.lines.insert(after, line);
self.current = after + 1;
self.modified = true;
}
Every mutation sets it. One thing clears it:
/// Called by `w` after a successful whole-buffer write. A
/// partial-range write does NOT clear modified, since the
/// buffer still differs from any single file on disk.
pub fn mark_saved(&mut self) {
self.modified = false;
}
The comment is the design, and it is easy to get wrong. 1,2w part.txt on
a three-line buffer has written a file successfully, and the buffer is still
unsaved, because what is on disk is not what is in memory. A flag that meant
“a write succeeded” would clear here and the program would then let you quit
over the top of unsaved work:
* 1,2w part.txt
wrote 6 bytes to part.txt
* q
? warning: buffer modified
run_write computes the distinction rather than trusting the command form,
because 1,$w and a bare w are the same write:
let whole = range.start == 1 && range.end == buf.len();
The flag is named for the buffer’s relationship to the file, not for what the
last command did. Naming it saved or dirty would invite the same bug from
the other direction.
There is one more case, and it is the reason run_write does not simply call
resolve_or_whole and be done:
let (content, wrote_whole) = if buf.is_empty() && spec.is_empty() {
(String::new(), true)
} else {
An empty buffer resolves to an error, because chapter 4’s resolve_with opens
with if buf.is_empty(). But w empty.txt on an empty buffer is a legitimate
request that should produce a zero-byte file, not ? invalid address. Writing
nothing is a thing a user can want. This is the first appearance of a pattern
that recurs through the rest of the program: the general path is right for
every case except the empty one, and the empty one has to be spelled out.
5.4 The double-q dance
Action::Quit => {
if buffer.is_modified() && !quit_warned {
let _ = writeln!(out, "? warning: buffer modified");
quit_warned = true;
} else {
return ExitCode::SUCCESS;
}
}
Action::EnterInputMode => {
input_mode = true;
quit_warned = false;
}
Action::Print(msg) => {
let _ = writeln!(out, "{msg}");
quit_warned = false;
}
Action::Error(msg) => {
let _ = writeln!(out, "? {msg}");
quit_warned = false;
}
The first q on a modified buffer warns. A second q immediately after quits.
Anything in between puts the guard back:
* q
? warning: buffer modified
* p
x
* q
? warning: buffer modified
Three things about where this code is.
The guard is in the loop, not in dispatch. quit_warned is a fact about
the session, like input_mode, and it changes in response to every action
rather than in response to one command. dispatch still answers the question
“what does this command mean” and does not know that the program is arguing
with anybody.
Every arm resets it, including the error arm. That is deliberate and it is
the part people get wrong: a mistyped command between the two qs should cancel
the confirmation, because the user’s attention moved. The arms are written out
one by one rather than reset once before the match, which is four lines instead
of one and is the version that survives a fifth variant being added, since a new
variant with no reset is a compile error only if the author is looking. Chapter
11 adds one.
The warning goes through the same ? channel as errors. It is not an error
— nothing failed — and it is formatted as one, because ed formats it as one and
scripts grep for the ?. Chapter 14 comes back to whether that was right.
The asymmetry worth noticing: a program that refuses to lose your work without asking, but asks by printing one line and then obeying you a second later. ed’s answer to “are you sure” is to make you repeat yourself. It works because the cost of being wrong is one keystroke and the cost of a dialog box is a program that cannot be driven from a pipe.
5.5 Writing the file
if let Err(e) = std::fs::write(&filename, &content) {
return Action::Error(format!("cannot write {}: {}", filename, e));
}
One line does the work and one line turns its failure into a sentence:
* w /nope/x.txt
? cannot write /nope/x.txt: No such file or directory (os error 2)
The message includes the path, because the user may have typed it wrong, and
the operating system’s own words, because os error 2 is what the manual pages
and the search results are about. It does not include a stack trace, and the
program does not exit. A failed write is an ordinary event.
std::fs::write creates or truncates, writes the bytes, and closes. What it
does not do is make the replacement atomic. Between the truncate and the last
byte, the file on disk is neither the old contents nor the new ones, and a
crash, a full disk, or a power loss in that window leaves it that way. The
durable version writes to a temporary file in the same directory and renames it
over the target, because rename within a filesystem is atomic, so the file is
either entirely old or entirely new and never half of either.
ved does not do this. For a tool whose users are mostly writing small files interactively it has never mattered, and saying so is more useful than pretending the simple call was a considered choice. It is also the kind of thing that becomes a bug report exactly once, from someone whose disk filled up.
5.6 Saying what happened
let msg = format!("wrote {bytes} bytes to {filename}");
Real ed prints 11. Just the number, no context, no filename. ved prints
wrote 11 bytes to out.txt, and this is the first place the program’s stated
purpose shows up as code rather than as a sentence in PLAN.md.
The byte count is kept because it is the part of ed’s output that carries information: it tells you the write happened and roughly what went out. The rest is added because a terminal is not a quiz. Two things follow from having made the decision once, here, at slice four rather than at slice nine: every command added afterwards was written with a confirmation line from the start, and the format stayed consistent because there was something to be consistent with.
The comment above the message is worth keeping, too:
// Build the confirmation message before we move `filename` into
// the buffer's filename slot.
let msg = format!("wrote {bytes} bytes to {filename}");
buf.set_filename(filename);
set_filename takes ownership. Formatting afterwards would be a borrow of a
moved value, and the compiler would say so. The comment documents an ordering
that exists for the compiler’s sake, which is the useful kind of comment about
borrowing: not what the rule is, but why these two lines are in this order.
5.7 What slice four bought
The program can now be used for the thing it is for. Type text, write it to a file, quit. Six hundred lines, four commands, and everything from here is addition rather than foundation.
It also acquired its first three ways to hurt somebody: it can overwrite a file without asking, it can leave a truncated file behind if it dies mid-write, and it could, until recently, be crashed by a character. The first is ed’s design and stays. The second is a known trade. The third was a bug, and it lasted from this slice to the writing of this chapter.
Exercise 5-1. This chapter’s crate still panics, because slice 4 did. Fix
it there without looking at section 5.1 again. Then grep the finished program
in examples/ved for every literal byte offset applied to a string, and for
each one write the single sentence that says why it is safe. One of them will
take longer than the others.
Exercise 5-2. Make the write atomic: write to filename.tmp in the same
directory, then std::fs::rename over the target. Then work out what your
version does that the simple one did not, when the target is a symlink, and
when the process lacks write permission on the directory but has it on the
file.
Exercise 5-3. 1,2w part.txt leaves the buffer modified. Write the session
that convinces you this is right, then change mark_saved to clear
unconditionally and write the session that loses data.
Exercise 5-4. The q guard resets on every action. Remove the reset from
the Error arm only, then find the sequence of three commands that quits
without warning and should not have.
Exercise 5-5. ved will overwrite an existing file without comment. Decide whether it should, given that ed does and that scripts depend on it, and if you decide it should not, work out how the new behavior stays scriptable.
6. The Command Loop
This chapter has no slice of its own. The next one starts a regex engine that will take three chapters and add more code than the program currently contains, and before that happens it is worth reading what four slices have built as a single thing rather than as four additions.
The code is examples/ch05-write for the version this chapter describes, and
examples/ved for what it becomes.
The claim being made is narrow and checkable. At the end of slice 4 the program
is 609 lines, run_repl is 75 of them, and dispatch is 52. At release the
program is 2,809 lines, run_repl is 95, and dispatch is 110. Everything
else — the regex engine, eleven more commands, file loading, encoding
detection, the help system — arrived without the loop changing shape.
6.1 The loop, whole
fn run_repl(prompt: Option<&str>) -> ExitCode {
let stdin = io::stdin();
let stdout = io::stdout();
let mut out = stdout.lock();
let mut reader = stdin.lock();
let mut line = String::new();
let mut buffer = Buffer::new();
let mut input_mode = false;
let mut quit_warned = false;
loop {
// prompt, unless we are in input mode
// read a line; EOF and I/O error return here
// strip the terminator, keep the spaces
if input_mode {
// a lone `.` leaves input mode; anything else is text
continue;
}
match dispatch(trimmed, &mut buffer) {
Action::Quit => { /* the unsaved-buffer guard */ }
Action::EnterInputMode => input_mode = true,
Action::Print(msg) => { let _ = writeln!(out, "{msg}"); }
Action::Error(msg) => { let _ = writeln!(out, "? {msg}"); }
}
}
}
Four sections: set up, read, one branch for the mode, one match over what the last command decided. Everything the program owns that is not text lives in those nine local variables, and three of them are locks and buffers.
Read the responsibilities rather than the code and it divides cleanly. The loop
owns the terminal, the modes, and the session. dispatch owns the command
language. Buffer owns the text. Spec owns addresses. Nothing owns two of
those, and the direction of the dependencies runs one way: the loop calls
dispatch, dispatch calls Buffer and Spec, and neither of them can see
the terminal or knows a mode exists.
That is the property worth naming, because it is what the rest of this chapter
is about and it did not happen by accident. It was the decision in chapter 2 to
have dispatch return an Action rather than print, made when the program had
one command and the decision looked like ceremony.
6.2 What twelve more commands did to it
By release the loop has gained twenty lines, and they are worth listing because the list is short.
A file named on the command line is loaded before the loop starts. Two Action
variants arrive: ForceQuit, which is Q, quitting without the unsaved-buffer
warning, and Done, which is the variant for commands that change the buffer
and have nothing to say beyond their confirmation. And quit_warned gains
resets in the two new arms.
That is the difference. No new mode, no state threaded through, no flag
consulted in three places. s, g, v, m, t, j, d, c, i, l,
e, r, and H were added without touching run_repl at all, because each
of them is a command, and commands are dispatch’s business.
A loop that had printed its own output would have grown differently. Each new
command would have added a call to writeln!, the error format would live in
fourteen places, and the rewrite of every message that the plan scheduled for
slice 9 would have been a search rather than an edit.
6.3 One function per command
Eleven commands in the finished program are a function with nearly the same signature:
fn run_delete(spec: &Spec, buf: &mut Buffer) -> Action
fn run_join(spec: &Spec, buf: &mut Buffer) -> Action
fn run_write(spec: &Spec, buf: &mut Buffer, args: &str) -> Action
fn run_move(spec: &Spec, buf: &mut Buffer, dest_arg: &str) -> Action
fn run_global(spec: &Spec, buf: &mut Buffer, args: &str, invert: bool) -> Action
An address, the buffer, whatever text followed the letter, and an Action back.
The uniformity is not aesthetic. It means every command is callable from a test
with two lines of setup, it means a new command has an obvious shape before it
has an implementation, and it means the difference between two commands is
visible in one place: run_global takes an invert flag because g and v
are the same command with the match sense reversed, and that fact is legible in
the signature rather than buried in two near-identical functions.
The naming convention is doing work too. run_ is a prefix with no meaning
except “this is a command implementation”, which is what a reader needs
from it. Grepping for fn run_ produces the command set.
6.4 A match, not a table
The obvious next thought, somewhere around the sixth command, is that this
should be a table: a HashMap<char, Box<dyn Fn(&Spec, &mut Buffer, &str) -> Action>>, registered at startup, so that adding a command is data rather than
code.
ved does not do this, and the reasoning generalizes past ed.
A match arm is checked at compile time. A misspelled command name in a table is a runtime miss. The match is also faster, which does not matter here, and shorter, which does: the table version needs a registration call, a boxed closure per command, and a lookup that can fail, in exchange for deleting a match arm. The extensibility it buys is the ability to add commands without recompiling, which is worth a great deal to a program with a plugin system and nothing at all to a program shipped as one static binary.
The argument for the table arrives when commands come from somewhere the compiler cannot see, when there are hundreds of them, or when something other than the dispatcher needs to enumerate them. ved’s help text, which does need to enumerate them, is a separate hand-written list, and chapter 14 admits what that costs.
The general form of this mistake is worth recognizing because it is expensive
and it feels like craftsmanship at the time: building the mechanism for a
variation the program does not have. The cost is not the mechanism. It is that
every future reader has to understand the mechanism before they can find out
what d does.
6.5 Errors are strings
enum Action {
Quit,
ForceQuit,
EnterInputMode,
Done,
Print(String),
Error(String),
}
The program defines no error type. Action::Error carries a String,
address.rs returns Result<_, String> in eight places, and bre.rs does not
use Result at all — a match either succeeds or returns None.
In a library this would be wrong, and straightforwardly so. A caller who
receives a String cannot branch on what went wrong without matching on
English, cannot translate it, and cannot tell a bad address from a full disk
except by reading it. Error types exist so that the caller can make decisions.
ved’s errors have one destination: a terminal, formatted with a ? in front,
read by a person. Nothing in the program branches on the kind of failure —
there is no retry, no fallback, no recovery path that differs by cause. Every
error does the same thing, which is to be printed and to leave the buffer
alone. A enum VedError { InvalidAddress, NoMatch, ... } would add a type, a
Display implementation that reproduces the strings that are already there,
and a conversion at each boundary, in exchange for nothing this program does.
The honest version of this position has a boundary on it, and the boundary is
reuse. The moment bre.rs is published as a crate — an idea that sits in ved’s
backlog — its failures acquire callers who need to branch, and String stops
being adequate. The same is true if ved ever gains a mode where an error should
be recoverable rather than reported. Neither has happened. The rule that
follows is not “errors should be strings”; it is that an error type is a
decision about what callers need to do, and a program whose only caller is a
terminal has one caller with one need.
6.6 Three commands that never got a function
dispatch is 110 lines in the released program, and it should be about 70.
Three commands are implemented inline in the middle of it rather than as
run_ functions:
"i" | "insert" => {
// Insert before the addressed line (default: current).
// Implemented as "append after address - 1", so the
// input-mode loop (which always does append_after) works
// unchanged. On an empty buffer or address 1, current
// becomes 0 (the before-first-line sentinel).
if !buf.is_empty() {
let addr = match spec.resolve(buf) {
Ok(r) => r.end,
Err(e) => return Action::Error(e),
};
buf.set_current(addr.saturating_sub(1));
}
return Action::EnterInputMode;
}
a, i, and c all do the same two things: move the current line to where
the following text should land, then return Action::EnterInputMode. They are
inline because each was three lines when it was written, and because they
return a mode change rather than output, which made them feel unlike the other
commands.
They are now eleven, fifteen, and fifteen lines, sitting between "q" and
"d" in a match that a reader is scanning to find out which commands exist.
The extraction is mechanical and nothing prevents it. It has not been done
because nothing has forced it, which is the answer in most codebases and is
worth saying rather than dressing up as a design.
The lesson is about when to notice. The cost of inline code in a dispatcher is not felt when it is written; it is felt when the dispatcher stops being readable as a list, and by then it has stopped being obvious that a rule was ever broken. The signal is structural rather than aesthetic: the arms of this match no longer all look alike.
6.7 Why all of this is testable
#[test]
fn move_into_self_errors() {
let mut buf = buf_with(&["a", "b", "c", "d", "e"]);
let act = dispatch("2,4m3", &mut buf);
assert!(matches!(act, Action::Error(_)));
assert_eq!(buf.line(3), Some("c"));
}
Build a buffer, call dispatch with a string, assert on the value that comes
back and on the buffer afterwards. No process is spawned, no terminal is
faked, no output is captured and parsed, and the test runs in microseconds.
Most of ved’s 123 tests are that shape, and they are that shape because of the
decision in chapter 2 and nothing else. A dispatch that printed would need
its output captured, which in Rust means either threading a Write through
every command or replacing stdout globally, and the tests would assert on
formatted text, so changing a message would break tests that were not about
messages.
Chapter 15 is about the parts this does not cover, of which there are more than the passing count suggests. The panic in chapter 5 lived under 122 green tests.
6.8 What to take from it
Four things, and none of them are about ed.
The program’s I/O happens in one function. Everything else returns values.
The command language is one function that reads like a list of what the commands are, and the rule is that new commands are arms rather than conditions.
The state is small enough to enumerate and it lives with whoever owns the
concept: the text in Buffer, the session in run_repl, nothing in
dispatch.
And the shape stopped changing after four slices. That is the return on the decisions in chapters 2 through 5, and it is why the next three chapters can build a regex engine without once mentioning the REPL.
Exercise 6-1. Extract a, i, and c into run_append, run_insert,
and run_change. Then decide what their return type should be, given that they
change the buffer’s current line and return a mode change rather than output.
Exercise 6-2. Write the table-driven dispatcher from section 6.4 for the
five commands in examples/ch05-write. Count the lines, then decide what would
have to be true about the program for the answer to flip.
Exercise 6-3. Define an error enum for address.rs with the three cases it
actually produces, convert the eight Result<_, String> signatures, and see
what happens at the call sites in dispatch. Keep it only if they got better.
Exercise 6-4. run_repl grew from 75 lines to 95 across eight more slices.
Pick a program you have written with a main loop, measure the same two numbers,
and if the answer is worse, find the command that should have been a value.
7. A Regex Engine: The Recursive Matcher
ed’s s command takes a regular expression, and so do g and v. The
standard ed dialect is POSIX Basic Regular Expressions, which the regex crate
does not implement, and this program has no dependencies anyway. So the engine
gets written.
It takes three chapters and ends at a thousand lines, which is a third of the finished program. This one covers the first forty-three.
7.1 A slice that adds no capability
Chapter 1 stated the rule that makes slicing work: each slice is a complete
working program with one more capability than the previous. Slice 5 breaks it,
and the plan says so by splitting it in two. 5a is the engine. 5b is the s
command that uses it.
At the end of 5a the program does what it did at the end of slice 4. Running the two crates side by side produces identical output, because the new module is not connected to anything:
mod address;
#[allow(dead_code)] // unused until slice 5b wires it to the substitute command
mod bre;
mod buffer;
That attribute is the honest version of a compromise. Without it the build is noisy with warnings about unused functions, and a warning that is always present is a warning nobody reads. With it, the lint is suppressed for one module, and the comment says what will make the suppression unnecessary.
The rule to take from it is about lint suppressions generally: one that names
its expiry is a note, and one that does not is a decision nobody will revisit.
#[allow(dead_code)] with no comment on a module is indistinguishable from
#[allow(dead_code)] on code that is genuinely dead.
The deeper question is whether splitting the slice was right, given that the
point of a slice is to leave something that runs. The alternative was one slice
containing both engine and command, finished in one stretch, with nothing
working in the middle. What the split buys is that the engine gets built
against its own tests rather than against s, which matters more here than
usual: a regex bug reached through a substitute command presents as “the wrong
text changed”, and the same bug reached through match_any(b"a*b", b"xb")
presents as itself.
The rule survives, with a footnote. A slice that produces no capability is acceptable when it produces a component with its own tests, and it is the only case where it is acceptable.
7.2 The matcher being translated
The starting point is the recursive matcher from Kernighan and Pike’s The
Practice of Programming: roughly thirty lines of C that handle literal
characters, ., *, ^, and $. It is famous for the ratio — a usable
subset of regular expressions in a page of code that can be read in one sitting
— and it works by treating the pattern as a program and recursing down it.
Three functions, mutually recursive:
pub fn match_any(pattern: &[u8], mut text: &[u8]) -> bool
fn match_here(pattern: &[u8], text: &[u8]) -> bool
fn match_star(c: u8, pattern: &[u8], mut text: &[u8]) -> bool
match_any finds a match anywhere. match_here requires one at the start.
match_star handles a repeated element. That is the design, and the next
three sections are the three functions.
7.3 Three decisions in the translation
The module comment records them, which is the right place for them: they are facts about this code that a reader will otherwise rediscover.
// * Pike's C uses `char *` and advances pointers with `regexp+1`.
// We use `&[u8]` slices and `&pattern[1..]` — mechanically the
// same, safer at the language level.
// * Pike reads past the end of the string freely because C strings
// are null-terminated: `regexp[1]` on a one-char pattern reads
// the '\0'. Rust slices panic on out-of-bounds access, so we
// guard each lookahead with a length check.
// * Pike's function is named `match`, which is a Rust keyword.
// Ours is `match_any`.
The middle one is the interesting one, and it is the general shape of porting C
to Rust. The C original is not sloppy; it is correct because of an invariant
the language provides, namely that there is always a readable byte at the end
of a string. Rust provides a different invariant, that a slice knows its own
length and indexing past it is a panic rather than a read. The translation has
to add explicitly what the source language supplied implicitly, which is why
match_here has a pattern.len() >= 2 that the C has no equivalent of.
Ports go wrong when this is treated as noise. Every one of those length checks
corresponds to a place the original depended on the terminator, and dropping
one produces a panic on a pattern like a* where the lookahead runs off the
end.
Working in &[u8] rather than &str is the third decision, unstated because
it follows from the first. It also means . matches a byte rather than a
character, which is correct for ASCII and wrong for anything else; chapter 9
comes back to it.
7.4 match_any: slide along the text
pub fn match_any(pattern: &[u8], mut text: &[u8]) -> bool {
if !pattern.is_empty() && pattern[0] == b'^' {
return match_here(&pattern[1..], text);
}
// Try each starting position, INCLUDING the empty tail, so that
// `$` against `""` still gets a chance to match.
loop {
if match_here(pattern, text) {
return true;
}
if text.is_empty() {
return false;
}
text = &text[1..];
}
}
An unanchored pattern matches anywhere, which is implemented by trying here
at every position. Two details carry their weight.
^ is handled once, at the top, and then removed from the pattern. It is
not a case inside match_here, because ^ does not mean “start of text”
recursively — it means “do not slide”. Having stripped it, the rest of the
engine never sees it. A ^ in the middle of a BRE is a literal caret, and this
structure gives that for free rather than as a special case.
The empty tail is a position. The order of the two checks inside the loop
is the point: match_here runs before the is_empty test, so when
text has been consumed down to nothing there is still one attempt. Without
that, $ against any text would fail, because $ only matches when the
remaining text is empty and the loop would have exited first. There is a test
named dollar_alone_finds_end whose only job is to hold that ordering in
place.
7.5 match_here: peel one element
fn match_here(pattern: &[u8], text: &[u8]) -> bool {
if pattern.is_empty() {
return true;
}
// Lookahead: if the next element is `*`, hand off to match_star.
if pattern.len() >= 2 && pattern[1] == b'*' {
return match_star(pattern[0], &pattern[2..], text);
}
// `$` only anchors when it's the last character of the pattern.
// Everywhere else it's a literal, which is what BRE actually
// specifies.
if pattern[0] == b'$' && pattern.len() == 1 {
return text.is_empty();
}
// Otherwise match one character (literal or `.`) and recurse.
if !text.is_empty() && (pattern[0] == b'.' || pattern[0] == text[0]) {
return match_here(&pattern[1..], &text[1..]);
}
false
}
Four branches, in an order that is not arbitrary.
The empty pattern returns true, because a pattern with nothing left has matched
everything it asked for. This is the base case of the recursion and the reason
match_any(b"", anything) is true.
The * lookahead comes second, before anything else looks at pattern[0],
because a* is one element and not two. A design that peeled a first and
then discovered * would have to un-consume it.
The $ rule is a specification detail, and getting it right is a small
argument for cloning something with a written standard. In POSIX BRE, $ is an
anchor only as the final character of the expression; a$b matches a literal
dollar sign. Most people’s intuition, informed by Perl-style regex, is that $
is always an anchor. The comment states the rule so the next reader does not
“fix” it.
The last branch is the one people picture when they picture a regex engine, and it is three lines: if there is text and the pattern character matches it, drop one from each and recurse.
7.6 match_star, and the bug it shipped with
/// Search for `c*pattern` at the beginning of `text`. Tries zero
/// matches of `c` first, then one, then two, and so on, until
/// either the tail pattern matches or `c` stops consuming.
fn match_star(c: u8, pattern: &[u8], mut text: &[u8]) -> bool {
loop {
if match_here(pattern, text) {
return true;
}
if text.is_empty() {
return false;
}
if text[0] != c && c != b'.' {
return false;
}
text = &text[1..];
}
}
Zero repetitions first, then one, then two, stopping at the first success. The
doc comment describes the behavior accurately, the twenty-three tests pass, and
for answering “does this match?” the function is correct: a pattern that
matches with three repetitions also matches with the shortest number that
works, and match_any returns a bool.
It is the wrong answer as soon as the caller wants to know what matched.
POSIX specifies leftmost-longest: of all matches starting at the earliest
position, a BRE matches the longest one. This function finds the shortest.
While the engine only returns true or false the difference is invisible,
which is why it survived this chapter and the next two. Once it is
wired to s, it is visible on the first try:
$ cargo run -q -p ch10-substitute
a
aaa
.
s/a*/X/
,p
Xaaa
a* matched zero characters at position 0, so X was inserted in front and
the three a’s remain. POSIX requires X. The released program produces X;
this was fixed in v0.1.3, well after ed scripts had been run against it.
Two things are worth taking from that, and neither is “check your star”.
The first is about borrowed code. The matcher was copied from a famous, correct program, and it was copied correctly. What did not come with it was the question of whether the specification the new program is implementing has a requirement the original never claimed to meet. The original answers “does this match”, which is a complete and honest answer to the question it was written for.
The second is about where the bug was visible. Not in match_star, where the
code is four lines and matches its own comment. Not in the tests, which all
pass. It appears in the output of a command two slices away, and the path back
from Xaaa to a loop that tries zero first is the path this chapter’s
split of slice 5 was meant to shorten. It did not shorten it, because the bug
is not in the layer the tests covered — it is in the agreement between the
layer and the standard.
Chapter 15 has a name for this and a way to test for it.
7.7 Twenty-three tests for forty-three lines
#[test]
fn star_combined_with_slide() {
// Exercises both the outer slide and match_star's zero case:
// at position 0, `a*b` fails because `xb` starts with x.
// We slide to position 1 and match `b` with zero a's.
assert!(match_any(b"a*b", b"xb"));
}
That is one test for every two lines of code, which is high, and the right number for this module and the wrong number for most others. What makes it right is that this is a pure function over two byte strings with no I/O, no state, and a specification someone else wrote. Every test is one line of setup and one assertion, they run in microseconds, and the input space is small enough to cover the interesting corners by hand.
The names are the documentation: caret_refuses_to_slide,
dollar_anchors_at_end, empty_anchored_matches_empty,
anchored_star_rejects_wrong_char. A failure prints the name, and the name is
the sentence you would have written in a bug report.
The comment in the test above is the other half. It explains which code path the case is reaching, which is what a reader needs when the test fails two years later and the obvious reading of the assertion does not suggest why it ever mattered.
What the twenty-three do not do is compare against another implementation. They encode what the author believed POSIX required, which is why they are all green in a chapter that ends with a shipped deviation from POSIX.
7.8 What slice 5a bought
Forty-three lines of code, in three mutually recursive functions, answering
whether a byte string matches a pattern containing literals, ., *, ^, and
$. They sit in a 221-line file, because the other hundred and sixty are tests
and the comment explaining the translation, and they are connected to nothing.
That is a fraction of BRE. Bracket expressions, escaped specials, groups, and backreferences are all missing, and the structure that makes this version readable — the pattern is the program, walked by recursion — is the structure that has to be replaced to get them. Chapter 8 replaces it.
Exercise 7-1. Make match_star greedy: consume as many repetitions as
possible, then back off one at a time until the tail matches. Check
^a*$ against aaa, a*b against xb, and a* against the empty string
before you believe it.
Exercise 7-2. Delete the pattern.len() >= 2 guard in match_here and
find the pattern that panics. Then explain, in one sentence, what the C
original does instead.
Exercise 7-3. Add + (one or more) to the engine. It is not in BRE, so
decide first whether a clone should have it, then implement it in terms of the
functions that exist.
Exercise 7-4. . matches one byte. Write the test that demonstrates the
problem using a multi-byte character, then decide whether the fix belongs in
match_here or in whoever calls the engine.
Exercise 7-5. The twenty-three tests all pass against an engine that deviates from POSIX. Write one test, in the shape they are written in, that would have failed.
8. A Regex Engine: Compiling the Pattern
The matcher in chapter 7 treats the pattern as a program and walks it with
recursion. That works for literals, ., *, ^, and $, all of which are
one byte. It stops working at the next feature in BRE.
[a-z] is one matchable thing spelled with five bytes. So is [^abc], and so
is []]. The recursive matcher looks at pattern[0] and peeks at
pattern[1], and neither tells it anything useful about a bracket expression.
Handling them in that shape means scanning forward for the closing ] on every
match attempt, at every position in the text, and then doing it again to find
out whether a * follows.
The fix is the one Ken Thompson used in the original ed: turn the pattern into a data structure once, and match against that.
This chapter is the compile step and bracket expressions. The crate is
examples/ch08-bre, which contains the end state of slice 5a; the parts of it
dealing with groups and backreferences are chapter 9.
8.1 Two types, and the difference between them
/// One matchable thing: a literal byte, any-byte wildcard, or
/// a bracket character class.
enum Atom {
Literal(u8),
Dot,
Class { negated: bool, chars: Vec<u8> },
}
/// One element of a compiled pattern.
enum Element {
One(Atom),
Star(Atom),
Caret,
Dollar,
GroupStart(usize),
GroupEnd(usize),
BackRef(usize),
}
An Atom answers one question: does this byte match? An Element is an
instruction in the compiled pattern, and most instructions are about an atom
rather than being one.
The split is what the design turns on, so it is worth stating plainly.
Dot is an Atom because . matches a byte. Dollar is an Element
because $ matches a position and consumes nothing. Star is an Element
because repetition is a thing you do to an atom, not a thing that matches.
Putting them in one enum would work and would mean every function that handles
atoms has arms for cases that cannot occur there.
Class carries its characters already expanded: [a-z] compiles to a Vec<u8>
of twenty-six bytes. Storing the ranges and testing membership arithmetically
would use less memory and more code. For patterns typed by a person at an
editor the difference is invisible, and the expanded form makes
atom_matches a three-line function:
fn atom_matches(atom: &Atom, byte: u8) -> bool {
match atom {
Atom::Literal(c) => byte == *c,
Atom::Dot => true,
Atom::Class { negated, chars } => {
let found = chars.contains(&byte);
if *negated { !found } else { found }
}
}
}
contains on a Vec<u8> is a linear scan, which for a class of twenty-six is
faster than anything cleverer. There are only 256 distinct bytes to name, so a
class written by a person stays well inside the range where the scan wins.
8.2 The compiler is a loop
pub fn compile(pattern: &[u8]) -> Regex {
let mut elements = Vec::new();
let mut i = 0;
// ^ only anchors at the very start of the pattern.
if i < pattern.len() && pattern[i] == b'^' {
elements.push(Element::Caret);
i += 1;
}
while i < pattern.len() {
// $ only anchors at the very end of the pattern.
if pattern[i] == b'$' && i + 1 == pattern.len() {
elements.push(Element::Dollar);
i += 1;
continue;
}
// ... backslash sequences ...
// Parse one atom.
let (atom, next) = parse_atom(pattern, i);
i = next;
// If followed by *, wrap in Star; otherwise One.
if i < pattern.len() && pattern[i] == b'*' {
elements.push(Element::Star(atom));
i += 1;
} else {
elements.push(Element::One(atom));
}
}
Regex { elements }
}
A cursor, a vector, and a loop. No recursion, no grammar, no parser generator, because BRE without alternation is a flat sequence — there is nothing to nest except groups, which are markers rather than structure.
The anchors moved out of the matcher and into the compiler, and this is the
improvement that is easy to miss. Chapter 7’s match_here had to ask, on every
call, whether pattern[0] == b'$' && pattern.len() == 1. Here the question is
asked once per pattern, at compile time, and the answer is recorded as an
Element::Dollar that means “anchor” and nothing else. A $ in the middle of
the pattern never becomes a Dollar at all; it falls through to parse_atom
and becomes Literal(b'$'). The specification rule from chapter 7 is now
enforced by the shape of the compiled output rather than re-derived at every
step.
The * handling has the same character. Chapter 7 looked ahead for * during
matching. Here the lookahead happens once, and Star(atom) versus One(atom)
is decided before any text is seen.
8.3 Bracket expressions, and POSIX’s awkward corners
/// Follows POSIX BRE bracket rules:
/// - `]` as the first character (after optional `^`) is literal
/// - `-` at the start or end is literal, not a range
/// - `a-z` in the middle is a range, expanded inline
/// - `[^...]` negates the class
fn parse_bracket(pattern: &[u8], start: usize) -> (Atom, usize) {
Those four rules exist because bracket expressions have no escape character.
Inside [...], a backslash is a literal backslash, so ] and - cannot be
escaped and the specification instead gives them positions where they lose
their meaning. []] is a class containing ]. [a-] is a class containing
a and -. []-] is both.
The implementation follows the rules positionally, which is the only way:
// ] as the very first character (after optional ^) is literal.
if i < pattern.len() && pattern[i] == b']' {
chars.push(b']');
i += 1;
}
while i < pattern.len() && pattern[i] != b']' {
// Range: lo-hi, but only when - is followed by a char
// that isn't the closing ].
if i + 2 < pattern.len()
&& pattern[i + 1] == b'-'
&& pattern[i + 2] != b']'
{
let lo = pattern[i];
let hi = pattern[i + 2];
for c in lo..=hi {
chars.push(c);
}
i += 3;
} else {
chars.push(pattern[i]);
i += 1;
}
}
This is the part of the engine where having a written specification pays for
itself twice over. Nobody’s intuition produces “a ] immediately after the
opening bracket is literal”, and nobody would defend it as a design. It is
there because ed did it in 1969 and every tool since has copied it, and a
clone that guessed differently would break scripts in a way that looks like a
bug in the script.
for c in lo..=hi expands the range with no check that lo <= hi. A reversed
range like [z-a] produces an empty iterator and therefore an empty class,
which matches nothing. POSIX says the behavior is undefined. Producing an empty
class is a defensible reading of undefined, and it is not what GNU ed does: ed
rejects the command and, with H set, says Invalid range end.
8.4 A pattern that cannot fail to compile
pub fn compile(pattern: &[u8]) -> Regex
There is no Result. Every byte string is a valid pattern, and this is a
decision rather than an oversight — it is the same signature in the released
program.
What it means in practice:
$ ved
a
xaybzc
.
s/[abc/X/g
,p
xXyXzX
[abc has no closing bracket. The loop in parse_bracket runs to the end of
the pattern, the “skip the closing ]” step finds nothing to skip, and the
result is a class containing a, b, and c. The substitution then does
something entirely reasonable and not what POSIX says, which is that an
unmatched [ is an error.
The appeal of a non-failing compiler is real. There is no error type, no
Result threaded from compile through run_substitute to Action::Error,
and no question about what to do with a half-compiled pattern. The cost is that
a typo becomes a silent behavior change. A user who types s/[abc/X/ meant
something, and what they get is neither an error nor what they meant.
The version with errors is not hard — compile returns Result<Regex, String>,
parse_bracket reports an unterminated class, and the two call sites already
have an Action::Error to return it through. It was not done, and the reason
is the ordinary one: the first version did not need it, and nothing since has
forced the question. Chapter 19 is where the backlog records that kind of debt
honestly, and this is one of the entries.
8.5 From a bool to a position
pub struct Regex {
elements: Vec<Element>,
}
/// The result of a successful match: byte offsets into the text,
/// plus any captured groups.
pub struct Match {
pub start: usize,
pub end: usize,
caps: Caps,
}
pub fn find(&self, text: &[u8]) -> Option<Match>
Chapter 7’s engine answered whether a pattern matched. That is enough for g
and v, which select lines, and useless for s, which has to replace the
matched span and therefore has to know where it is.
Option<Match> rather than Match with a sentinel, and start/end as byte
offsets into the text rather than a borrowed slice. The offsets are the choice
worth noticing: returning &[u8] would tie the Match to the lifetime of the
text, and run_substitute wants to build a new line out of the pieces before
and after the match, which means it wants indices.
The slide moved into find, where it can be written once:
let anchored = !elements.is_empty()
&& matches!(elements[0], Element::Caret);
let elems = if anchored { &elements[1..] } else { elements };
let mut offset = 0;
loop {
let caps = Caps::new();
if let Some((len, caps)) =
self.match_here(elems, &text[offset..], offset, caps, text)
{
return Some(Match { start: offset, end: offset + len, caps });
}
if anchored || offset >= text.len() {
return None;
}
offset += 1;
}
The anchor check is the same trick as chapter 7 — strip the Caret and refuse
to slide — expressed against the compiled form. The offset >= text.len()
test after the match attempt preserves the empty-tail behavior that $ depends
on, and it is the same ordering, now with a comment’s worth of distance between
the two versions.
match_here returns Option<(usize, Caps)>: how many bytes were consumed, and
the capture state. The length has to come back because the caller adds it to
offset to get end, and because match_star needs it to account for what a
repetition consumed. Chapter 7 could return bool because nobody downstream
cared how much was eaten.
8.6 A defensive arm, and a comparison
Element::Caret => None,
compile emits Element::Caret only at position 0, and find strips it
before calling match_here. A Caret can therefore never reach this arm.
Chapter 4 had the same situation — a state the type permits and the code never
produces — and answered it with unreachable!("parser never produces (None, Some)"). Here the answer is None, which is to say: if this impossible thing
happens, the match fails.
The second answer is better, and the difference is what happens when the
assumption stops holding. A future change that emits a Caret in the middle of
a pattern turns the unreachable! into a crash for the user and the None
into a pattern that does not match. Both are wrong. One of them loses the
buffer.
The rule that falls out is narrow enough to apply: when an unreachable case has
a sensible failure value, return it. Keep unreachable! for the cases where
there is no such value and continuing would corrupt something.
8.7 The limitation visible in the types
enum Element {
One(Atom),
Star(Atom),
Star holds an Atom, so * can repeat one matchable thing. It cannot repeat
a group:
$ ved
a
ababX
.
s/\(ab\)*/Y/
? no match
The module comment says so:
Known limitation:
\(...\)*(star applied to a whole group) is not yet supported. Star can only apply to a single atom. This is uncommon in ed usage and can be added later if needed.
What makes this a good limitation to have is that it is not a bug hiding in a
branch. It is the shape of the type. Star(Atom) says what it can repeat, and
anyone reading the enum knows the answer before reading a line of matching
code. The fix is equally visible: Star would have to hold something that can
represent a sequence, which means either a boxed sub-pattern or a pair of
indices into elements, and the matcher would have to try repetitions of a
compiled span rather than of a single byte test.
Compare that to the star greediness from chapter 7, which was also a limitation, also documented in a doc comment, and completely invisible in the types. One of the two was found by reading the code. The other was found by a user.
8.8 What the compile step bought
Bracket expressions, which is what it was for. Escaped specials, because the
compiler has a place to turn \. into Literal(b'.') before any matching
starts. Positions instead of a boolean, which is what makes s possible in the
next chapter but one. And a representation that groups and backreferences can
be added to as two more Element variants rather than as another lookahead in
the matcher — which is chapter 9.
It cost the property that made chapter 7’s version worth showing: you can no longer read the engine in one sitting. The file went from 221 lines to 823, and the part a reader has to hold in their head went from three functions to three functions plus two enums, a compiler, and the invariant that connects them.
Exercise 8-1. Make compile return Result<Regex, String>, reporting an
unterminated bracket expression. Follow the error to run_substitute and
decide what the message should say. Count the lines it cost.
Exercise 8-2. [z-a] compiles to a class that matches nothing. Decide what
it should do, then find out what GNU ed does, then decide again.
Exercise 8-3. Write the three-line test that proves []] is a class
containing ], and the one that proves [a-] contains a hyphen. Then break
parse_bracket in the smallest way that leaves both passing.
Exercise 8-4. Implement \(...\)*. Start by writing the Element variant,
and stop when you can state what match_star would have to become — the rest
is a weekend, and the design decision is the part worth doing.
Exercise 8-5. Class stores expanded bytes. Replace it with a list of
ranges plus a list of singletons, and measure the compile time and match time
for [a-z] and for [0-9a-fA-F]. Report both numbers, then decide whether the
original was wrong.
9. A Regex Engine: Groups and Backreferences
Two more Element variants, one small struct, and a parameter added to three
function signatures. That is all of groups and backreferences, and it is also
the point where the thing being implemented stops being a regular
expression in the formal sense.
\(ab\)*\1 cannot be recognized by a finite automaton. A backreference asks
the matcher to remember arbitrary text and compare it later, which is outside
what regular languages can do, and it is the reason engines that promise linear
time — RE2, Go’s regexp, Rust’s regex crate — do not offer backreferences
at all. ed has had them since 1969, so this engine has them, and section 9.7 is
about what they cost.
9.1 What a group has to remember
/// Capture state for up to 9 groups, threaded through matching
/// by value. Small enough to copy on every recursive call (9
/// usizes + 9 usizes + 9 bools = ~153 bytes).
#[derive(Debug, Clone, Copy)]
struct Caps {
start: [usize; NGROUPS],
end: [usize; NGROUPS],
valid: [bool; NGROUPS],
}
Positions, not text. A group records where it began and where it ended, and anyone who wants the characters goes back to the original input and slices. Storing the text instead would mean an allocation per group per match attempt, and there are a great many failed match attempts.
The three parallel arrays are the unusual part, and valid is why. A group
that matched the empty string has start == end, and a group that never took
part in the match at all also has nothing between its offsets. Those are
different facts. In \(a\)*b matched against b, group 1 did not participate,
and \1 afterwards must fail rather than match nothing. The boolean is what
carries that distinction, because two equal usizes cannot.
Fixed-size arrays rather than Vec because the specification supplies the
bound: BRE addresses groups as \1 through \9, so nine is not a guess. No
allocation happens anywhere in the matcher, which for a structure copied on
every recursive call is the difference between a fast engine and an unusable
one.
9.2 Backtracking, for free
Element::GroupStart(n) => {
let mut caps = caps;
if *n <= NGROUPS {
caps.start[n - 1] = pos;
}
self.match_here(&elements[1..], text, pos, caps, full_text)
}
caps arrives by value, let mut caps = caps makes it mutable, the copy is
modified, and the copy is what recurses. The caller’s Caps is untouched.
That one line of shadowing is how backtracking is handled here, and it is worth
sitting with, because getting this wrong is the classic source of bugs in
hand-written matchers. A regex engine explores: it tries a branch, records
partial results, fails, and has to undo them before trying the next branch. An
implementation holding capture state behind &mut needs an explicit undo at
every failure point, and the failure points are numerous — every None return
in match_here, every extra repetition in match_star.
With Caps: Copy threaded by value, there is nothing to undo. A branch that
fails returns None and its modified copy goes out of scope. A branch that
succeeds returns Some((len, caps)) and hands its copy up. The state that
survives is the state on the path that worked, and the language enforces it
rather than the programmer remembering to.
The cost is 153 bytes copied per recursive call, which the comment states
because somebody will ask. It is the right trade at this size and it would not
be at ninety-nine groups; the version that scales differently keeps a
Vec<(usize, usize)> and an explicit undo log, and is the reason production
engines are harder to read than this one.
9.3 Markers, not structure
enum Element {
// ...
GroupStart(usize),
GroupEnd(usize),
BackRef(usize),
}
A group is not a sub-tree. It is two zero-width markers in the same flat
Vec<Element> as everything else, and matching one consumes no input and
advances no position — it writes a number and recurses onward.
Nesting is handled entirely in the compiler, with a stack:
b'(' => {
group_num += 1;
group_stack.push(group_num);
elements.push(Element::GroupStart(group_num));
i += 2;
}
b')' => {
if let Some(n) = group_stack.pop() {
elements.push(Element::GroupEnd(n));
}
i += 2;
}
Group numbers are assigned in order of opening parenthesis, which is the
universal convention, and the stack is what pairs \) with the right \( when
they nest. By the time matching starts the nesting has been flattened away
entirely.
This is the design that chapter 8’s Star(Atom) limitation comes from. Because
a group leaves no structure in the compiled form, there is nothing for * to
repeat — the elements between GroupStart and GroupEnd are not grouped in
any way the matcher can see. Supporting \(...\)* means giving the compiled
form the structure this representation deliberately discards.
The if let Some(n) = group_stack.pop() is quietly permissive: a \) with no
matching \( is dropped. Combined with the non-failing compiler from chapter
8, s/\(ab/X/ compiles to a pattern with an unmatched GroupStart, matches
ab, and substitutes — no error, and group 1 never becomes valid.
9.4 A backreference needs the whole text
Element::BackRef(n) => {
if !caps.valid[n - 1] {
return None;
}
let captured = &full_text[caps.start[n - 1]..caps.end[n - 1]];
if text.starts_with(captured) {
let clen = captured.len();
self.match_here(&elements[1..], &text[clen..], pos + clen, caps, full_text)
.map(|(len, caps)| (len + clen, caps))
} else {
None
}
}
This is why match_here has both text and full_text. text is the
remaining suffix being matched; caps holds absolute offsets into the original
input. Slicing text with them would be wrong by however much has been
consumed, so the function needs the original to look captures up in.
pos is the third of the trio, and it is the absolute position corresponding
to the start of text — carried so that GroupStart can record where it is in
the coordinate system the captures use. Three parameters to express one idea:
where we are, in two coordinate systems, plus the tape.
The valid check earns itself here. A backreference to a group that did not
participate returns None rather than matching the empty string, which is what
POSIX requires and what the test named backref_to_uncaptured_fails holds in
place.
9.5 Nine slots, and the day there were ten
The chapter you are reading found a bug while it was being written. It is ved #9, fixed in 0.2.1.
$ ved
a
abcdefghij
.
s/\(a\)\(b\)\(c\)\(d\)\(e\)\(f\)\(g\)\(h\)\(i\)\(j\)/X/
thread 'main' panicked at src/bre.rs:253:17:
index out of bounds: the len is 9 but the index is 9
Caps has nine slots because \1 through \9 are what a BRE can address.
compile numbers groups with group_num += 1 and no bound. A tenth group
produced GroupStart(10), which indexed caps.start[9], which is past the
end.
The specification is the source of the confusion, and it is worth being precise about what it says: POSIX limits how many groups can be referenced, not how many can appear. GNU ed accepts the pattern above and substitutes normally. So this was a crash and a compatibility gap at once, and the fix follows from the distinction — record the first nine, let the rest delimit without being recorded:
if *n <= NGROUPS {
caps.start[n - 1] = pos;
}
Since groups leave no structure for the matcher to use, a group that is not
recorded is a group that costs nothing. The nine also became a named constant
rather than a literal appearing in the struct, its constructor, and
Match::group, which is how the bug was able to hide: three places agreed on a
number, and a fourth place generated it.
This is the second panic in this book found the same way, after chapter 5’s, and both have the same shape: an index derived from user input, bounded by an assumption held somewhere else in the file. The first was bounded by “the command letter is one byte”. This one by “there are at most nine groups”. Neither assumption was written down anywhere the compiler could see it.
9.6 Six parameters
fn match_here(
&self,
elements: &[Element],
text: &[u8],
pos: usize,
caps: Caps,
full_text: &[u8],
) -> Option<(usize, Caps)>
Chapter 7’s version took two arguments and returned a bool. This one takes
six and returns a tuple in an Option, and every addition paid for itself when
it arrived: pos for group positions, caps for the captures,
full_text for backreferences, the usize in the return so the caller can
compute the end of the match.
It is still too many, and the shape of the fix is standard: three of those six
never change during a match. full_text is fixed, &self is fixed, and
elements changes only by being advanced. A struct holding the invariant parts,
with text, pos, and caps as the moving state, would make the signature
two arguments and a method call.
That it was not done is the same answer as chapter 6’s inline commands: nothing forced it. The signal to watch for is the one visible above — when a parameter list grows past what fits on a line, and rustfmt breaks it one-per-line, the formatter is reporting something.
9.7 What backtracking costs, measured
This engine tries possibilities until one works. With one star in a pattern that is linear. With several, the possibilities multiply.
The pattern a*a*a*a*a*a*a*a*b matched against a string of n a’s and no b
has to try every way of splitting the a’s among the eight stars before it can
report failure. Measured against the release binary:
| a’s | a*a*a*a*a*a*a*a*b |
|---|---|
| 16 | 0.045s |
| 20 | 0.161s |
| 24 | 0.454s |
| 28 | 1.137s |
| 32 | 2.86s |
Every two characters roughly doubles the time. Forty characters would be about a minute, fifty about half an hour, and the line is not long — it is shorter than this sentence.
The same text with the pattern a*b takes 0.001s.
This is not a defect in the implementation; it is what backtracking is. The engines that avoid it — Thompson’s NFA simulation, which tracks the set of states reachable at each position rather than exploring paths one at a time — run in time proportional to pattern length times text length, always. They also cannot do backreferences, because tracking a set of states means not knowing which path you took, and a backreference is a question about the path.
So the choice is not between a good algorithm and a bad one. It is between two
languages: regular expressions, which are fast and cannot express \(a\)\1, and
the thing ed actually specifies, which can. ed chose in 1969 and a clone
inherits the choice.
Whether it matters here is a separate question, and the answer is mostly no. ed
patterns are typed by a person, applied to one line at a time, and the
pathological shapes do not occur in anything anyone types on purpose. The place
it could bite is g/pattern/ over a large file, where a bad pattern is applied
to every line. Nothing in the program guards against it — there is no step
limit and no timeout — and adding one is in the same category as chapter 8’s
compile errors: known, cheap, not done.
9.8 The engine matches bytes
fn atom_matches(atom: &Atom, byte: u8) -> bool
Everything in this engine is a u8. Atom::Dot matches any byte, One
advances by one byte, and bracket classes hold bytes. For ASCII that is correct
and fast. For anything else it is wrong, and the way it is wrong is the worst
of the available options:
$ ved
a
café
.
s/./Y/g
,p
YYYYY
Five replacements for four characters, because café is five bytes and é is
two of them. GNU ed prints YYYY.
The damaging case is a match that covers part of a character:
$ ved
a
café
.
s/f./Z/
w out.txt
wrote 7 bytes to out.txt
f. consumed the f and the first byte of é. The second byte was left
stranded, and run_substitute rebuilds the line with
String::from_utf8_lossy, which replaces the stranded byte with U+FFFD. The
file on disk holds caZ followed by EF BF BD. The character is gone, no
error was printed, and the buffer is no longer what the user had.
A text editor that silently alters text it was not asked to alter has a problem, and this one is worse than a crash: a crash loses the buffer and the user knows. This loses one character and looks like it worked. It became ved #10, and chapter 19 tells how it was fixed.
The README says, under “Limitations worth knowing”, that “UTF-8 text with multi-byte characters works”. That sentence is the part of this that a reader of chapter 1 should recognize — a document stating what is true, which is no longer true, and which nobody checked because nothing tests it.
The fix is not small. Byte orientation is correct for the \0NN octal escapes
and it is why the engine is simple, so making . character-aware means
teaching One, Star, and the bracket parser to work in characters while
keeping literal bytes addressable. There is a cheaper first step that removes
the data loss without touching the engine: have run_substitute refuse a match
whose boundaries fall inside a character, and report it. That converts silent
corruption into an error message, which is the property an editor most needs.
Chapter 19 is where an entry like this one gets written down rather than
discovered.
9.9 What slice 5a ended with
An 823-line module implementing literals, ., *, ^, $, bracket
expressions with POSIX’s positional rules, escaped specials, capturing groups,
and backreferences, with its own tests and no connection to the rest of the
program.
It cannot repeat a group, it cannot fail to compile, it matches bytes rather than characters, and it can be made to run for half an hour by a fifty-byte pattern. Three of those four are written down in the module comment or the backlog. The one that was not is the one that corrupts data.
Slice 5b, next chapter, is the two hundred lines that connect it to the s
command.
Exercise 9-1. Make Caps hold Vec<(usize, usize)> behind a &mut and
add the undo logic that failed branches now need. Count the places that need
it, then put the original back.
Exercise 9-2. Write the implementation of the interim UTF-8 fix from
section 9.8: reject a match whose start or end is not on a character boundary.
str::is_char_boundary does the work. Then decide what the error message says.
Exercise 9-3. Add a step limit to the matcher: a counter threaded through
match_here, and a failure when it is exceeded. Pick the number by measuring,
then work out what g/pattern/ should do when one line hits the limit.
Exercise 9-4. s/\(ab/X/ substitutes rather than erroring. Decide whether
an unmatched \( should be an error, then find out what GNU ed does, then
write the test.
Exercise 9-5. Collapse match_here’s six parameters into a struct plus
three. Do it for real, run the tests, and then decide whether the call sites
read better. They might not.
10. Substitute
Slice 5b connects the regex engine to a command. It is the slice the previous three chapters were for, and it is where ed stops being a way to type text and becomes a way to change it.
$ cargo run -q -p ch10-substitute
a
the cat sat on the mat
.
s/at/og/
the cog sat on the mat
s/at/og/g
the cog sog on the mog
s|o|/|g
the c/g s/g /n the m/g
s/the/[&]/g
[the] c/g s/g /n [the] m/g
The code is about a hundred and sixty lines in main.rs and fifty in bre.rs,
and it has four parts: a scanner that splits /old/new/g into its fields, an
expander that turns & and \1 into text, a loop that applies the pattern to a
line once or repeatedly, and the command itself, which applies that to a range.
The engine does not change at all. That was the point of building it in
isolation.
This chapter also found more bugs than any other in the book. Most of them are
in the scanner and in the loop behind the g flag, sections 10.2 and 10.4.
10.1 The command, as a grammar
[range]s/pattern/replacement/[flags]
The first character after s is the delimiter, and it can be anything. / is
the convention, | is what people use when the pattern contains slashes, and
ed accepts s.a.b. as readily as either. The delimiter is the reason s
cannot have a long-form alias: subst/a/b/ would make u the delimiter of a
command named s, and chapter 14 comes back to that.
fn run_substitute(spec: &Spec, buf: &mut Buffer, args: &str) -> Action {
let args = args.as_bytes();
if args.is_empty() {
return Action::Error("no delimiter".to_string());
}
let delim = args[0];
let args = &args[1..]; // skip delimiter
let (pattern, rest) = match scan_delimited(args, delim) {
Some(r) => r,
None => return Action::Error("unterminated pattern".to_string()),
};
let (replacement, rest) = match scan_delimited(rest, delim) {
Some(r) => r,
None => return Action::Error("unterminated replacement".to_string()),
};
let global = rest.contains(&b'g');
The function converts to bytes on its first line and never goes back. That is
the decision chapter 5’s panic made safe, since args[1..] on a &[u8] cannot
land inside a character the way the same slice on a &str can. A delimiter
that is itself a multi-byte character fails differently: only its first byte is
taken as the delimiter, and each field starts with the stray byte after it.
That is a wrong answer rather than a crash, and nobody has ever typed it.
Two things in that block are less careful than they look.
The closing delimiter is required. s/a/b with nothing after the b is
? unterminated replacement in ved and a working substitution in ed, where the
final delimiter is optional and the line’s end closes the replacement. It is
the most common way to type s in practice, and it is a script that does not
run unchanged. Filed as ved #23.
The flags are a search, not a parse. rest.contains(&b'g') asks whether a
g appears anywhere in what is left. It does not ask what else is there:
s/a/b/gq
bbb
s/a/b/2
baa
ed answers the first with ? Invalid command suffix and the second by
replacing the second match, aba, because a number is a flag that selects
the nth occurrence. ved accepts the garbage, ignores the count, and does
something plausible with both. Chapter 8 called this a non-failing compiler
when it happened to bracket expressions, and the cost is the same here: a typo
becomes a different command rather than an error, and the user who typed 2
meant something by it. Filed as ved
#24.
The general rule is the one from chapter 2’s argument parser, applied one level
down. Start strict. A suffix parser that rejects everything it does not know
can learn p and 2 later without breaking anybody. One that accepts
everything has already promised that gq works.
10.2 What a field is
/// Scan a delimiter-terminated field, handling backslash escapes.
/// Returns the field content (with escapes preserved for the BRE
/// engine) and the remainder after the closing delimiter.
fn scan_delimited(input: &[u8], delim: u8) -> Option<(Vec<u8>, &[u8])> {
let mut result = Vec::new();
let mut i = 0;
while i < input.len() {
if input[i] == delim {
return Some((result, &input[i + 1..]));
}
if input[i] == b'\\' && i + 1 < input.len() {
if input[i + 1] == delim {
// Escaped delimiter: include just the delimiter
result.push(delim);
i += 2;
} else {
// Other escape: pass through as-is for the BRE
// engine or replacement expander to interpret.
result.push(input[i]);
result.push(input[i + 1]);
i += 2;
}
} else {
result.push(input[i]);
i += 1;
}
}
None // no closing delimiter found
}
The same function scans the pattern and the replacement, which is right,
because the rule for where a field ends is the same in both: at the first
delimiter not preceded by a backslash. The return shape is chapter 4’s again,
“what I found and where I stopped”, and the None is how unterminated pattern gets its own message rather than being reported as something stranger
further along.
The comment says escapes are preserved for whoever reads the field next, and
that is true of every escape except one. An escaped delimiter is unescaped:
\/ becomes /. That is the reason the function returns a Vec<u8> rather
than a slice of its input. It has to build a new string, because the field it
returns is not a substring of the field it was given.
It is also a bug, and the comment explains why without noticing. If every other
escape is kept for the next reader to interpret, then the next reader is the
one who knows what an escape means, and the scanner has just decided one on its
behalf. When the delimiter is / the decision is harmless, since / means
nothing to a BRE. When the delimiter is a character the engine treats as
special, the backslash that made it literal is gone before the engine sees it:
$ ved
a
axb
.
s.a\.b.X.
X
\. was the user’s way of saying “a literal dot that is not the end of the
field”. The scanner turned it into ., which the engine reads as any
character, and axb matched. GNU ed says ? No match. The same thing happens
to s*x\*y*Z*, which ved compiles as x*y, and to \& in a replacement
delimited by &, which ved expands into the matched text instead of a literal
ampersand. Filed as ved #21.
The fix is to stop interpreting. The scanner’s job is to find the end of a field, and it can do that without changing a byte:
fn scan_delimited(input: &[u8], delim: u8) -> Option<(&[u8], &[u8])> {
let mut i = 0;
while i < input.len() {
if input[i] == delim {
return Some((&input[..i], &input[i + 1..]));
}
if input[i] == b'\\' && i + 1 < input.len() {
i += 2;
} else {
i += 1;
}
}
None
}
Every escape now reaches the next stage intact. The pattern compiler already
handles \X for an arbitrary X as a literal X, which is what POSIX
requires, so \. is a dot and \/ is a slash without either one being a
special case. The replacement expander needs one arm changed, from “push the
backslash” to “push the character after it”, which also corrects a second
difference from ed: s/b/\n/ on abc produced a\nc in ved and anc in ed.
With both changes, the scanner returns a borrowed slice and allocates nothing,
and the 125 tests in the crate still pass.
That is the shape of this bug in general and it is common in hand-written parsers: a lexer that does a little interpretation “while it is there”, for the case its author was thinking about, and destroys information a later stage needed for a case the author was not. The tell is in the comment. A function that preserves escapes for someone else should preserve all of them.
10.3 & and \1
/// Expand a replacement string using match results.
///
/// Handles ed's replacement conventions:
/// - `&` is replaced with the entire matched text
/// - `\1`-`\9` are replaced with captured group contents
/// - `\&` is a literal ampersand
/// - `\\` is a literal backslash
/// - Everything else is literal
pub fn expand_replacement(replacement: &[u8], m: &Match, text: &[u8]) -> Vec<u8> {
The replacement is not a string. It is a template, and expanding it needs the
match: its span for &, its captures for \1. That is why this function lives
in bre.rs rather than next to run_substitute. Match keeps its captures
private and exposes them through m.group(n), and the expander is the one
consumer outside the engine that needs them, so putting it inside the module
keeps Caps from becoming public for one caller.
It takes text as well as the match, for the reason chapter 9 gave for
full_text: a match is offsets, not characters, and offsets need the original
to be read against.
a
2026-11-20
.
s/\([0-9]*\)-\([0-9]*\)-\([0-9]*\)/\3.\2.\1/
20.11.2026
A group that did not participate expands to nothing, which is what ed does and what one of the seven tests that arrived with this function holds in place:
#[test]
fn replace_backref_uncaptured_vanishes() {
let text = b"abc";
let m = Regex::compile(b"^\\(abc\\)$").find(text).unwrap();
// \2 was never captured, so it expands to nothing
assert_eq!(expand_replacement(b"\\1-\\2", &m, text), b"abc-");
}
A reference to a group that does not exist at all is a different case, and
POSIX leaves it undefined. s/\(b\)/\2/ on abc is a2c in GNU ed, which
treats the \2 as a literal digit, and ac in ved, which treats it as an
empty group. Neither reports the mistake, and a user who typed \2 meaning
the first group gets no hint in either program.
10.4 Once, or everywhere
/// Replace the first match in `text`. Returns None if no match.
fn substitute_first(re: &bre::Regex, text: &[u8], replacement: &[u8]) -> Option<Vec<u8>> {
let m = re.find(text)?;
let mut result = Vec::new();
result.extend_from_slice(&text[..m.start]);
result.extend_from_slice(&bre::expand_replacement(replacement, &m, text));
result.extend_from_slice(&text[m.end..]);
Some(result)
}
Everything before the match, the expansion, everything after. The ? on the
first line returns None from the function when there is no match, and that
None is how run_substitute later tells a line that changed from a line that
did not. The function is seven lines and has no bugs.
The g flag is the other function, and it is the harder problem by some
distance, because “replace every match” is not a well-defined instruction until
three questions are answered. Where does the next search start? What does ^
mean when it is not at the start of the line? And what happens when the
pattern matches the empty string?
fn substitute_all(re: &bre::Regex, text: &[u8], replacement: &[u8]) -> Option<Vec<u8>> {
let mut result = Vec::new();
let mut pos = 0;
let mut matched = false;
while pos <= text.len() {
match re.find(&text[pos..]) {
Some(m) => {
matched = true;
let abs_start = pos + m.start;
let abs_end = pos + m.end;
result.extend_from_slice(&text[pos..abs_start]);
result.extend_from_slice(&bre::expand_replacement(replacement, &m, &text[pos..]));
// Advance past the match. If the match was empty,
// advance by one byte to avoid an infinite loop.
if abs_end == abs_start {
if pos < text.len() {
result.push(text[pos]);
}
pos = abs_start + 1;
} else {
pos = abs_end;
}
}
None => {
result.extend_from_slice(&text[pos..]);
break;
}
}
}
if matched { Some(result) } else { None }
}
The design is to search, replace, and search again in the slice that is left. It is the obvious design and it answers all three questions wrongly, each in a different way.
^ matches again. re.find(&text[pos..]) hands the engine a fresh slice,
and the engine has no way to know the slice is not a whole line. An anchored
pattern matches at the start of every slice it is given:
a
aaa
.
s/^a/X/g
XXX
ed prints Xaa, because there is one start of line and the anchor can match it
once.
An empty match away from pos copies the wrong byte. The empty-match
branch pushes text[pos] to step over one character. That is correct when the
empty match is at pos, and every test of this code had one there. When
the empty match is further along, which is what $ produces, pos is still
pointing at the start of the slice:
a
abc
.
s/$/!/g
abc!a
text[pos..abs_start] copied abc, the expansion added !, and the step-over
pushed text[0], which is a, to the end of the line. That is a substitution
that adds a character the user did not type and did not ask for, and it lasted
from this slice through the release of 0.2.1.
An empty match next to a real one is counted. a* matches the empty
string anywhere, including immediately after it has matched aaa:
a
baaac
.
s/a*/X/g
XbXXcX
sed prints XbXcX. The POSIX rule, which sed follows, is that an empty
match adjacent to the previous match is not a new match. Without it, the loop
replaces aaa and then replaces the nothing that follows it. GNU ed sidesteps
the question and refuses this substitution outright, with ? Infinite substitution loop. This and the anchor are filed together as ved
#22.
All three have one cause. The loop throws away context every time it slices: the engine no longer knows where the line began, and the loop no longer knows where the last match ended. The fix gives both back. The engine learns to search from a position in the whole text rather than from the start of a piece of it:
pub fn find_at(&self, text: &[u8], start: usize) -> Option<Match> {
let elements = &self.elements;
let anchored = !elements.is_empty() && matches!(elements[0], Element::Caret);
let elems = if anchored { &elements[1..] } else { elements };
if anchored && start > 0 {
return None;
}
let mut offset = start;
// ... the rest of `find`, unchanged
}
and find becomes self.find_at(text, 0). The loop keeps two positions, where
it has copied up to and where it searches next, plus the end of the previous
match:
fn substitute_all(re: &bre::Regex, text: &[u8], replacement: &[u8]) -> Option<Vec<u8>> {
let mut result = Vec::new();
let mut copied = 0;
let mut search = 0;
let mut last_end = None;
while search <= text.len() {
let Some(m) = re.find_at(text, search) else {
break;
};
if m.start == m.end && last_end == Some(m.start) {
search = m.start + 1;
continue;
}
result.extend_from_slice(&text[copied..m.start]);
result.extend_from_slice(&bre::expand_replacement(replacement, &m, text));
copied = m.end;
last_end = Some(m.end);
search = if m.start == m.end { m.end + 1 } else { m.end };
}
last_end?;
result.extend_from_slice(&text[copied..]);
Some(result)
}
Matches are now in the coordinates of the whole line, so the expander gets the
whole line and the relative-offset comment that the original needed is gone.
The step-over no longer pushes a byte at all: skipping a position changes
search and leaves copied alone, so the skipped character is copied with the
next stretch of unmatched text. And matched, a flag kept in step with the
loop, has become last_end, which the loop needed anyway. Built and run against
the cases above, this version prints Xaa, abc!, and XbXcX, agrees with
sed on s/x*/-/g (-a-b-c-) and s/a*$/E/g (bE), and passes the 125
existing tests, none of which had exercised any of the three.
Version 0.3.0 rewrote the engine to work in characters, for chapter 9’s reasons,
and the $ corruption went away with that rewrite, because the new loop pushes
the character at the match rather than the one at pos. The anchor and the
adjacent empty match are still there. Chapter 19 picks up the list.
10.5 Applying it to a range
let range = match spec.resolve(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
let mut last_modified_line = None;
for n in range.start..=range.end {
let line = match buf.line(n) {
Some(l) => l.to_string(),
None => continue,
};
let line_bytes = line.as_bytes();
let new_line = if global {
substitute_all(&re, line_bytes, &replacement)
} else {
substitute_first(&re, line_bytes, &replacement)
};
if let Some(new_bytes) = new_line {
let new_str = String::from_utf8_lossy(&new_bytes).into_owned();
buf.replace_line(n, new_str);
last_modified_line = Some(n);
}
}
spec.resolve with its default of the current line, which is ed’s: a bare s
changes one line, and ,s or 1,$s changes all of them. The command did not
have to know any of that. It is the return on chapter 4.
buf.line(n).to_string() copies the line before working on it, and the copy
is not waste. line borrows from buf, replace_line needs buf mutably,
and the two cannot overlap. Copying first ends the borrow. The alternative,
taking the line out of the buffer with something like std::mem::take, avoids
the copy and leaves the buffer holding an empty line for as long as the
substitution takes, which is fine until the code between the take and the put
learns to return early.
String::from_utf8_lossy is chapter 9’s data loss. The engine produced bytes,
the buffer holds strings, and this is the one place they meet. Most of the
time the bytes are valid UTF-8 and the conversion copies them. When a match
split a character, the conversion is where the damage becomes permanent,
because it replaces what it cannot decode rather than refusing. In 0.3.0 the
line is String::from_utf8(new_bytes).expect(...), with a comment explaining
why the result is valid by construction: the engine consumes whole characters,
so every boundary it reports is a character boundary. The conversion went from
repairing a broken invariant to asserting a kept one.
replace_line is the one addition to buffer.rs this slice needed:
/// Replace the content of 1-indexed line `n`. Marks the buffer
/// as modified. Panics if `n` is out of range.
pub fn replace_line(&mut self, n: usize, content: String) {
self.lines[n - 1] = content;
self.modified = true;
}
It can panic on a bad address, and its doc comment says so. That is a weaker
contract than chapter 3’s line, which returns None, and the reason it is
acceptable is that the only caller passes an n it has just read with
buf.line(n). The invariant is real and it is held by the call site, which is
the arrangement chapter 4’s unreachable! was criticized for. The difference
is one of distance: here the check and the reliance on it are four lines apart.
10.6 What it says afterwards
match last_modified_line {
Some(n) => {
buf.set_current(n);
match buf.line(n) {
Some(s) => Action::Print(s.to_string()),
None => Action::Error("invalid address".to_string()),
}
}
None => Action::Error("no match".to_string()),
}
The current line moves to the last line that changed, which is ed’s rule, and
that line is printed. ed prints nothing unless the command ends in p; ved
always shows the result, which is the program’s purpose stated in chapter 1
showing up as an Action::Print. Across a range, only the last changed line is
shown:
a
alpha
beta
gamma
.
1,3s/a/A/
gAmma
That is a compromise between printing every changed line, which on ,s over a
long file floods the terminal, and printing a count, which would be more
consistent with the deleted 3 lines confirmations chapter 14 introduces and
less useful for the common case of fixing one line.
no match is reported only when nothing in the range matched. A range in which
some lines matched is a success, and the lines that did not match are
unchanged without comment. That is ed’s behavior, and it is also what makes
,s/foo/bar/g usable at all: a substitution across a file is expected to miss
most lines.
10.7 Repeating the last substitution
Bare s arrived later, in version 0.1.5, and it is short:
let (pattern, replacement, global) = if args.is_empty() {
match buf.last_subst() {
Some((p, r, g)) => (p.clone(), r.clone(), *g),
None => return Action::Error("no previous substitute".to_string()),
}
} else {
// ... scan the fields as before ...
buf.set_last_subst(pattern.clone(), replacement.clone(), global);
(pattern, replacement, global)
};
The no delimiter error disappears, because an empty argument now means
“again”. The interesting decision is where the remembered substitution lives,
and the commit that added it states it: the state lives on Buffer alongside
filename and current-line — all single-session REPL state.
Chapter 5 argued for putting the filename on Buffer because “which file is
this” is a property of the text, and that argument does not extend to the last
substitution. The last thing the user replaced is a fact about the session. The
two places are equivalent until something replaces the buffer while the session
continues, and e does that, with *buf = Buffer::new():
e notes.txt
8
s/teh/the/
the one
w
wrote 8 bytes to notes.txt
e draft.txt
8
s
? no previous substitute
In ed, the remembered substitution survives e, and the second s fixes the
same typo in the second file, which is the use the feature exists for. ved
forgets, because the memory was stored in the object that e throws away.
It is a small bug with a general lesson about convenience. Buffer was the
place that was already threaded through dispatch, so adding a field to it
meant no new parameter anywhere, and the commit message counts that as an
advantage. The cost of storing state in the nearest available struct is that
it inherits that struct’s lifetime, whether or not the state should.
ed has a related feature ved does not: s//new/ with an empty pattern reuses
the last pattern, whether it came from s, g, or a search. In ved the
empty pattern is compiled like any other, matches the empty string at the start
of the line, and inserts the replacement there. It is in the backlog, and it
would need the remembered pattern to live somewhere g can reach as well.
10.8 What slice 5b bought
The program can change text, with a regex engine that is its own, through a command that ed users already know. At 1,711 lines, this checkpoint is the first one where ved does the job people use ed for.
It also has the program’s densest cluster of disagreements with ed, and they
share a cause. The scanner interpreted an escape it should have passed on. The
g loop discarded the positions it needed. The flag parser accepted characters
it did not understand. In each case a component answered a question that
belonged to somebody else, or declined to ask a question that was its own, and
the result was a plausible line of output. None of it was visible to tests that
checked the cases their author had in mind, which is chapter 15’s subject.
Exercise 10-1. Make the flag suffix strict: accept g, p, and a decimal
count, reject anything else with ? invalid command suffix, and implement the
count by replacing only the nth match. Then decide what s/a/b/2g should do,
and check GNU ed’s answer.
Exercise 10-2. Make the closing delimiter optional, as it is in ed. Find the one case where this is ambiguous, which involves the pattern field rather than the replacement, and decide what ved should do with it.
Exercise 10-3. Apply the scan_delimited fix from section 10.2 to
examples/ved, including the one-arm change to expand_replacement. Then
write the four tests that would have caught the original: one for each of .,
*, and & as the delimiter, and one for \n in a replacement.
Exercise 10-4. Apply the find_at fix from section 10.4. Write a test for
each of the three failures before you apply it and watch them fail. Then find
out whether g/^a/s/a/X/g was ever affected, and explain why or why not.
Exercise 10-5. Move the last substitution off Buffer and into run_repl,
so that e preserves it. Work out how dispatch gets access to it, and decide
whether that changes chapter 6’s claim that dispatch holds no state.
11. Commands That Move Lines
Slice six was two commands: d deletes lines and i inserts before one. It is
the checkpoint in examples/ch11-editing, and it is small. Four more commands
of the same kind arrived after the first release, as users asked for them: c
in 0.1.1, then j, m, and t together in 0.1.5. They live in
examples/ved, and this chapter takes all six together, because they share a
problem the substitute command did not have. They change which lines exist, not
what is in them, so every one of them has to decide where the current line goes
and what happens to the addresses of everything after it.
$ cargo run -q -p ved
a
one
two
three
four
five
.
2,3d
deleted 2 lines (2-3)
p
four
$m0
moved 1 lines (3-3) to after 0
1t$
copied 1 lines (1-1) to after 3
2,3j
joined 2 lines (2-3) into line 2
,n
1 five
2 onefour
3 five
Something in that session is wrong, twice, and it is not in the output of
,n. Section 11.6 is about it, and it is a plural.
11.1 Deleting
/// Delete lines from `start` to `end` (1-indexed, inclusive).
/// Updates current to the line after the deleted range, or the
/// new last line, or 0 if the buffer is now empty.
pub fn delete_range(&mut self, start: usize, end: usize) {
self.lines.drain((start - 1)..end);
self.modified = true;
if self.lines.is_empty() {
self.current = 0;
} else if start <= self.lines.len() {
self.current = start;
} else {
self.current = self.lines.len();
}
}
drain removes a range from a vector in one move, shifting what follows once
rather than once per line. The range is the conversion chapter 3 promised would
happen in one place: start - 1 to get a 0-indexed start, and end unchanged,
because an inclusive 1-indexed end and an exclusive 0-indexed end are the same
number. That is chapter 3’s cancelling off-by-one again, in a different
function, and the doc comment does not mention it. A reader who “fixes” it to
(start - 1)..(end - 1) gets a delete that leaves the last line of every range
behind.
The three branches that follow are ed’s rule for where you are after a delete.
If anything survives after the deleted range, the current line is the first of
those, which now has the number start. If the range ran to the end of the
buffer, the current line is the new last line. If nothing survives, it is the
sentinel 0. The checkpoint crate shows the first two on a four-line buffer:
2d
p
three
$d
p
three
The rule exists so that repeated d works the way someone deleting a paragraph
expects. Each d removes the line you are on and leaves you on the next one,
and at the end of the buffer it leaves you on the last line rather than on
nothing. It is the kind of rule nobody would design from first principles and
everybody relies on once they have used it.
At slice six this command printed nothing, which was ed’s behavior, and
returned a new Action variant:
enum Action {
Quit,
EnterInputMode,
Done,
Print(String),
Error(String),
}
Done is “the command succeeded and has nothing to say”. The loop handles it
by resetting quit_warned and printing nothing. It arrived here because d was
the first command that changed the buffer without any text to show for it, and
Print(String::new()) would have printed an empty line. Slice nine gave d a
confirmation, deleted 2 lines (2-3), so d no longer uses it. Chapter 12’s
g does.
11.2 Insert is append with a different number
"i" | "insert" => {
// Insert before the addressed line (default: current).
// Implemented as "append after address - 1", so the
// input-mode loop (which always does append_after) works
// unchanged. On an empty buffer or address 1, current
// becomes 0 (the before-first-line sentinel).
if !buf.is_empty() {
let addr = match spec.resolve(buf) {
Ok(r) => r.end,
Err(e) => return Action::Error(e),
};
buf.set_current(addr.saturating_sub(1));
}
return Action::EnterInputMode;
}
Input mode has one operation, buffer.append_after(buffer.current(), line),
and it was written in chapter 3 for a. Inserting before line n is appending
after line n − 1, so i sets the current line and enters the same mode. The
loop never learns that there are two commands, and when c arrives it will not
learn about a third.
This is the cheapest kind of reuse there is: noticing that a new operation is
an old one with a different argument. It works here because the sentinel was
designed in chapter 3 to mean “before the first line”, so 1i becomes
append_after(0, ...), which was already the right call. The doc comment
mentions the sentinel by name, which is what keeps the trick from looking like
an accident.
Slice six also changed a. Until then a ignored its address entirely and
always appended after the current line, so 1a appended wherever the current
line happened to be. The
commit message lists it as a fix made in passing, also fixed a to respect
address prefixes, and the fix is the subject of the next section.
11.3 One error kept, one thrown away
"a" | "append" => {
// Append after the addressed line (default: current).
// On an empty buffer, current is 0 and append_after(0)
// inserts at the start — correct.
if !buf.is_empty()
&& let Ok(r) = spec.resolve(buf)
{
buf.set_current(r.end);
}
return Action::EnterInputMode;
}
Put that beside the i arm and the difference is one pattern. i matches on
the result of resolve and returns the error. a uses if let Ok and ignores
it. When the address is bad, i reports it and a appends after the current
line as though no address had been typed:
1p
one
5a
carried on
.
,n
1 one
2 carried on
3 two
4 three
GNU ed answers 5a on a three-line buffer with ? Invalid address and stays in
command mode. ved appended after line 1, which is where the current line
happened to be, and said nothing.
The worse case is an address that is valid in ed and rejected by resolve:
1p
one
0a
heading
.
,n
1 one
2 heading
3 two
4 three
0a is how you put text at the top of a file in ed, and it is one of the first
idioms anyone learns, because 1i does the same thing and 0a is one
keystroke shorter to think about. In ved the text goes after the current line.
It is in the right file, it is not lost, and it is in the wrong place, with no
message saying so. This is still the behavior in 0.3.0, filed as ved
#20.
Two decisions combined to produce it, and each was reasonable alone.
resolve_with rejects 0, because for p, d, s, and nearly every other
command there is no line 0 to act on. And if let Ok in a condition reads like
a guard rather than like discarding an error, especially after it was
reformatted into the if ... && let chain that the 2024 edition allows. The
code went through that refactor and nobody looked at what the else did,
because there was no else to look at.
The 0 address is the real subject. p and d act on lines, and a line number
must name a line. a and i put text between lines, and an address for them
names a gap, of which there is one more than there are lines. The program
already knew this. Chapter 4’s parse_dest, written for m and t, says the
destination may be 0 (“before line 1”), because those commands write after
their destination too. The concept existed in one function and was missing from
the two commands that needed it most.
The fix gives Spec a method for addressing a gap:
/// Resolve to the single line that input goes after, for `a`
/// and `i`. A range uses its second address, as ed does, and 0
/// is allowed: `0a` puts text before the first line.
pub fn resolve_target(&self, buf: &Buffer) -> Result<usize, String> {
let (first, last) = match (&self.start, &self.end) {
(None, None) => return Ok(buf.current()),
(Some(s), None) => (s, s),
(Some(s), Some(e)) => (s, e),
(None, Some(_)) => unreachable!("parser never produces (None, Some)"),
};
let (first, last) = (resolve_one(first, buf)?, resolve_one(last, buf)?);
if first > buf.len() || last > buf.len() {
return Err("invalid address".to_string());
}
Ok(last)
}
Both addresses of a range are checked, though only the second is used, and
neither has to come before the other. That is GNU ed’s rule, and it is narrower
than it looks: 9,3a on a six-line buffer is an error, and 3,1a appends
after line 1.
and both arms become the same shape:
"a" | "append" => {
match spec.resolve_target(buf) {
Ok(n) => buf.set_current(n),
Err(e) => return Action::Error(e),
}
return Action::EnterInputMode;
}
"i" | "insert" => {
match spec.resolve_target(buf) {
Ok(n) => buf.set_current(n.saturating_sub(1)),
Err(e) => return Action::Error(e),
}
return Action::EnterInputMode;
}
The if !buf.is_empty() guards are gone from both. They existed because
resolve fails on an empty buffer, and resolve_target does not need to: on an
empty buffer the current line is 0, 0a resolves to 0, and 1a is larger than
the buffer and is an error, which is what ed says too. This is chapter 5’s
pattern of the empty case that has to be spelled out, and here it stops needing
to be spelled out, because the function now describes gaps and an empty buffer
has one.
Run against GNU ed on 0a, 5a, 0i, 2i, $a, 1,2a, bare a, and 0a,
1a, a, and i on an empty buffer, this version produces the same buffer
in every case and fails in the same cases, and the 125 existing tests pass.
None of them called a with an address.
11.4 Change
"c" | "change" => {
let range = match spec.resolve(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
let start = range.start;
buf.delete_range(range.start, range.end);
buf.set_current(start.saturating_sub(1));
return Action::EnterInputMode;
}
c is d followed by i at the same address, and the code is that sentence.
The commit that added it in 0.1.1 says equivalent to d followed by i in one
command, and it was cheap enough to add in an afternoon because both halves
already existed.
The ordering has a consequence that ed shares. The lines are deleted before the
replacement is typed, so a c followed immediately by . is a delete:
2c
.
,n
1 one
2 three
The alternative, holding the deleted lines until input mode ends and putting
them back if nothing was typed, would need input mode to know which command
started it, and the design in chapter 3 deliberately does not. ed made the same
choice, and the user who wanted the lines back has u in ed and nothing in
ved. Section 11.7 is about that.
11.5 Join, and a silent no-op that prints
fn run_join(spec: &Spec, buf: &mut Buffer) -> Action {
let range = match spec.resolve_or_pair_with_next(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
if range.start == range.end {
buf.set_current(range.start);
return Action::Print(String::new());
}
let mut joined = String::new();
for n in range.start..=range.end {
if let Some(line) = buf.line(n) {
joined.push_str(line);
}
}
buf.replace_line(range.start, joined);
buf.delete_range(range.start + 1, range.end);
buf.set_current(range.start);
// ... the confirmation
}
resolve_or_pair_with_next is the third default from chapter 4, and j is the
command it was written for: bare j joins the current line with the next. The
join is a plain concatenation with no separator, which surprises people who
expect a space and is what ed does.
The single-line case is where the code and its documentation part company. The doc comment says a single-line range is a silent no-op, and a test holds it in place:
#[test]
fn join_single_line_is_silent_noop() {
let mut buf = buf_with(&["one", "two", "three"]);
let act = dispatch("2j", &mut buf);
if let Action::Print(s) = act {
assert!(s.is_empty());
} else {
panic!("expected silent Print on single-line join");
}
// ...
}
The test passes, and the command is not silent. Action::Print goes to a
writeln!, and writeln! of an empty string writes a newline:
2,2j
p
two
ed prints nothing. The fix is return Action::Done, which is the variant
section 11.1 introduced for this purpose, and which was already in the enum
when j was written.
The bug is small and the way it survived is not. The test checks the value
dispatch returns, which is the decision from chapter 2 that makes the whole
command language testable without a terminal. It cannot check what the loop
does with that value, and here the meaning lives in the loop: “silent” is a
property of the terminal, and the test is asserting on something one step
before the terminal. The test’s name describes the requirement and its body
describes the implementation, and they agree with each other and not with the
user. Chapter 15 comes back to the gap between the two.
11.6 Move and transfer
fn run_move(spec: &Spec, buf: &mut Buffer, dest_arg: &str) -> Action {
let range = match spec.resolve(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
let dest = match address::parse_dest(dest_arg, buf) {
Ok((d, _)) => d,
Err(e) => return Action::Error(e),
};
if dest >= range.start && dest <= range.end {
return Action::Error("invalid destination".to_string());
}
let lines: Vec<String> = (range.start..=range.end)
.filter_map(|n| buf.line(n).map(str::to_string))
.collect();
let count = lines.len();
buf.delete_range(range.start, range.end);
// Deletion shifts everything past `range.end` down by `count`.
let adjusted = if dest > range.end { dest - count } else { dest };
for (at, line) in (adjusted..).zip(lines) {
buf.append_after(at, line);
}
buf.set_current(adjusted + count);
Action::Print(format!(
"moved {count} lines ({}-{}) to after {dest}",
range.start, range.end
))
}
2,4m6 moves lines 2 through 4 to after line 6. The destination is parsed by
parse_dest, which allows 0, so m0 moves to the top.
The comment in the middle is the most useful line in the function. Once the
range is deleted, every address after it has moved down by count, and the
destination the user typed refers to the buffer as it was. A destination before
the range is unaffected and one after it needs adjusting. That is the classic
bug in any operation that removes and reinserts within one sequence, and the
comment states the reason for the subtraction rather than restating the
subtraction, which is the kind of comment that stops someone from removing it.
A destination inside the range is an error, matching ed, since moving lines 2
through 4 to after line 3 has no meaning. t, the copy, allows it: 1,3t2 puts
a copy of all three lines after line 2, and the original lines stay where they
were. t is the same function without the delete and without the adjustment,
because nothing moved.
The implementation is built from the buffer’s existing operations: collect the
lines, delete the range, append them one at a time. Each append_after is a
Vec::insert, so moving k lines costs k shifts of everything after the
destination, where a single splice would cost one. For the files ed is used on
it does not matter, and chapter 3’s measurement applies. What matters more is
that m and t did not need new methods on Buffer, which is the subject of
the next section.
Two smaller problems are visible in the confirmation. The first is the plural:
1m2
moved 1 lines (1-1) to after 2
run_delete, written at the same time, checks count == 1 and says deleted line 2. run_move and run_transfer do not, so moving one line reads like a
program that has not been finished. It is a one-line fix in each, and it is the
sort of inconsistency that accumulates when each command formats its own
message. Chapter 14 is about the messages.
The second is the _ in Ok((d, _)). parse_dest returns the destination and
the rest of the input after it, and run_move discards the rest:
2m3xyz
moved 1 lines (2-2) to after 3
GNU ed says ? Invalid command suffix. It is chapter 10’s flag parser again: a
parser that returns “what I found and where I stopped” is only strict if the
caller checks where it stopped. Throwing the remainder away with _ is the
quiet version of if let Ok, and it accepts anything a user types after the
address.
11.7 Three primitives, and no undo
Six commands in this chapter, and buffer.rs gained one method for them:
delete_range. Everything else is built from what was already there.
| Command | Built from |
|---|---|
a, i | set_current, then input mode’s append_after |
d | delete_range |
c | delete_range, set_current, then input mode |
j | replace_line, delete_range |
m | delete_range, append_after |
t | append_after |
Every change to the buffer’s lines in the finished program, including s, g,
and r, goes through append_after, delete_range, or replace_line, and
e starts a new buffer and fills it with append_after. That is a narrow
interface, and it is the reason chapter 3’s invariant about current was still
holding at 2,800 lines: three methods maintain it, and nothing else can reach
the fields.
It is also the precondition for the feature ved most conspicuously lacks:
u
? unknown command: u
ed’s u undoes the last command that changed the buffer, and it is the command
that makes c followed by . survivable. ved has never had it. A program with
three mutation primitives is in a good position to add it, because there are
three places to record what changed: a deleted range and its lines, an inserted
line and its position, a replaced line and its old content. A command would
open a group, its primitives would append to it, and u would replay the group
backwards. The cruder version, which copies the whole Vec<String> before
every command that changes it, is a dozen lines and costs a buffer’s worth of
memory per command.
Either one is less work in this program than in one where commands edit lines
directly, and that is the useful general point. Undo is hard to add to a
program after the fact in proportion to the number of places that mutate its
state, and the number here is three. Chapter 19 says why it has not been done.
11.8 What slice six bought
At the checkpoint, d and i, a working a address, and an Action variant
for commands with nothing to say. In the finished program, six commands built
from three buffer methods, and the set of edits an ed user expects to make.
The bugs this chapter found are all in the gap between a value and what is
done with it. if let Ok discarded an error, Ok((d, _)) discarded the input
after an address, and a test checked a returned value that the loop then turned
into output nobody wanted. In each case the code that produced the value was
right. The mistake was in what the next line did with it.
Exercise 11-1. Apply the resolve_target fix from section 11.3 to
examples/ved. Before you do, write a test for 0a that fails. Then decide
whether c should use it too: what should 0c do, and what does GNU ed say?
Exercise 11-2. Fix the single-line j to return Action::Done, and then
fix the test, which will now fail. Rename the test if the name no longer
describes what it checks.
Exercise 11-3. Make m and t reject trailing input after the
destination. Then grep the program for every other place a parser’s remainder
is bound to _ or never read, and decide for each one whether ed would accept
what ved accepts.
Exercise 11-4. Replace the insertion loop in run_move with one
Vec::splice. That needs a new method on Buffer, since lines is private.
Decide whether the method is worth adding for m and t alone, and measure
the difference on a 100,000-line buffer before you decide.
Exercise 11-5. Implement u, single level, by snapshotting the buffer’s
lines and current line before any command that changes them. Then work out
which commands need the snapshot, where in dispatch it should be taken so
that a failed command does not overwrite it, and what u followed by u
should do.
12. The Global Command
g/re/p is three of ed’s ideas in five characters: select every line that
matches a regular expression, and print it. It was useful enough that in 1973
it became a program of its own, named after the command, and most people who
type grep today have never typed g.
Slice seven adds g and its inverse, v, which selects the lines that do
not match. The checkpoint is examples/ch12-global, and its run_global is
the same function, line for line, as the one in the shipped program.
$ cargo run -q -p ved
a
fn main() {
// TODO: parse args
let x = 1;
// TODO: handle errors
}
.
g/TODO/n
2 // TODO: parse args
4 // TODO: handle errors
v/TODO/p
fn main() {
let x = 1;
}
g/TODO/s/TODO/DONE/
// DONE: parse args
// DONE: handle errors
g/^ *\/\//d
,p
fn main() {
let x = 1;
}
The interesting part of g is not the matching, which is chapter 7 through 9’s
engine called once per line. It is that the command after the pattern can
change the buffer that g is iterating over, and this chapter is about what
that does to a loop.
12.1 Two passes
/// Global command: scan the addressed range for lines matching
/// (or not matching, if `invert` is true) a pattern, then execute
/// a command on each one. Default address: whole buffer (1,$).
///
/// `g/pattern/p` is literally "global regex print" — the ancestor
/// of the grep command.
///
/// Delete is special-cased (reverse iteration to keep line numbers
/// stable). All other commands dispatch through the normal path.
fn run_global(spec: &Spec, buf: &mut Buffer, args: &str, invert: bool) -> Action {
The first half parses the same way s does: a delimiter, scan_delimited for
the pattern, and whatever remains is the command to run, defaulting to p when
it is empty. The range defaults to the whole buffer through
resolve_or_whole, the second of chapter 4’s defaults, since g with no
address means every line.
The second half is ed’s specification, which describes g as two passes. The
first pass marks every line in the range that matches. The second pass visits
each marked line, makes it current, and runs the command. Doing it in two
passes is not an optimization. It is what keeps the command’s effects from
feeding back into the selection: g/a/s/a/b/ must not, after changing a line,
reconsider whether that line still matches, and g/x/t. must not run again on
the copies it is making.
let mut marked = Vec::new();
for n in range.start..=range.end {
if let Some(line) = buf.line(n) {
let matched = re.find(line.as_bytes()).is_some();
if matched != invert {
marked.push(n);
}
}
}
matched != invert is all of v. When invert is false the line is marked if
it matched; when it is true, if it did not. != on two booleans is exclusive
or, and it is the shortest correct way to write “flip this condition when that
flag is set”. It is why the dispatcher has g and v calling one function
with a flag, which chapter 6 pointed to as a signature that says what the
difference between two commands is.
12.2 A mark is a number
marked is a Vec<usize>, a list of line numbers. That is the decision this
chapter is about, and the second pass shows what it assumes:
// Delete is special: remove marked lines bottom-to-top so
// earlier line numbers stay valid.
if cmd == "d" {
for &n in marked.iter().rev() {
buf.delete_range(n, n);
}
return Action::Done;
}
// For all other commands: set current to the marked line and
// dispatch normally. Works for p, n, s (which don't change
// line count) and anything else that operates on current line.
let mut output = String::new();
for &n in &marked {
buf.set_current(n);
match dispatch(cmd, buf) {
// ... collect output ...
}
}
A line number is a position, and a position is only meaningful until something
is inserted or removed in front of it. The comment states the condition under
which the loop is correct: commands that do not change the line count. p,
n, l, and s qualify, and those are most of what anyone uses g for.
d does not qualify, and the special case handles it with the standard trick:
delete from the bottom up, so that every deletion happens after all the
positions still waiting to be visited, and none of them shift. It is correct,
and it is also an admission. The loop’s representation is wrong for one of the
four commands the slice was written to support, and the fix was to route that
command around the loop.
The special case matches the string "d". It does not match .,+1d, or -1d,
or d with anything after it, and those go through the general loop with
stale numbers. Neither does it cover m, t, j, c, or r, which also
change the line count and arrived after g did.
12.3 What stale numbers do
Take a five-line buffer where the odd lines start with a:
a
a1
b2
a3
b4
a5
.
g/a/j should join each a line with the line after it. The marks are 1, 3,
and 5. The first join turns lines 1 and 2 into one line, and now a3 is line 2
and b4 is line 3. The loop visits its next mark, 3, and joins b4 with a5:
g/a/j
joined 2 lines (1-2) into line 1
joined 2 lines (3-4) into line 3
? invalid address
,n
1 a1b2
2 a3
3 b4a5
GNU ed produces a1b2, a3b4, a5, and reports the error on the last line,
where j has nothing to join.
The case that loses data is a command with a relative address:
g/a/-1d
? invalid address
deleted line 2
deleted line 4
,n
1 a1
2 a3
3 b4
The intent is to delete the line before each a line. The first mark is line
1, -1 is line 0, and that is an error. The loop carries on. The second mark
is line 3, -1 is line 2, and b2 is deleted, which is right. The third mark
is line 5, in a buffer that now has four lines. set_current(5) does not check
its argument, -1 resolves to 4, and line 4 is a5: a line that matched the
pattern, that the user was not deleting, and that is now gone, with a
confirmation reporting the deletion of a line number rather than of a line.
Filed as ved #19.
GNU ed, given the same command, stops at the first error and changes nothing.
Some commands happen to work. g/^/m0, the ed idiom for reversing a file, is
correct, because each move takes a line from below the remaining marks to the
top, and only the lines already visited shift. g/a/t$ is correct, because the
copies land after every mark. Both are the same kind of correct as p and s:
the line count changes, but never in front of a position still to be visited.
That is a fact about the arithmetic of particular commands, not about the loop,
and nothing in the code says which commands have it.
All of this has been in the program since slice seven, and it is in 0.3.0. At
0.2.1 the test suite had no tests for g at all. 0.3.0 added seven, and the
only one with a command that changes the line count is g/foo/d, which takes
the special case.
12.4 Marking lines instead of numbers
ed itself does not have this problem, because ed does not mark numbers. It
marks lines. In the Seventh Edition’s ed.c, the buffer is a table with one
entry per line, the mark is the low bit of the entry, and when a command moves
entries around, the bit moves with them. The second pass scans the table for a
set bit, clears it, makes that line current, runs the command, and starts the
scan again from the top. It does not matter what the command did to the buffer
in between, because the next marked line is found by looking rather than
remembered by position.
ved can do the same thing without a linked list, and the reason it can is
chapter 11’s table. Every change to lines goes through three methods. If
Buffer keeps a second vector of flags, one per line, then two of those
methods have one line each to add and the flags follow the lines wherever they
go:
pub struct Buffer {
lines: Vec<String>,
marks: Vec<bool>,
// ...
}
pub fn append_after(&mut self, after: usize, line: String) {
self.lines.insert(after, line);
self.marks.insert(after, false);
// ...
}
pub fn delete_range(&mut self, start: usize, end: usize) {
self.lines.drain((start - 1)..end);
self.marks.drain((start - 1)..end);
// ...
}
replace_line changes no positions, so it needs nothing. The invariant, that
marks and lines have the same length and the mark at index i belongs to
the line at index i, is held in buffer.rs beside chapter 3’s invariant about
current, for the same reason. Then:
/// Unmark and return the first marked line, wherever earlier
/// commands have moved it.
pub fn take_mark(&mut self) -> Option<usize> {
let i = self.marks.iter().position(|&m| m)?;
self.marks[i] = false;
Some(i + 1)
}
and the second pass becomes one loop with no special case:
let mut output = String::new();
while let Some(n) = buf.take_mark() {
buf.set_current(n);
match dispatch(cmd, buf) {
Action::Print(msg) => {
// ... append to output ...
}
Action::Error(msg) => {
buf.clear_marks();
// ... append "? msg" to output ...
}
_ => {}
}
}
The bottom-up delete is gone, because a deleted marked line takes its mark with
it and the next take_mark finds whatever is marked now. clear_marks on the
first error is ed’s rule, which stops the command rather than continuing with a
buffer the user did not expect.
Built against examples/ved and run beside GNU ed on sixteen global commands,
among them every failure above and g/b/.,+1j, g/b/1,.d, v/b/m0, g/a/m$,
and g/./t., this version produced the same buffer as ed in all sixteen. The
125 existing tests pass unchanged.
take_mark scans from the start each time, so a g over n lines with m
marks is O(n × m) in the worst case. The Seventh Edition loop has the same
shape, and for a buffer of a hundred thousand lines it is still faster than
printing the result. A program that needed better would keep the scan position
and restart from it, which is correct only if commands never move a marked line
upward, and m0 does.
One difference from ed remains. m and t are built from delete_range and
append_after, so a moved line is a new line and arrives unmarked. In ed a
moved line keeps its mark. It matters only for a command like g/a/.,+2m0,
where the range being moved contains marks not yet visited, and the fix is the
splice method that exercise 11-4 asked about, made to carry the marks across.
12.5 dispatch calls dispatch
The second pass runs its command with dispatch(cmd, buf), the same function
the loop calls for every command the user types. run_global is called from
dispatch, so this is recursion, and it works without any preparation because
of a property chapter 2 established for other reasons: dispatch holds no
state. It is a function from a string and a buffer to an Action, and calling
it from inside itself is no different from calling it twice in a row.
That is the cheapest feature in this chapter. Every command in the program
became something g can run, including commands added years later, without
g knowing they exist. g/x/l worked the day l was added.
It also means g can run itself, which ed forbids:
g/a/g/1/d
? no match
? no match
The inner g runs once per outer mark, on the whole buffer, because its range
defaults to 1,$ rather than to the current line. Two of its three runs find no
line containing 1 and report it, and the first run deletes a1. GNU ed
refuses with ? Cannot nest global commands, and in a recursive design the
refusal is three lines at the top of the second pass:
if cmd.starts_with(['g', 'v']) {
return Action::Error("cannot nest global commands".to_string());
}
Recursion through a shared dispatcher gives every command to every other command, and some of those combinations are meaningless. The property is worth having, and it comes with the job of listing the combinations that should not be allowed, because the type system will not.
12.6 What g cannot run
Two kinds of command are swallowed by the _ => {} arm, and in both cases the
user is not told.
q inside g does nothing. ed treats it as a quit, subject to the usual
warning. Nobody types g/x/q on purpose, so the difference is small, but the
silence is the same silence as chapter 11’s if let Ok: an Action that the
loop would have acted on, discarded by a match arm that exists to make the
match exhaustive.
a, i, and c return EnterInputMode, and the arm drops that too:
g/x/a
new
? unknown command: new
The append does nothing, and the text meant for it is read as the next command.
This one is a limit of the design rather than a dropped value. Input mode
belongs to the loop, and g is inside dispatch, which cannot read from the
terminal. ed solves it with command lists: a g command can span several
lines, each ending in a backslash, so g/x/a\ followed by the text puts the
text after every matching line. ved reads one line per command and has no
continuation syntax, so g can only run commands that fit on one line and need
no input.
Implementing command lists would mean giving dispatch a way to ask for more
input, which is the first thing in the program that would break chapter 6’s
rule that the loop owns the terminal. The design that keeps the rule is to
collect the continuation lines in the loop, before dispatch, and pass the
command list in as one string. It is the right design and it is not small.
12.7 Output, collected
Action::Print(msg) => {
if !output.is_empty() {
output.push('\n');
}
output.push_str(&msg);
}
Action::Error(msg) => {
if !output.is_empty() {
output.push('\n');
}
output.push_str(&format!("? {msg}"));
}
Every line of output from the inner commands is gathered into one string and
returned as a single Print, because run_global is in dispatch and does not
get to write. That is chapter 3’s choice for ,p again, with the same cost: a
g/./p over a large file holds the whole output in memory before any of it is
shown.
The Error arm is the interesting one. It formats ? {msg} itself, which is
the only place outside run_repl that knows what an error looks like. Chapter 2
moved the ? prefix into the loop so that one place would decide the format,
and this arm is a second place, written because Action has no way to carry a
mixture of output and errors. If the format of errors ever changes, this is
the line that will not change with them.
A g that matches nothing is ? no match. ed says nothing, on the reasoning
that “for every matching line” over zero lines is a command that did nothing
wrong. ved’s version is consistent with s, which does report it, and it means
a script running g/TODO/d over a clean file sees a ? that ed would not have
printed. Which of those is right is the question of chapter 14.
12.8 What slice seven bought
The ancestor of grep, built on top of everything already there: the scanner
from s, the address default from chapter 4, the engine from chapters 7
through 9, and the dispatcher from chapter 2, called recursively. run_global
is eighty-four lines, and nearly all of them are about running other commands
rather than about matching.
The representation chosen for the marks was the first one that came to mind,
it was right for the commands the slice was tested with, and the special case
for d was the sign that it was wrong. That pattern is common enough to be
worth a rule. When a loop needs a special case for one of the operations it was
written to perform, the representation is the thing to question before the loop
is.
Exercise 12-1. Apply the marks change from section 12.4 to examples/ved.
Before you do, write tests for g/a/j and g/a/-1d on the buffer from section
12.3 and watch them fail.
Exercise 12-2. set_current(5) on a four-line buffer succeeded silently,
and that is half of why g/a/-1d deleted the wrong line. Make set_current
refuse an out-of-range line, decide what “refuse” means for a method that
returns nothing, and find every caller that breaks.
Exercise 12-3. Make g/a/.,+2m0 keep the marks of the lines it moves, as
ed does. You will need a Buffer method that moves a range in one operation.
Exercise 12-4. Implement ed’s command lists for g: a command ending in a
backslash continues on the next line. Keep the rule that dispatch never reads
from the terminal.
Exercise 12-5. grep began as g/re/p run non-interactively over a file.
Write it with ved’s modules: a binary that takes a pattern and a filename,
loads the file into a Buffer, runs g/pattern/p, and exits 1 if nothing
matched. Count how many lines of new code it took.
13. Files, and the Outside World
Until slice eleven, every line in the buffer was typed by the person at the keyboard. From here the program reads files it did not write, made by other programs, on other operating systems, in encodings it may not understand, and the assumption that the program knows what a line is stops being safe.
$ cargo run -q -p ved -- notes.txt
22
,n
1 shopping
2 .
3 eggs
4 bread
a
milk
.
e other.txt
22
,p
contents of other.txt
The milk is gone, and nothing said it would be. GNU ed would have refused the
e until it was typed twice. Section 13.5 is about that.
Slice eleven arrived in one commit with slices eight, nine, and ten, so the
checkpoint examples/ch13-files holds four slices: long-form aliases, the
rewritten error messages, the H help command, and file loading. Chapter 14
takes the first three. This chapter takes the last, plus what was added to it
after release: treating a missing file as a new one in 0.1.2, and the encoding
warnings in 0.2.0.
13.1 A filename on the command line
Chapter 2’s argument parser rejected anything it did not recognize, and said that this would be the first thing to loosen. Slice eleven loosens it:
s if s.starts_with('-') => {
return Err(format!("unknown option: {s}"));
}
_ => {
filename = Some(arg.clone());
}
Unknown flags still fail, and a bare word is a filename. Two bare words are two
filenames, and the second silently replaces the first, so ved notes.txt small.txt opens small.txt. GNU ed opens the first and silently ignores the
rest. Neither says anything, and they disagree about which file you get.
parse_args now returns a pair, (prompt, filename), and run_repl
takes the filename and loads it before the loop starts, which is the twenty
lines chapter 6 counted as the loop’s growth.
The guard has one gap that chapter 2’s exercises pointed at:
$ ved -- -p
ved: unknown option: --
-- is the universal way to say “everything after this is an operand, even if
it starts with a dash”, and it is how a user edits a file named -p. ved
treats -- as an unknown flag. The fix is one arm that sets a flag to stop
looking for options, and it is the sort of thing an argument-parsing crate gets
right without being asked, which is part of the price of chapter 1’s
constraint.
13.2 What a buffer can hold
fn load_file(filename: &str, buf: &mut Buffer) -> Result<LoadOutcome, String> {
let detected = enc::warn_if_non_utf8(filename);
let content = match std::fs::read_to_string(filename) {
Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
buf.set_filename(filename.to_string());
buf.mark_saved();
return Ok(LoadOutcome::NewFile);
}
Err(e) => return Err(format!("cannot open {filename}: {e}")),
};
let bytes = content.len();
for line in content.lines() {
buf.append_after(buf.len(), line.to_string());
}
buf.set_filename(filename.to_string());
buf.mark_saved();
if let Some(enc) = detected {
buf.mark_non_utf8_source(enc, filename.to_string());
}
Ok(LoadOutcome::Loaded(bytes))
}
Chapter 4 said this chapter would examine the difference between the command
language and the buffer, and read_to_string is where the program answers it.
The command language is ASCII, so the address parser and the dispatcher can
work in bytes. The buffer is Vec<String>, and a String is valid UTF-8 by
construction, so a file can only enter the buffer if it is valid UTF-8.
read_to_string checks, and refuses anything else:
$ ved latin1.txt
? cannot open latin1.txt: stream did not contain valid UTF-8
That file is caf followed by the byte E9, which is é in Latin-1 and is
not valid UTF-8 on its own. GNU ed opens it, shows it, and writes it back
unchanged, because ed’s buffer is bytes and it has no opinion about what they
encode. ved cannot open it at all.
This is a real limitation and it is a defensible one. The alternative types
for the buffer are Vec<Vec<u8>>, which makes every command that prints or
matches a line responsible for deciding what to do with bytes that are not
text, or Vec<OsString>, which has the same problem with less convenient
methods. Either is more correct, and either would have spread a question that
the program currently answers once, at the door. And refusing is the right
failure. Chapter 9 showed what happens when bytes that are not a whole
character get into a String through from_utf8_lossy: the text is changed
and nothing says so. A program that refuses to open a file has lost nothing.
The error message is less good than the decision. stream did not contain valid UTF-8 is the standard library’s wording, and it does not say what the user can
do. Section 13.7 is about the module that was written to improve it.
13.3 What a line is
content.lines() splits the text into lines, and every line goes into the
buffer through append_after, the primitive from chapter 3. Loading a file is
typing it very fast.
Chapter 3 noted that a line consisting of one . cannot be typed into the
buffer, because it ends input mode, and promised that files containing one
would load without trouble. They do, because loading never enters input mode:
$ printf 'a\n.\nb\n' > dot.txt
$ ved dot.txt
6
,n
1 a
2 .
3 b
lines() does two things beyond splitting on \n, and both are
conveniences. It does not produce an empty last line when the text ends in a
newline, which is right, since a\nb\n is two lines and not three. And it
strips a \r before each \n, so that a file with Windows line endings comes
out with no carriage returns at the ends of its lines.
The second one is a silent conversion:
$ printf 'one\r\ntwo\r\n' > crlf.txt
$ ved crlf.txt
10
w
wrote 8 bytes to crlf.txt
q
Ten bytes in, eight bytes out. Every line ending in the file was changed from
CRLF to LF, and the user’s only edit was to save. run_write joins lines with
\n, as it should, and the information that they were ever joined with
anything else was discarded by lines() before the first command ran. GNU ed
writes back ten bytes, because to ed the \r is the last character of the
line. Filed as ved #18.
ved ships through WinGet, so this is not a hypothetical. A user on Windows opening a file their editor saved with CRLF endings, fixing one typo with ved, and committing it, produces a diff that changes every line.
There are two fixes, and they differ in what the user sees. The ed fix is to
split on \n alone and keep the \r:
for line in content.split_terminator('\n') {
buf.append_after(buf.len(), line.to_string());
}
split_terminator behaves like lines() about the final newline and leaves
everything else alone, so the file round-trips byte for byte. In a scratch copy
of examples/ved with this change in both load_file and run_read, the CRLF
file writes back as ten bytes and the 125 tests pass. The cost is the one ed
users already pay: the \r is part of the line, so s/e$/E/ on one\r is
? no match, because the last character is not e, and l shows the \r
as \r.
The other fix is to detect the line-ending style at load, strip the \r as
lines() does now, remember the style on Buffer beside the filename, and use
it in run_write. That keeps $ working and the file intact, and it needs a
decision about a file whose endings are mixed. ed’s version is two words; the
other is a feature. Either is better than converting without saying so.
A file that does not end in a newline gets one, in both programs:
$ printf 'abc' > nonl.txt
$ ved nonl.txt
3
w
wrote 4 bytes to nonl.txt
GNU ed does the same and prints Newline appended when it loads the file.
ved changes the file without the warning, which, for a program whose purpose is
to say what it did, is the wrong one to be quieter about.
13.4 A missing file is a new file
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
buf.set_filename(filename.to_string());
buf.mark_saved();
return Ok(LoadOutcome::NewFile);
}
ved notes.txt on a file that does not exist yet starts an empty buffer that
remembers the name, so that w will create it:
$ ved brandnew.txt
brandnew.txt: new file
That arrived in 0.1.2. Before it, a missing file was ? cannot open, which is
correct and useless, since creating a file is the most common reason to name
one that is not there. ed behaves the same way, and the guard is narrow: only
NotFound is treated as new. A directory, a permission failure, or anything
else is still an error with the operating system’s own words in it.
LoadOutcome is the enum that carries the distinction back to the caller. It
is two variants, and it replaces the alternative of returning a byte count of
zero and hoping the caller can tell an empty file from a missing one.
13.5 Replacing the buffer
/// Edit: replace the buffer with the contents of a file.
/// Warns if the buffer has unsaved changes (like q does).
fn run_edit(buf: &mut Buffer, args: &str) -> Action {
let filename_arg = args.trim_start();
let filename = if filename_arg.is_empty() {
// ... the remembered filename, or an error ...
};
// Replace the buffer entirely.
*buf = Buffer::new();
match load_file(&filename, buf) {
Ok(LoadOutcome::Loaded(bytes)) => Action::Print(format!("{bytes}")),
Ok(LoadOutcome::NewFile) => Action::Print(format!("{filename}: new file")),
Err(e) => Action::Error(e),
}
}
The doc comment says e warns about unsaved changes, as q does. It does not.
There is no check of is_modified anywhere in the function, and the first
thing it does is throw the buffer away:
a
an afternoon of work
.
e other.txt
22
,p
contents of other.txt
GNU ed answers the e with ? Warning: buffer modified and does nothing until
it is typed a second time, which is the same double-command dance as q. ved
discards the work without a word. Filed, with the failed load below, as
ved #17.
The ordering makes the second case worse. *buf = Buffer::new() happens before
load_file, so if the load fails, the buffer is already gone and there is
nothing to replace it with:
a
an afternoon of work
.
e latin1.txt
? cannot open latin1.txt: stream did not contain valid UTF-8
,p
? invalid address
The command failed, said so, and lost the buffer anyway. Of everything this book has found in ved, this is the case most likely to cost somebody real work, because it needs nothing unusual: a typo in a filename that happens to name a binary file, or a file in the wrong encoding, after an hour of unsaved editing. It is in 0.3.0.
Both problems have short fixes. Load into a new buffer and replace the old one only if the load succeeded:
if buf.is_modified() && !force {
return Action::Error("buffer modified; use E to discard changes".to_string());
}
let mut fresh = Buffer::new();
let outcome = match load_file(&filename, &mut fresh) {
Ok(o) => o,
Err(e) => return Action::Error(e),
};
*buf = fresh;
The force parameter is ed’s E, which is e without the check, dispatched
as 'E' => run_edit(buf, args, true). ed itself accepts either a second e or
an E. Implementing the second e would need the loop’s quit_warned state,
which dispatch cannot see, so this version takes only the E route and keeps
dispatch stateless; the message says which command to use. Built into a
scratch copy, e on a modified buffer refuses, E on a file that fails to load
leaves the buffer as it was, E on a good file loads it, and the 125 tests
pass.
The general lesson is about the order of destructive operations. Construct the
replacement first, then swap it in. A function that clears state and then does
something fallible has made its failure path destroy the thing it was asked to
replace, and the match that reports the error afterwards gives the impression
of handling it.
13.6 Reading into the buffer
r inserts a file’s contents after an addressed line, defaulting to the end of
the buffer. Its address handling has a shape that chapter 11’s resolve_target
would simplify:
let after = if buf.is_empty() {
0
} else if spec.is_empty() {
buf.len()
} else {
match spec.resolve(buf) {
Ok(r) => r.end,
Err(e) => return Action::Error(e),
}
};
The empty case, the default, and the general case, written out separately,
because resolve fails on an empty buffer and rejects 0. 0r header.txt is an
ed idiom for putting a file at the top, and in ved it is ? invalid address.
That is at least an error, which is better than what 0a did.
r is the one command that loads a file without being able to lose anything,
since it only adds lines, and its failure is clean:
r nope.txt
? cannot open nope.txt: No such file or directory (os error 2)
It prints the byte count it read, as ed does, and if the buffer had no filename it takes the name of the file it read. Both are ed’s behavior, and the second one is the kind of rule nobody would guess, which is a reason to copy it from a specification rather than decide it.
13.7 Encodings, sniffed
/// Sniff the first 4 KiB of `path` for a non-UTF-8 signature. On detection,
/// emit a two-line warning to stderr with a copy-pasteable iconv command and
/// return the encoding display name (e.g. "UTF-7"). Sniff failures (missing
/// file, IO error) and clean UTF-8 files return None silently.
pub fn warn_if_non_utf8(path: &str) -> Option<String> {
enc.rs arrived in 0.2.0 to improve the error from section 13.2 for the two
non-UTF-8 encodings its author kept meeting. A file that starts with the byte
order mark of UTF-16 gets a warning that names the encoding and a command that
converts it:
$ ved u16.txt
warning: u16.txt appears to be UTF-16 little-endian encoded.
hint: iconv -f UTF-16LE -t UTF-8 u16.txt > u16.utf8.txt
? cannot open u16.txt: stream did not contain valid UTF-8
The cryptic error still follows, but the user has been told what to do. That is chapter 14’s subject arriving early, and it is a good message: it names the problem in the user’s terms and hands them the fix.
The module’s header says something about the program as a whole: inlined (rather than depending on the encsniff crate) to keep ved pure-stdlib. The detection logic already existed as a crate, written by the same author for sibling programs, and ved could not use it. Chapter 1 said the no-dependencies constraint answered questions in a minute instead of a week, and this is one of them. The answer cost a 131-line module that duplicates code living elsewhere, which has to be kept in step with it by hand, as the header says it is.
The second encoding is the problem. UTF-7 has no byte order mark, so the module looks for a marker instead:
const UTF7_MARKER: &[u8] = b"+ACI-";
+ACI- is how UTF-7 writes a double quote, and it appears in UTF-7 exports
whenever the text contains one. The module comment says detection rules are
deliberately narrow — byte-perfect signatures only, no heuristics, and this
rule is a heuristic. UTF-7 is a 7-bit encoding, so every UTF-7 file is also a
valid ASCII file and a valid UTF-8 file, and there is no signature that can
tell them apart. The marker is a guess about content.
The guess has a consequence, because 0.2.0 also added a refusal to overwrite a file that was detected as non-UTF-8:
$ cat note.txt
He said +ACI-hi+ACI- in UTF-7.
$ ved note.txt
warning: note.txt appears to be UTF-7 encoded.
hint: iconv -f UTF-7 -t UTF-8 note.txt > note.utf8.txt
31
s/said/says/
He says +ACI-hi+ACI- in UTF-7.
w
? refusing to overwrite note.txt (loaded as UTF-7); convert with iconv first, or use `w <newname>` to write elsewhere
That file is plain UTF-8 that happens to contain the marker, as a sentence about UTF-7 would. It cannot be saved in place. Filed as ved #25.
Follow the two detections through load_file and the refusal turns out to
protect only this case. A UTF-16 file fails read_to_string and never reaches
the buffer, so mark_non_utf8_source is never called for it. The only files
that are ever marked, and so the only files the refusal ever blocks, are the
ones that passed the UTF-7 heuristic, all of which are valid UTF-8 and would
have been written back byte for byte. The guard was written for a danger, saving
a file’s content in the wrong encoding, that cannot occur on the path that
reaches it.
What the guard was protecting against is real in a narrower form. A user who types a non-ASCII character into a real UTF-7 file and saves it produces a file that is neither encoding. The warning on load covers that, and the refusal adds nothing but the false positive. The fix is to keep the warning and drop the refusal for UTF-7, which deletes code. The lesson is about guards in general: a check that blocks the user needs the same scrutiny as the operation it guards, because a false positive in a refusal is a bug the user cannot work around without leaving the program.
13.8 What w does not do
run_write is chapter 5’s function with the refusal added. The file it writes
is the one named, and that includes names ed would not treat as names:
w !cat
wrote 2 bytes to !cat
In ed, w !command pipes the buffer to a shell command and r !command reads
a command’s output into the buffer. They are how ed users sort a range, format
a paragraph, or insert a date. ved has no shell escapes, so w !cat creates a
file named !cat in the current directory, which is the worst of the available
behaviors for a script written for ed: it does not fail, and it leaves a file
behind.
The standard library can run a command, with std::process::Command, so this
is not a cost of the constraint. It is unimplemented. A one-line check that
refuses filenames beginning with !, with a message saying shell commands are
not supported, would turn a silent wrong answer into a refusal, and it
is the right first step before the feature.
13.9 How large a file
Chapter 3 noted that ,p builds its whole output as one String and said this
chapter would come back to it when files got large. They have. A file of one
million lines, 56.9 MB, measured on the machine this was written on, with peak
memory from getrusage:
| Command | Time | Peak memory |
|---|---|---|
open and q | 0.08 s | 140.8 MB |
,p to /dev/null | 0.12 s | 140.9 MB |
w out.txt | 0.12 s | 141.6 MB |
g/7/p | 0.27 s | 140.0 MB |
,s/line/LINE/ | 0.28 s | 140.2 MB |
GNU ed, open and q | 0.28 s | 47.7 MB |
GNU ed, ,s/line/LINE/ | 2.33 s | 141.1 MB |
The ,p copy does not show up at all. Its peak is the same as opening the file
and quitting, because loading already holds two copies of the text for a
moment: the String from read_to_string, and the million Strings that
lines() and append_after build from it, before the first is dropped. ,p
builds one buffer-sized string while the lines exist, which is the same shape.
The cost chapter 3 worried about is real and is dominated by one it did not
mention.
GNU ed opens the same file in a third of the memory because it keeps the text
in a scratch file on disk and holds only an index in memory, which is a design
from a machine with 64 KB of address space. ved is three times faster at
opening and eight times faster at a substitution across the file, and uses
three times the memory to be so. For the files people edit with ed, that is
the right side of the trade. Chapter 3 bet that Vec<String> would be fast
enough, and at a million lines it still is.
13.10 What slice eleven bought
A program that edits files: ved file on the command line, e to switch,
r to read one in, w to save, and a missing file that becomes a new one.
At the end of slice eleven the program is 2,006 lines, and it is the first
checkpoint that could replace ed for someone’s daily work.
It is also where most of the data loss in this book lives. CRLF endings are
rewritten without a word, a failed e destroys the buffer, and a guard meant
to prevent corruption blocks saving an ordinary file. None of them is visible
in a session that types its text by hand, which is how nearly every test in the
program builds its buffer. The two tests that load a file check a missing file
and a directory. All three problems are visible the first time the program
meets a file from somewhere else.
Exercise 13-1. Make ved -- -p open a file named -p. Then decide what
ved -p (with no value) should do now that a bare word can be a filename, and
check that your parser and chapter 2’s agree.
Exercise 13-2. Apply the split_terminator fix from section 13.3. Then
implement the other one: detect CRLF at load, remember it on Buffer, and use
it in run_write. Decide what a file with mixed endings should get, and write
the test for each.
Exercise 13-3. Apply the e fix from section 13.5, add E, and write a
test for each of the three cases: refused, forced and failed, forced and
loaded. Then make a second e act as a confirmation, the way a second q
does, without giving dispatch any state.
Exercise 13-4. Remove the overwrite refusal for UTF-7 and keep the warning.
Then decide whether a UTF-8 file containing +ACI- should be warned about at
all, and if not, what evidence would be enough to say a file is UTF-7.
Exercise 13-5. Implement r !command with std::process::Command, reading
the command’s standard output into the buffer. Decide what happens to its
standard error and its exit status, and what the confirmation should say.
Exercise 13-6. Reduce the peak memory of opening a file. Read it with
BufRead::lines instead of read_to_string, measure again, and explain why
the number did or did not halve.
14. The Voice of the Program
ed has two things to say. When something goes wrong it prints ?, and when
something goes right it prints nothing, except a byte count when it reads or
writes a file. Everything else is left to the user’s memory of what they typed.
ved exists to replace that, and chapter 1 put the replacement in its design
table as two rows: full English replacing ed’s bare ?, and echo what each
command did. This chapter is about how those two rows turned out, which means
it is about every string the program prints, who it is printing them for, and
what happens when the reader is not a person.
The slices are eight, nine, ten, and twelve: long-form aliases, friendly errors
and confirmations, the H help command, and l. The first three are in
examples/ch13-files; l arrived in 0.1.4 and is in examples/ved.
14.1 The slice that had nothing to do
The plan gave slice nine a large job: friendly errors, confirmations, Q
(force quit). Chapters 2 and 3 described it the same way, as the slice that
would rewrite the program’s messages, and arranged the code so that the rewrite
would be contained: errors went through one Action variant, and one place in
the loop wrote the ?.
When slice nine arrived, there was almost nothing to rewrite. Compare every
error string in examples/ch12-global with every error string in
examples/ch13-files, which contains slice nine, and one string was added,
cannot open {filename}: {e}, which belongs to slice eleven’s file loading. No
existing message changed. invalid address, no match, unterminated pattern, and the rest had been written in English as each command was built,
because chapter 5 had made the decision, at slice four, that every command
would say what it did in a sentence, and every command after it was written
that way.
So slice nine shrank to two items. d gained its confirmation, deleted 3 lines (2-4), replacing the silence that slice six had copied from ed. And Q
arrived, which quits without the unsaved-buffer warning and is one match arm:
"Q" => return Action::ForceQuit,
The general point is about plans. A slice scheduled to do something across the whole program is a slice that assumes the rest of the program will be built without it. If the decision it represents is made earlier, and applied as the program grows, the slice has nothing to do, and that is the good outcome: a sweep that never needs to happen is cheaper than one that does, by the size of the sweep. The slice plan said when the messages would be finished. The code decided it was every time a message was written.
14.2 An inventory
Run every command that changes the buffer and record what it says. The result is the program’s voice, measured rather than intended:
| Command | ved prints | GNU ed prints |
|---|---|---|
w out.txt | wrote 14 bytes to out.txt | 14 |
e, r, opening a file | 14 | 14 |
| opening a missing file | notes.txt: new file | notes.txt: No such file or directory |
2d | deleted line 2 | nothing |
2,3d | deleted 2 lines (2-3) | nothing |
2,3m1 | moved 2 lines (2-3) to after 1 | nothing |
1m2 | moved 1 lines (1-1) to after 2 | nothing |
1,2t$ | copied 2 lines (1-2) to after 6 | nothing |
1,2j | joined 2 lines (1-2) into line 1 | nothing |
s/a/b/ | the last changed line | nothing |
a, i, c | nothing | nothing |
Three voices are in that table. w, d, m, t, and j speak in sentences.
e and r print ed’s bare byte count, which is the one piece of output ed
already had, kept unchanged when every other command gained a sentence. And
a, i, and c say nothing, which is arguably right, since what they did is
on the screen in the lines the user just typed.
Each confirmation is a format! call in the command that produces it, with no
shared code. That is why deleted line 2 handles the singular and
moved 1 lines does not: run_delete was written with an if count == 1, and
run_move and run_transfer, written later, were not. Chapter 2 put the ?
prefix in one place so that the error format could not drift, and nothing did
the same for confirmations. A helper would:
/// "line 3" or "3 lines (2-4)", for confirmations.
fn describe_lines(start: usize, end: usize) -> String {
if start == end {
format!("line {start}")
} else {
format!("{} lines ({start}-{end})", end - start + 1)
}
}
and run_delete, run_move, run_transfer, and run_join would say deleted {}, moved {} to after {dest}, and so on, with the plural decided once. It is
the same move as chapter 2’s, applied to the half of the program’s voice that
chapter 2 did not cover.
14.3 What the errors say
The errors are better than the confirmations, and the reason is structural.
They pass through one Action variant to one writeln!, they all have the
same shape, a lower-case phrase after ? , and most of them say what the
user needs to know: unterminated replacement, no previous substitute,
cannot write /nope/x.txt: No such file or directory (os error 2).
The weak one is the most common. invalid address appears in nine places in
the source, and it is the answer to all of these:
1000p
? invalid address
0p
? invalid address
3,2p
? invalid address
+10p
? invalid address
Four different mistakes, one message. The first is a line past the end, the
second is the line that does not exist, the third is a backwards range, and the
fourth is an offset past the end. The code that rejects them, in resolve_with
and resolve_one, knows which case it is in, because each is a separate
condition, and it knows the buffer’s length. line 1000 is past the end (the buffer has 3 lines) costs one format! per case and is what a user who typed
1000p by mistake needs to see. It is ed’s ? with the word “address” added.
The ? itself is the other question, and chapter 5 deferred it: the warning on
q with unsaved changes is printed as ? warning: buffer modified, through the
error channel, although nothing failed. That was right, for a reason that has
nothing to do with the user at the terminal. GNU ed prints ? for the same
warning, and a script that drives ed looks for the ?. ved’s warning is an
error in format because ed’s is, and a program that promises compatibility
inherits its predecessor’s decisions about what counts as an error, including
the ones it would not have made itself.
14.4 Who is listening
All of it goes to standard output. That includes the lines the user asked to see, the confirmations, and the errors, in the order they happen. At a terminal that is correct: the user sees one stream, in sequence, and every line is about the command just above it.
A script is a different reader. ed scripts are usually run like this:
$ ed -s notes.txt < edits.ed
-s is ed’s flag for silence. It suppresses the byte counts and the
diagnostics, so the only output is whatever the script asked to print. It is
the most common way ed is invoked from a shell, and ved does not have it:
$ ved -s notes.txt < edits.ed
ved: unknown option: -s
try 'ved --help' for usage information
$ echo $?
2
Without -s, a script that runs ved and captures its output gets the
confirmations mixed into the text:
$ printf ',p\nd\nw\nq\n' | ved greeting.txt > captured.txt
$ cat captured.txt
6
hello
deleted line 1
wrote 0 bytes to greeting.txt
The script asked for one line, hello, and got four.
The third difference is the exit status. GNU ed, reading commands from
something that is not a terminal, exits 1 if any command failed, so a shell
script can write ed -s file < edits.ed || exit 1 and stop when an edit did
not apply. ved exits 0 after any number of errors:
$ printf 'zz\nq\n' | ved notes.txt; echo $?
22
? unknown command: zz
0
These are three halves of one problem. ved’s voice was designed for the person
at the keyboard, and the design table says so. It made no provision for the
other reader, and ed’s compatibility with scripts lives almost entirely in how
it treats that reader: silence on request, and a status that reports failure.
The ved README describes its compatibility as close enough that most scripts
written for ed run unchanged, which is accurate, and the scripts that do not
are mostly the ones that use -s. The flag and the exit status are filed as
ved #27 and ved
#26.
Chapter 12 left a question here, about whether g/TODO/d over a file with no
matches should print ? no match, as ved does, or nothing, as ed does. The
answer is that it depends on who is listening, and that is the design ved
needs: one flag that changes the reader.
enum Action {
Quit,
ForceQuit,
EnterInputMode,
Done,
Print(String),
Confirm(String),
Error(String),
}
The flag cannot be implemented with the Action the program has. Print is
used for both the output the user asked for, the lines p prints, and the
confirmations the program volunteers, deleted line 1, and the loop cannot
tell them apart, so it cannot suppress one without the other. A Confirm
variant, used by every command that reports what it did, gives the loop the
distinction. Then -s sets a flag in run_repl, the Confirm arm prints only
when the flag is clear, and the Error arm records that an error happened so
that the loop can return ExitCode::FAILURE at the end. No command changes
except to return a different variant.
This is chapter 2’s exercise 2-1 arriving for real. It asked where a quiet
flag should live, in dispatch or in the loop, and the answer is the loop, for
the reason chapter 2 gave: output is the loop’s job. What chapter 2 could not
show is that the answer depends on the types. A flag in the loop is only as
precise as the distinctions Action makes, and an enum that merges two kinds
of output into one variant has decided, in advance, that no reader will ever
want one without the other.
14.5 Long names
"q" | "quit" => return Action::Quit,
"a" | "append" => {
// ...
"d" | "delete" => return run_delete(&spec, buf),
"p" | "print" => return run_print(&spec, buf, PrintMode::Plain),
"n" | "number" => return run_print(&spec, buf, PrintMode::Numbered),
"l" | "list" => return run_print(&spec, buf, PrintMode::List),
"j" | "join" => return run_join(&spec, buf),
"H" | "help" => return run_help(),
Slice eight is a second pattern in eight match arms, and it is safe for a
reason worth checking rather than assuming. A long name is only harmless if it
is not already a valid ed command, since delete might be d followed by
something ed would accept. Each of ved’s long names typed into GNU ed is an
error, ? Invalid command suffix or similar, so no script written for ed can
contain one meaning something else. The aliases add vocabulary without changing
the meaning of anything that was already legal.
Chapter 10 said s could have no long name, and the plan’s design table says
why: substitute, global, and inverse global stay short-only because their
/foo/bar/ argument syntax makes long names ambiguous. subst/a/b/ cannot be
distinguished from s with u as its delimiter, and global/x/p from g
with l as its delimiter. The rule is that a command whose first argument
character is arbitrary cannot have a name longer than one letter.
The same table promised three more: write, read, and edit. They were
never implemented. The plan marks slice eight as done, and its example, in the
slice list, is long-form command aliases (append, write, quit, etc.).
What write does instead:
$ ved notes.txt
22
write
wrote 22 bytes to rite
edit
dit: new file
write saved the buffer to a file named rite, and edit opened a file named
dit and, because of chapter 13’s e, discarded the buffer to do it. Neither
said anything that looked wrong. A user who read the plan, or guessed the name
from append and delete, gets a file with a strange name, or loses their
work. Filed as ved #15.
The same mechanism reaches the most common command in ed scripts. wq, write
and quit, is how a great many of them end:
$ printf 's/hello/bye/\nwq\n' | ved f.txt
6
bye
wrote 4 bytes to q
ved read wq as w with the filename q. It wrote the edited buffer to a new
file named q, left f.txt unchanged, did not quit, and exited 0 when its
input ran out. A script that ends in wq runs to completion under ved, reports
success, and does not change the file it was written to change. GNU ed writes
f.txt and quits. Filed as ved
#14.
The cause is in the second stage of the dispatcher, which takes the first
character of the command as the letter and everything after it as the argument,
with trim_start() removing any space. w file and wfile are the same
command to ved. GNU ed requires the space, or the end of the line, after w,
e, and r, and rejects write with ? Unexpected command suffix, which is
why the name was safe to give a meaning in the first place. ved accepted the
spaceless form, so the name had a meaning already, and it was not the one the
plan intended.
The fix has two parts and the order matters. First, require whitespace or the
end of the line after e, r, and w, so that write becomes ? unknown command: write, which is at least true. Then add the aliases. Doing only the
second, by putting "write" in a match arm, would fix the word and leave
wnotes.txt as a way to write to notes.txt that ed scripts do not expect.
This is in 0.3.0 unchanged.
14.6 Help, by hand
fn run_help() -> Action {
Action::Print(
"\
ved commands (addresses shown in brackets are optional):
[.]a, append Append text after the addressed line. End with '.'
[.]i, insert Insert text before the addressed line. End with '.'
// ... fifteen more lines ...
"
.to_string(),
)
}
H prints a reference, and it is a string literal. Chapter 6 said the help was
a separate hand-written list of the commands, and that this chapter would admit
what that costs. Here is the cost, found by comparing the string with the
dispatcher:
e, r, and Q are implemented and missing from the help. The README’s
command table lists all three, so the two documents that describe the commands
disagree with each other as well as with the code. g and v are shown as
[.,.]g/re/cmd, which says the default address is the current line; it is the
whole buffer, 1,$, which is the most important fact about g. And w is
shown as [.,.]w, with the text default: all, which contradicts its own
brackets. Filed as ved #29.
None of this can be caught by a test of the kind the program has, since the help is a string and the tests check behavior. It can be caught by a test of a different kind, cheaply:
#[test]
fn help_mentions_every_command() {
let Action::Print(help) = run_help() else { panic!() };
for cmd in ["a", "i", "c", "d", "p", "n", "l", "j", "m", "t",
"s", "g", "v", "w", "e", "r", "q", "Q", "H"] {
assert!(help.contains(&format!("{cmd} ")) || help.contains(&format!("{cmd},")),
"help does not mention {cmd}");
}
}
The list in the test is a third copy of the command set, which is the obvious objection to it, and it is still better than two copies that drift silently, because when it drifts it fails. The real fix is the one chapter 6 decided against: a table of commands that both the dispatcher and the help are generated from. Chapter 6 named the condition under which a table wins, something other than the dispatcher needing to enumerate the commands, and noted that the help is such a thing. Three copies of a list, and four mistakes in the one nobody tests, are what leaving the table unbuilt cost.
H itself is a compatibility decision. In ed, H toggles help mode, in which
every ? is followed by an explanation, which is the closest ed comes to ved’s
purpose. ved prints English errors all the time, so the toggle would do
nothing, and the letter was reused for the reference. A script that sends H
to get verbose errors gets the help text in its output instead, which is
harmless and is one more line on the list of things a script does not expect.
14.7 Showing what is invisible
l arrived in 0.1.4, as slice twelve. It prints lines with the characters a
terminal would hide made visible, and it ends each line with $ so that
trailing spaces can be seen:
a
café x\y
.
l
caf\303\251\011x\\y$
Non-ASCII bytes as three-digit octal, a backslash doubled so that it cannot be
mistaken for an escape, and $ at the end. That is POSIX’s format, and GNU ed
agrees on the é, which is two bytes in UTF-8 and is shown as both of them.
It disagrees on two things. POSIX says that \t, \a, \b, \f, \r, and
\v are written as those escapes rather than in octal, so GNU ed prints the tab
as \t and ved prints \011. And POSIX says that long lines are folded, with
a backslash at the point of folding, so that a line of a hundred characters is
shown as two lines of output on a narrow terminal. ved prints it as one.
The tab is held in place by a test named list_tab_becomes_octal, which
asserts ved’s behavior rather than the standard’s. That is the shape chapter 11
found with join_single_line_is_silent_noop: a test that describes what the
code does, written at the same time as the code, so that when the code was
wrong the test agreed with it. Chapter 15 is about how to write tests that can
disagree.
14.8 What the voice bought
Errors that say what went wrong, a help command, long names for the commands
that can have them, l, and a confirmation for most commands that change the
buffer. For the person at the keyboard, ved does what chapter 1 said it would.
For a script, it is louder than ed and reports success after a failure, and the
gap between the two readers is one flag and one Action variant wide. The
inventory in section 14.2 found three styles of confirmation, the help was
missing three commands, and the plan’s three remaining aliases did something
other than what their names said. None of that was decided. It accumulated in
the places where each command spoke for itself, and the parts of the voice that
were consistent were the parts that went through one function.
Exercise 14-1. Add describe_lines from section 14.2 and use it in every
confirmation. Then decide whether e and r should say read 22 bytes from notes.txt, and whether doing so breaks anything a script depends on.
Exercise 14-2. Make invalid address say which of the four cases in
section 14.3 occurred. Keep the phrase invalid address at the start of each
message, and decide why that might matter.
Exercise 14-3. Implement -s: add Action::Confirm, move every
confirmation to it, suppress confirmations and byte counts when the flag is
set, and exit 1 if any command failed. Then run an ed script that uses -s
against both programs and diff the output.
Exercise 14-4. Require whitespace after e, r, and w, then add
write, read, and edit. Write the test that write does not create a file
named rite.
Exercise 14-5. Replace the help string and the dispatcher’s match with one table of commands, and generate the help from it. Keep the match for dispatching if you can. Count the lines, compare with chapter 6’s exercise 6-2, and decide whether the answer flipped.
Exercise 14-6. Make l print \t for a tab and fold lines longer than 72
columns, as POSIX specifies. Fix the test that asserts the old behavior, and
decide what the folding width should be on a terminal that is wider.
15. Testing
ved 0.2.1 has 125 tests, they all pass, and they run in less time than cargo test takes to print its header. Chapters 10 through 14 found, between them,
more than twenty ways in which the program does something other than what ed
does, at least five of which lose or misplace text. None of the 125 tests
fails on any of them.
That is not an argument that the tests are bad. Most of them are the right tests, of the right shape, and they are why the program could be changed without fear from its first release to 0.2.1. It is an argument that a passing suite is a statement about the questions the suite asks, and this chapter is about which questions ved’s suite asks, which it does not, and three cheap ways to ask the rest.
15.1 What there is
| Module | Lines | Tests |
|---|---|---|
bre.rs | 1,064 | 90 |
main.rs | 1,287 | 32 |
enc.rs | 131 | 3 |
address.rs | 233 | 0 |
buffer.rs | 156 | 0 |
The regex engine is the most tested part of the program by a wide margin, and that is the right allocation. It is the hardest code, it is the code with an external specification precise enough to write expected values from, and its tests are cheap, because a pattern and a string go in and a match comes out:
#[test]
fn backref_to_uncaptured_fails() {
// \1 with no group should fail to match
assert!(!has_match(b"^\\1$", b"anything"));
}
address.rs and buffer.rs have no tests of their own. Both are exercised
through main.rs, since every command test parses an address and changes a
buffer, so they are covered in the sense that their code runs. They are not
covered in the sense that anyone has stated what they should do in a case the
commands do not happen to reach. resolve_with has four conditions for an
invalid address, and chapter 11’s 0a was the fifth case, one nobody had
written down.
15.2 What dispatch tests are worth
Chapter 2 made dispatch return a value instead of printing, and said this
chapter would show what that was worth. Here is what it was worth:
#[test]
fn move_into_self_errors() {
let mut buf = buf_with(&["a", "b", "c", "d", "e"]);
let act = dispatch("2,4m3", &mut buf);
assert!(matches!(act, Action::Error(_)));
assert_eq!(buf.line(3), Some("c"));
}
Every command test in the program has that shape. Build a buffer from a list
of strings, call dispatch with what a user would type, and check two things:
the Action that came back, and the buffer afterwards. There is no process, no
terminal, and no captured output, and the whole suite finishes in what cargo
reports as 0.00 seconds.
The assertions are as important as the setup, and they share a habit. They
check the kind of Action, with matches!(act, Action::Error(_)), and they
check the buffer’s contents line by line. They almost never check the text of
a message. That is why chapter 14 could propose rewriting invalid address
into four different messages without breaking a test: the tests say that 2,4m3
must fail and must leave line 3 alone, which is the requirement, and they leave
the wording free, which is the part that should be free to improve.
A test that asserts on a message string is a test of the message. There are cases where that is the point, and ved has one, which section 15.4 is about. In most cases it is an accident that makes the suite fight every change to the program’s voice.
15.3 The layer nobody tested
dispatch tests stop at dispatch. Everything that happens after an Action
is returned is in run_repl, which turns the value into output and decides the
exit status, and in main and parse_args, which run before it. At 0.2.1, none
of that has a test.
Two bugs from earlier chapters live in that layer. Chapter 11’s single-line
j returns Action::Print(String::new()), which a dispatch test sees as an
empty string and the loop prints as a blank line. Chapter 14’s exit status is
0 after a failed command, which no dispatch test can see because dispatch
does not return an exit status. Both are visible from outside the process, and
Cargo has direct support for testing from there. A file in tests/ is an
integration test, compiled as a separate crate, and Cargo gives it the path to
the program’s binary:
use std::io::Write;
use std::process::{Command, Stdio};
fn session(input: &str) -> (String, i32) {
let mut child = Command::new(env!("CARGO_BIN_EXE_ved"))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("ved runs");
child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap();
let out = child.wait_with_output().unwrap();
(String::from_utf8(out.stdout).unwrap(), out.status.code().unwrap())
}
#[test]
fn single_line_join_prints_nothing() {
let (out, _) = session("a\none\ntwo\n.\n2,2j\nQ\n");
assert_eq!(out, "");
}
#[test]
fn failed_command_sets_exit_status() {
let (_, status) = session("zz\nQ\n");
assert_eq!(status, 1);
}
Added to a copy of examples/ved, both fail, with the bugs they were written
for:
assertion `left == right` failed
left: "\n"
right: ""
assertion `left == right` failed
left: 0
right: 1
session is the whole harness, and it is the one piece of test infrastructure
this program lacked. It drives ved the way a user or a script does, through
standard input, and it sees what they see. The tests are slower than
dispatch tests, since each one starts a process, and they should be few: one
for each thing the loop is responsible for, which is a short list. Prompts,
input mode, the double q, the exit status, what goes to standard output and
what goes to standard error. The command language stays in dispatch tests,
where it is cheap.
The general rule is that a test suite should have at least one test at every
boundary the program has with the outside world, because the bugs that live at
a boundary are invisible from either side of it. ved’s suite had tests on one
side of dispatch and none on the other.
15.4 Tests that agree with the code
Chapter 14 found a test that holds a deviation from POSIX in place:
#[test]
fn list_tab_becomes_octal() {
assert_eq!(render_list_line("a\tb"), "a\\011b$");
}
POSIX says l writes a tab as \t. GNU ed does. ved writes \011, and this
test makes sure it keeps doing so. Chapter 11 found another, which asserts that
a single-line join returns an empty Print and is named as though it asserted
silence.
Both tests were written at the same time as the code they test, by the same author, and the expected value in each came from the same place as the code: the author’s idea of what the function should do. When that idea was wrong, the test was wrong in the same way, and the two agreed. A test like that is not useless, since it still catches the code changing by accident, but it cannot catch the code being wrong, because it has no independent source of truth.
The repair is about where the expected value comes from.
list_tab_becomes_octal should have been written by reading the POSIX
description of l, or by running printf 'a\tb\n' | ed -s with an l
command, and copying what came out. Then the test disagrees with the code on
the day it is written, and the disagreement is the finding. A test that can
never disagree with the code it tests is documentation.
Chapter 14 asked how to write tests that can disagree. That is the answer: the expected value comes from somewhere the code did not.
15.5 A second program as the specification
Chapter 7 described a bug that survived because it was not in any layer the
tests covered. match_star tried the shortest repetition first, the engine’s
tests all passed, and the wrong answer appeared only in the output of s, two
slices later, as a disagreement with POSIX’s leftmost-longest rule. Chapter 7
said this chapter had a name for that, and a way to test for it.
The name is differential testing. When a program has a reference
implementation, the reference is the oracle: run the same input through both
and compare. Any difference is either a bug in the program, a bug in the
reference, or a deliberate deviation, and all three are worth knowing about.
Chapter 1 chose ed partly because a specification existed. The most useful
form of that specification is not POSIX’s text. It is /usr/bin/ed, which is
installed on the machine and answers any question in a millisecond.
Most of the bugs in chapters 10 through 14 were found that way, by hand: type a
command into both editors and compare. Automating it takes about forty lines.
The harness used here generates random scripts from a small grammar of
addresses and commands, runs each through ved and through GNU ed on the same
six-line file, ends each script with w out.txt and Q, and compares the
files the two editors wrote:
CMDS = ["p", "n", "d", "j", "m{a}", "t{a}", "s/a/X/", "s/a/X/g", "s/^a/X/g",
"s/$/!/g", "s/[ab]*/-/g", "s/\\(a\\)\\(.\\)/\\2\\1/", "s.a\\..X.", "s/a/X",
"g/a/d", "g/a/j", "g/a/m0", "g/b/-1d", "v/a/d", "g/a/s/a/A/", "g/a/.,+1d",
"a\nNEW\n.", "i\nNEW\n.", "c\nNEW\n.", "s"]
Comparing the written file rather than the output is the decision that makes the harness usable. ved’s messages differ from ed’s on purpose, so comparing everything either editor printed would report a difference on every line. The file is the part that has to agree, and it is the part a user loses if it does not.
Three thousand single-command scripts against ved 0.2.1, with a fixed random seed, took twelve seconds. 516 of them left a different file:
| Command | Different | Run |
|---|---|---|
s.a\..X. (escaped delimiter, ch. 10) | 87 | 132 |
s/a/X (optional delimiter, ch. 10) | 86 | 116 |
s/$/!/g (empty match, ch. 10) | 77 | 130 |
s/[ab]*/-/g (empty match, ch. 10) | 69 | 103 |
g/a/.,+1d (stale marks, ch. 12) | 54 | 132 |
g/a/j (stale marks, ch. 12) | 46 | 121 |
g/b/-1d (stale marks, ch. 12) | 42 | 107 |
a with an address (ch. 11) | 37 | 123 |
i with an address (ch. 11) | 18 | 104 |
Every row is a bug this book had already found by hand, which is a check on
the harness as much as on the program. Then the same three thousand scripts
against a copy of examples/ved with the fixes from chapters 10 through 13
applied: 155 differences, all from two causes. 86 are s/a/X, the optional
closing delimiter, which no chapter fixed. 69 are s/[ab]*/-/g, where GNU ed
refuses with ? Infinite substitution loop and ved, after chapter 10’s fix,
gives the answer sed gives. That row is a disagreement with the reference
that the program is right to keep, and the harness has no way to know that.
A person has to read it.
The harness also found a bug in this book. Chapter 11’s first version of
resolve_target checked only the second address of a range, so 9,3a on a
six-line buffer appended after line 3 when ed reports an error, and tightening
it to reject a backwards range made 3,1a an error when ed accepts it. Both
were caught on the first run after each change, and the version in chapter 11
is the one that passes. Neither case was among the eleven that chapter 11
checked by hand, which is the argument for generating cases rather than
choosing them: a person picks the cases they have thought of.
With scripts of one to three commands, where earlier commands move the current
line for later ones, the count goes from 607 of 2,000 on 0.2.1 to 195 after the
fixes. Most of the remainder is the same two causes. The rest are smaller
disagreements about where the current line ends up after a command that does
nothing, such as a single-line j, which leaves ed’s current line where it was
and moves ved’s.
A harness like this is not a unit test, since it needs GNU ed installed and takes seconds rather than microseconds, and it should not run on every build. It is a tool to run when the command language changes, and its output is a list of things to read rather than a pass or a fail.
15.6 Input nobody typed on purpose
Chapter 5 found a panic that lived from slice four to the writing of the
chapter: a non-ASCII character typed as a command sliced a str off a
character boundary. Chapter 5 said the tests missed it because they drive the
program with the command language, which is ASCII, and that this chapter would
come back to what a suite built from valid input cannot tell you.
It cannot tell you what invalid input does. Every test in the suite was written by someone thinking about a command, and so every test is a command. The panic needed a string that is not a command at all, and nobody writes a test for a string they would never type.
A fuzzer writes them. The full version is a crate, and the minimal version is a
test with a random number generator and catch_unwind:
#[test]
fn fuzz_dispatch_never_panics() {
let alphabet: Vec<char> =
"0123456789$.,;+-/\\[]()*^&gvsdpnljmtaciqQH \té×".chars().collect();
let lines = ["a", "é", "", "aéb", "ab", "\\"];
let mut seed: u64 = 0x9E3779B97F4A7C15;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
std::panic::set_hook(Box::new(|_| {}));
for _ in 0..1_000_000 {
// a random buffer of 0-4 lines from `lines`,
// then 1-4 random commands of 1-10 characters each
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
for c in &cmds {
dispatch(c, &mut buf);
}
}));
// record each distinct panic message and an example
}
}
The generator is xorshift, three lines, and the alphabet is the command
language’s characters plus three that are not ASCII. w, r, and e are left
out so that the fuzzer cannot write files. set_hook silences the default
panic message so that a million runs do not print a million backtraces, and
catch_unwind turns each panic back into a value the loop can record.
Run against examples/ch10-substitute, which still has chapter 5’s bug, a
million sequences took 0.99 seconds and found it twice, once for each non-ASCII
command character that reached the dispatcher’s slice:
PANIC start byte index 1 is not a char boundary; it is inside 'é' (bytes 0..
e.g. ["(/", "1é3 \\s9lé "] on ["", "\\", "ab", "ab"]
PANIC start byte index 1 is not a char boundary; it is inside '×' (bytes 0..
e.g. ["×;×Hp9"] on ["a", "aéb", "\\"]
2 distinct panics in 1000000 runs
Run against 0.2.1, a million sequences found nothing, and the same against
0.3.0. That is a real result, and it should be read for what it measures:
within this alphabet, this length, and this buffer, dispatch does not panic.
It says nothing about wrong answers, and the contrast with the previous section
is the useful part. The differential harness found 516 disagreements in twelve
seconds and the fuzzer found no crashes in a second, on the same program. ved’s
bugs are almost all of the first kind. A program that answers plausibly and
wrongly will pass a fuzzer indefinitely.
The two tools ask different questions. The fuzzer asks whether the program survives any input. The differential harness asks whether it gives the right answer to valid input. A suite built only from hand-written cases asks whether it gives the right answer to the input its author thought of. All three questions are cheap to ask, and ved, at release, asked the third.
15.7 Measuring the representation
Chapter 3 chose Vec<String> for the buffer and said that this chapter was
where the measuring happens. Chapter 3’s exercise 3-5 asked for the number,
and here it is. Buffer from examples/ved, compiled with --release, filled
with lines of fifty characters, on an 11th-generation Intel Core i7 laptop:
| Buffer | 1,000 inserts at line 1 | 1,000 inserts at the end | 1,000 deletes of line 1 |
|---|---|---|---|
| 100,000 lines | 51 ms | 0.04 ms | 48 ms |
| 1,000,000 lines | 1.37 s | 0.03 ms | 1.42 s |
An insert at the top of a hundred-thousand-line buffer costs about 51 microseconds, which is the memory move chapter 3 predicted and is invisible to a person typing. At a million lines it is 1.4 milliseconds per line, so pasting a thousand lines at the top of a million-line file takes over a second, and that is the first number in this book where the representation shows.
The pathological case is a command that does an insert per line across the
whole buffer. g/^/m0 reverses a file by moving every line to the top in turn,
which is quadratic with Vec<String>. On a hundred thousand lines it took 6.6
seconds in ved and 18.1 seconds in GNU ed.
So chapter 3’s bet holds, with a measured boundary on it. For files people edit with ed, the vector is faster than anything that would replace it, because it is simple and cache-friendly. It stops being invisible around a million lines, and only for operations near the top of the buffer. A program that expected to edit files that size would want a gap buffer or a rope, and it would know so from a benchmark rather than from a feeling.
There is no benchmarking crate in this measurement, because there is no crate
in this program. std::time::Instant around a loop, in a binary built with
--release, run twice to check the numbers repeat. That is enough to answer
the question chapter 3 asked, and the question was the hard part.
15.8 What not to test
The preface promised this chapter would say what not to test as well, and the earlier sections imply most of it.
Do not assert on the wording of messages, except in the tests whose subject is
a message. Do not test the standard library: a test that Vec::insert puts a
line where it was asked is testing Rust. Do not write a test whose expected
value you got by running the code, because it will agree with the code forever,
including when the code is wrong. And do not write a test that cannot fail: a
test that loads a file it just wrote, with no assertion on the contents, adds
to the passing count and to nothing else.
The other side of that list is where to spend the effort. One test per boundary with the outside world. Expected values from the specification or the reference. Random input, both valid and not, generated by a program. And for every bug found by any means, a test that fails before the fix and passes after, so that the passing count grows by the number of things the program has learned.
15.9 What the suite bought
A program that could be changed from release to release without breaking what
it already did, which is what a regression suite is for. 125 tests in
hundredths of a second, almost all of them through the dispatch boundary that
chapter 2 made for this purpose.
It did not buy correctness against ed, because nothing in it consulted ed. The three additions in this chapter cost a script of about forty lines, a test of about fifty, and an integration file of twenty-five, and between them they reproduce most of what the five chapters before this one found about what the program does to text. 0.3.0 has 185 tests. The next chapter but three is about what those sixty added tests do and do not check.
Exercise 15-1. Add tests for address.rs directly: one for each condition
in resolve_with that produces invalid address, and one for each form in
chapter 4’s grammar table. Write the expected values from the table, not from
running the code.
Exercise 15-2. Add the session harness to examples/ved and write one
test for each responsibility of the loop listed in section 15.3. Count how many
fail.
Exercise 15-3. Write the differential harness from section 15.5 in Rust, as
an ignored test that runs only when GNU ed is installed. Add r, e, and w
to the grammar with files in a temporary directory, and see what it finds in
chapter 13’s territory.
Exercise 15-4. Extend the fuzzer to drive the binary through session
rather than dispatch, so that input mode and the loop are reachable. Decide
what to do about commands that never return, such as an input mode that never
sees its ..
Exercise 15-5. Fix list_tab_becomes_octal by writing what POSIX requires
and letting it fail. Then go through every test in bre.rs and mark each
expected value with where it came from: POSIX, GNU ed, or the code. Count each.
16. Documentation
At 0.2.1, ved is described in seven places. The README, 226 lines on GitHub and
crates.io. A tutorial, docs/index.html, published on the project’s website.
The H command and ved --help, inside the program. Module header comments
and 180 lines of doc comments in the source. Seventy-six commit messages. And a
PLAN.md and BACKLOG.md that live in the author’s working copy and are no
longer committed.
Each of them has a different reader and is true for a different length of time, and most of what goes wrong with documentation is putting a sentence in the place whose reader or lifetime does not match it. This chapter goes through the seven, checks what each one says against what the program does, and ends with the rule chapter 1 introduced and promised this chapter would argue for: where the reasoning goes.
16.1 The README
# ved — the verbose ed
## Why
## Install
### Debian and Ubuntu
### Homebrew
### Prebuilt binary (Linux and macOS)
### Windows
### Cargo
### Build from source
## Quick start
## Commands
## Addresses
## Regular expressions
## As your default editor
## Implementation
### Limitations worth knowing
## License
Chapter 1 called the README the primary interface for everyone who is not you, and the order of its sections is the order of that reader’s questions. What is it, why would I want it, how do I get it, how do I start, what are the commands. The implementation comes near the end, because it is for the smaller group who got that far, and the license is last.
The opening paragraph does the most work and is the most often read. It names
the program, says what it is a clone of, says what it adds, and states the
compatibility claim: close compatibility so most scripts written for real ed
run against ved unchanged. That sentence was rewritten from an earlier one,
strict drop-in compatibility, when its author listed what ved does not have:
search addresses, u, !, =, k, f, and the repurposed H. The
commit that made the change says so, and it is the README’s best sentence,
because it is the one that was checked.
The quick start was not:
$ ved myfile.txt # open a file
135 # ved prints the byte count
* ,p # print all lines
Hello world
This is a test file
* 1s/Hello/Goodbye/ # substitute on line 1
Goodbye world
* g/test/n # print lines matching "test" with numbers
2 This is a test file
* w # write back to the file
37
* q # quit
Run it, with a file containing those two lines:
$ ved myfile.txt
32
,p
Hello world
This is a test file
1s/Hello/Goodbye/
Goodbye world
g/test/n
2 This is a test file
w
wrote 34 bytes to myfile.txt
q
The byte counts are wrong, which is minor. The prompt is shown although ved has
none without -p, which will confuse the first reader who tries it. And w
is shown printing 37, ed’s bare byte count, where ved prints wrote 34 bytes to myfile.txt. The one line in the example that demonstrates ved’s purpose,
saying what it did, shows ed’s behavior instead. The transcript was written
from what the author expected rather than copied from a terminal.
The Limitations worth knowing section has the same problem in a different
form. It says lines are delimited by \n (or \r\n), which is true on the
way in and leaves out that chapter 13’s CRLF file comes out with \n. It says
w refuses to overwrite a UTF-7 file because saving edits as UTF-8 would
silently corrupt the source, which chapter 13 showed cannot happen on the path
that reaches the refusal. Chapter 9 found a third sentence there, UTF-8 text
with multi-byte characters works, which was false for any substitution that
split a character. Each was true of what the author intended, and none was
checked against the program.
16.2 The tutorial
The tutorial is the longest piece of documentation ved has, and it is the best written: it explains what a line editor is, why a newcomer should care, and walks through a session one command at a time, with the long-form names, so that someone who has never seen ed can follow it. Then, under Working with files:
* write notes.txt
wrote 37 bytes to notes.txt
Chapter 14 found that write is not implemented. Typed into ved, that line
saves the buffer to a file named rite notes.txt:
$ ved -p '* '
* append
The quick brown fox
.
* write notes.txt
wrote 20 bytes to rite notes.txt
The tutorial also teaches edit filename, which opens a file named dit filename and, because of chapter 13’s e, discards the buffer first, and
read filename, which reads from a file named ead filename. A reader who
follows the tutorial carefully, in order, loses the work they typed in the
earlier sections at the point where they were taught to save it. It is filed as
ved #16, the most urgent issue
this book produced.
Further down, the same page says the commands that already use
delimiters — s/old/new/, g/pattern/cmd, v/pattern/cmd, w filename, e filename,
r filename — have no long form. The tutorial contradicts itself, and the
second statement is the true one. The first was written from the plan, which
listed write, read, and edit as aliases; the second from the code. The
page is unchanged in the repository at 0.3.0.
That is the most expensive documentation bug in this book, and its cause is simple. Every terminal session in the tutorial was typed rather than captured. The preface of this book makes a promise its author found necessary for the same reason: terminal sessions show what the program actually printed. A transcript in documentation is a claim about the program’s behavior, the same kind of claim a test makes, and it needs the same treatment as a test: it must be produced by running the program, and re-produced when the program changes.
Rust has this for code. rustdoc compiles and runs the examples in doc
comments, and mdbook test does the same for a book’s code blocks, which is
why every fragment in this book is tagged rust,ignore: it marks the block as
not meant to compile on its own. There is no standard tool for terminal
sessions, but for a program that reads standard input the tool is short. Split
each session into the lines the user typed and the lines the program printed,
feed the first to the binary, and compare its output with the second. Chapter
15’s session function is most of it. A documentation test that fails when
the tutorial is wrong is the same kind of check as a differential test against
ed, with the documentation as the reference.
16.3 Comments that describe a plan
Search the shipped source for the word slice:
// `filename` remembers the last filename used by `w`, so a bare `w`
// after `w foo.txt` writes back to foo.txt. Slice 11 will also set
// this when ved is invoked with a filename argument.
// Address forms recognized in slice 3:
// 5 absolute line number
// ...
// Search addresses (/foo/, ?foo?) wait for slice 5 when the regex
// engine arrives. Compound expressions like $-5 also wait.
Action::Error(msg) => {
// ved's friendly-error format. Slice 9 will route
// every error path through this variant and may add
// an H toggle to suppress the message like real ed.
let _ = writeln!(out, "? {msg}");
Three comments in buffer.rs, address.rs, and main.rs describe the
program as it was during the slice in which they were written, and refer to
future slices that have since happened. Slice 11 did set the filename. Slice 5
did not bring search addresses, which chapter 4 discussed. Slice 9 did not
route anything, because every error already went through the variant, and H
became the help command rather than a toggle.
None of these comments was wrong when it was written. Each is a sentence in the
future tense, and the future arrived. That is the failure chapter 1 described:
a sentence about a change, sitting in a file that is read as a description of
the present. A reader opening buffer.rs today is told that ved cannot yet
open a file named on the command line.
The module header of bre.rs is the larger case:
// ved's BRE engine — compiled, with capturing groups and
// backreferences.
//
// Step 1 was a direct port of Pike's recursive matcher: three
// functions, no compile step, the pattern itself is the program.
// That original is preserved in git history (commit c53f626).
//
// Step 2 introduced a compile step (closer to Ken Thompson's
// original ed) and bracket expressions ([abc], [^abc], [a-z]).
//
// Step 3 wrapped the compiled form in a Regex struct, returning
// match positions via a Match struct.
//
// ...
Twenty lines of history, five steps of how the engine was built, ending with a
known limitation. It is interesting, and this book is in part a longer version
of it, but it is a commit log living in the source. And it has decayed in a way
that a commit log cannot: commit c53f626 does not exist in ved’s repository.
ved began inside another repository and was moved to its own, and that commit
did not come with it. The reference points at a history the reader cannot
reach.
What the header should say is what the module is now. A present-tense version is shorter:
// ved's regex engine: POSIX Basic Regular Expressions, compiled to a
// flat list of elements and matched by recursive backtracking.
//
// Supports literals, `.`, `*`, `^`, `$`, bracket expressions with
// ranges and negation, `\(...\)` groups, `\1`-`\9` backreferences,
// and `\0NN` octal escapes. Matching is leftmost-longest. `*` applies
// to a single atom only; `\(...\)*` is not supported.
Every sentence there will stay true until the code changes, and when the code changes, the comment is beside it to be changed too. The history went into the commit messages when it happened, and the README says the full history is in the git log, which is the right pointer.
16.4 Doc comments
The doc comments are, by count, most of ved’s documentation: 180 lines of
/// across five files. Most of them are good, and the good ones share a habit.
They say something the code does not:
/// Called by `w` after a successful whole-buffer write. A
/// partial-range write does NOT clear modified, since the
/// buffer still differs from any single file on disk.
pub fn mark_saved(&mut self) {
The function body is one assignment. The comment is the design, and it is what
stops a later reader from calling mark_saved after 1,2w.
The bad ones share a different habit. They describe what the author intended
the function to do, and nothing compares the description with what it does.
run_edit’s doc comment says it warns if the buffer has unsaved changes (like
q does), and it does not. run_join’s says a single-line range is a silent
no-op, and it prints a blank line. enc.rs’s header says its rules are
byte-perfect signatures only, no heuristics, and its UTF-7 rule is a
heuristic. In all three cases the comment states the requirement correctly and
the code does not meet it, which means the comment is useful: it is the bug
report, written in advance, by the person who knew what the code was for.
The lesson is not that doc comments should be trusted less. It is that a doc comment which states a requirement is a test that nobody wrote. Warns if the buffer has unsaved changes is one assertion away from being checked, and if the assertion had been written beside the comment, the function would have failed it on the day it was written.
16.5 Commit messages
Chapter 1 said this chapter would make the case that commit messages are the right home for a kind of writing that otherwise ends up in the source. Here is one:
Treat a missing file as a new file, matching ed
Opening ved on a path that doesn't exist no longer prints an error and
forgets the name. It now remembers the filename, leaves an empty
unmodified buffer, and prints "<name>: new file", so a later bare w
creates the file. This matches ed, which never refuses a missing file
and creates it on first write rather than at startup.
Only ErrorKind::NotFound gets this treatment; permission errors,
is-a-directory, and the like stay real errors. The same path covers the
e command, since both route through load_file. load_file now returns a
LoadOutcome enum (Loaded/NewFile) so callers can word the two cases.
Adds the first filesystem-touching tests, in pure stdlib: one asserts a
missing file loads as NewFile with the name remembered and nothing
written to disk, the other asserts a directory still errors.
It says what the program did before, what it does now, why, where the boundary
of the change is, what else it affects, and how it was tested. Every one of
those is a statement about a change, and every one would be wrong in the source
by the next release: “no longer prints an error” describes a former state,
“now returns” is relative to a version nobody will be looking at, and “the
first filesystem-touching tests” stops being true when the second set arrives.
In a commit message none of that decays, because a commit message is read as
what it is, a record of one change at one moment. git blame on the line in
load_file leads to it, and it is still accurate.
Another, from the commit that made * greedy:
Updates two existing position tests (position_dot_star,
position_digits) that were pinned to the old behavior, and
adds four new tests covering the greedy + back-off cases.
That is chapter 15’s point about tests that agree with the code, recorded at the moment it was discovered: two tests had to change because they asserted the bug. The source cannot say that, since after the commit the tests assert the right thing and there is nothing to see. The commit is the only place the fact can live.
That is the argument in one sentence. A repository’s files describe what is true now, and its history describes how it got that way, and a sentence belongs in whichever one its tense says. Chapter 1’s test: a sentence that names a former state, a rejected alternative, or a date is about a change. The three comments in section 16.3 are in the future tense, which is the same failure pointing the other way, a sentence about a change that has not happened yet. They belonged in the plan.
The subject lines matter separately, because more people read them than read the bodies. In ved’s history they are imperative and specific: Refuse to overwrite a file loaded as non-UTF-8, Take the command letter as a character, not a byte, Record only the nine groups a BRE can address. Chapter 17 uses them as release notes, which is a reason to write them for the person installing the release rather than for the person who wrote the code.
16.6 The plan and the backlog
PLAN.md was the first document in the project, and chapter 1 quoted its
design table and its slice list. Its design table is present tense, a list of
decisions that are still in force. Its slice list is a status board, with each
slice marked done. And below that it accumulated something else: slice-by-slice
notes on where code should go, written before the code existed, such as the
note for l that names line numbers in main.rs where the new arm should be
added.
Those notes were committed until July, when a commit titled stop publishing
local planning notes removed PLAN.md and BACKLOG.md from the repository.
Chapter 1 described that as a decision log published by accident and later
trimmed, and the trimming was right. A note saying where to add code is useful
for the hour before the code is written and misleading forever after, because
the line numbers it cites now point at something else.
The status board had the other problem. It marks slice 8 done, and its
description of slice 8 is long-form command aliases (append, write,
quit, etc.), and write is not implemented. The tutorial’s write notes.txt
was written from the plan. A status board is a claim that something is true of
the code, and like the README’s quick start, nobody checked it.
BACKLOG.md is the other document that lives outside the repository, and it is
chapter 19’s subject: the list of what is not built, and why.
16.7 Seven places, one fact
The help text, the README’s command table, the tutorial, --help, the doc
comments, the plan, and the code each state, in part, what commands ved has.
They disagree. The help omits e, r, and Q. The README’s table has them.
The tutorial teaches three aliases that the code does not have. The plan
says they exist.
The rule that prevents this is to state each fact once and point to it from
everywhere else. For a command reference, that means one source, and chapter
14’s command table is the code version of it. For a README, it means the
command table and the help come from the same list, or the README says type
H in ved for the full reference and does not repeat it. For a tutorial, it
means every session is a captured transcript. For the design and the status,
it means a plan describes intentions and the code describes facts, and when the
two disagree, the code is the one that is right about what is true.
16.8 What the documentation bought
A program that newcomers can learn, which is a large part of why ved exists. The README answers the questions in the order people ask them. The tutorial explains a line editor to someone who has never used one. The doc comments, including the ones the code does not live up to, say what the functions are for. The commit messages are a complete and accurate history of why the program is the way it is.
And the parts that were never run against the program were wrong in ways that
the program’s own output would have shown in a second. The quick start’s byte
counts, the tutorial’s write, the plan’s status, the limitation that was not
a limitation. Documentation is code that nothing compiles. The parts of it that
can be executed should be, and the parts that cannot should be written in the
tense that keeps them true.
Exercise 16-1. Write the documentation test from section 16.2: parse the terminal sessions out of the tutorial’s HTML, run each one through ved, and report every line that differs. Run it against the tutorial and count the failures.
Exercise 16-2. Rewrite the three planning comments from section 16.3 in the
present tense, and the bre.rs header as in that section. Then grep the source
for will, later, yet, and now, and decide for each hit whether it
describes the present.
Exercise 16-3. For each doc comment in main.rs that states a requirement,
write the test that checks it. Count how many of the tests pass the first time.
Exercise 16-4. Rewrite the README’s quick start from a captured session.
Then decide whether the README should keep its command table or point to H,
and what that choice does to the help test from chapter 14.
Exercise 16-5. Read the last twenty commit messages of a project you work on. For each one, decide whether its body says something the diff does not, and whether any sentence in it should have been a comment instead, or the other way round.
17. Release
A release is a version number attached to a commit, and a promise that the
commit can be obtained by someone who is not you. Everything before this
chapter was about the program. This one is about the promise, and about the
machinery that turns git tag v0.2.1 into five binaries, two installers, a
Homebrew formula, two Debian packages, and a crate.
ved has had nine releases:
| Version | Released | What changed, for someone using it |
|---|---|---|
| 0.1.0 | 2026-05-14 | The first release: slices one through eleven |
| 0.1.1 | 2026-05-14 | c, change |
| 0.1.2 | 2026-05-28 | A missing file is a new file; Debian packages |
| 0.1.3 | 2026-06-12 | * is greedy, as POSIX requires |
| 0.1.4 | 2026-06-12 | l, list |
| 0.1.5 | 2026-06-12 | j, m, t, octal escapes, bare s |
| 0.2.0 | 2026-06-25 | Warnings for UTF-16 and UTF-7 files, and the overwrite refusal |
| 0.2.1 | 2026-09-15 | Two panics fixed; continuous integration |
| 0.3.0 | 2026-11-11 | Search addresses; a character-aware engine (chapter 19) |
The dates come from the GitHub releases. The code was finished on April 12, when slices eight through eleven landed in one commit. The first release came a month later, on the day the release machinery was added, and the Debian packages, the first channel beyond GitHub, two weeks after that.
17.1 What the number promises
Cargo versions are semantic versions: MAJOR.MINOR.PATCH, where a change to
the major number means existing users may break, a minor number means new
features, and a patch number means fixes. Before 1.0 the rule shifts one place
to the right. Cargo treats 0.2 and 0.3 as incompatible, the way it treats
1 and 2, and a patch release within 0.2 as compatible.
For a library the promise is about the API, and the compiler can check most of
it. For a program, the API is whatever other programs and people depend on,
and for ved that is a long list: the command language, the flags, the exit
status, what is printed and where, and what is written to disk. A script that
greps ved’s output for deleted depends on the confirmation format. Chapter
14’s proposal to say read 22 bytes from notes.txt instead of 22 is, by
that definition, a breaking change.
ved’s history uses the numbers sensibly. 0.2.0 is the release where the program
first refused to do something it used to do, overwriting a file it had flagged
as non-UTF-8, and it took the minor number. 0.2.1 fixed two crashes and changed
nothing else a user could see, and it took a patch number. 0.3.0 changed what
. matches in a regex, from a byte to a character, which changes the result of
existing commands on non-ASCII text, and it took the minor number.
Three releases in one evening, 0.1.3 to 0.1.5, is the other end of the scale. Each one shipped a feature as soon as it was done. That is cheap when release is automated and expensive when it is not, and the cost is not in the release itself. It is in the channels downstream, each of which has its own update cadence and review, which is chapter 18.
17.2 The manifest, read by strangers
Chapter 1 filled in Cargo.toml’s metadata on the first day and said this
chapter would come back to it:
[package]
name = "ved"
version = "0.2.1"
edition = "2024"
description = "The verbose ed — an ed clone with friendly errors and a built-in help system"
homepage = "https://excelano.com/ved/"
repository = "https://github.com/excelano/ved"
license = "MIT"
keywords = ["ed", "editor", "line-editor", "regex", "bre"]
categories = ["command-line-utilities", "text-editors"]
None of it is needed to build. All of it is read at release. crates.io refuses
a crate without a license or license-file, and without a description.
keywords is limited to five, all of which ved uses, and categories must be
slugs from crates.io’s fixed list. cargo publish --dry-run checks all of that
without uploading, and cargo package --list shows the files that would be
uploaded, which is how to find out that a stray test fixture or a local note is
about to be published.
The description is the sentence most people will ever read about the
program. It appears in cargo search, on the crates.io page, and, through
cargo-deb, in apt show. It is worth writing as carefully as the README’s
first paragraph, and it has the advantage of being shorter.
version is the only field that changes at every release, and the program
reads it at compile time with env!("CARGO_PKG_VERSION"), chapter 2’s
--version. One place holds the number, and every artifact gets it from
there.
17.3 The field that is missing
One field that Cargo.toml does not have is rust-version, the minimum
supported Rust version. Without it, Cargo has no way to tell a user that their
compiler is too old except by failing to compile.
Chapter 1 said edition = "2024" sets the minimum compiler version to 1.85,
and the 0.2.1 README’s build instructions say the same, 1.85+ for edition
2024. Both statements are true of the edition. They are not true
of ved 0.2.1:
$ cargo +1.87.0 build --release
error[E0658]: `let` expressions in this position are unstable
error[E0658]: `let` expressions in this position are unstable
$ cargo +1.88.0 build --release
$ echo $?
0
The two errors are if ... && let chains, which the 2024 edition allows from
Rust 1.88 onward. 0.2.0 builds on 1.87. So does the commit immediately before
the one that added continuous integration. The commit that added it does not,
and the next section explains why. Someone with Rust 1.85, 1.86, or 1.87 who
ran cargo install ved after September got a compile error from code they had
not written, with no indication that the fix was to upgrade. Filed as ved
#28.
Declaring it is one line:
rust-version = "1.88"
With it, Cargo on an older toolchain says that the crate needs 1.88 instead of
showing an error from the middle of main.rs, and newer versions of Cargo use
it to pick a version of a dependency that the toolchain can build. The line is
only useful if it is true, which means checking it: the fleet’s shared CI
workflow takes a toolchain input, so a second job that builds on the declared
version keeps the declaration true. Until it exists, the minimum version is
whatever the last refactor happened to need.
17.4 The gate
Releases 0.1.0 through 0.2.0 were built by a workflow that compiled and packaged the program and ran nothing. The commit that changed that, in August, says so:
Nothing compiled a test between a laptop and a release: cargo-dist builds the
artifacts but runs nothing, so a broken commit could be tagged, published to
crates.io, and promoted to apt behind a green checkmark.
The check that arrived is three commands, in a workflow shared with the
author’s other Rust repositories: cargo fmt --check, cargo clippy with
warnings denied, and cargo test. Sharing it is the decision that keeps it
maintained, since a fix to the workflow reaches every repository at once.
Denying warnings is the decision that keeps it meaningful, and the shared
workflow’s header explains it: a warning nobody has to fix is a warning nobody
fixes.
A check that would have failed on arrival is not a check anyone keeps, so the
commit that added it also made the code pass. Three files were not formatted.
Clippy reported seven warnings, among them collapsible_if, the lint that
chapter 3 predicted would find its three-deep prompt:
if !input_mode {
if let Some(p) = prompt {
if write!(out, "{p}").is_err() || out.flush().is_err() {
return ExitCode::FAILURE;
}
}
}
cargo clippy --fix rewrote it as one condition:
if !input_mode
&& let Some(p) = prompt
&& (write!(out, "{p}").is_err() || out.flush().is_err())
{
return ExitCode::FAILURE;
}
That is clearer, and it is the version in examples/ved. It is also a let
chain, and it is why 0.2.1 needs Rust 1.88. The lint fixed the indentation and
raised the minimum compiler version in the same edit, and nothing reported the
second effect, because CI builds with the current stable compiler, which has
let chains. The cleanup was correct and the release that shipped it broke
cargo install for anyone three versions behind.
The lesson is not to avoid clippy. It is that a gate checks what it runs, and this one runs the newest compiler. An automated fix is a code change like any other, and its effects include the ones the tool does not mention.
17.5 Five targets
ved is built for five platforms. Doing that by hand means five machines, or
cross-compilers and linkers for each, and it is the step most likely to be done
once and never again. ved used cargo-dist for it, configured by one file:
[dist]
cargo-dist-version = "0.31.0"
ci = "github"
installers = ["shell", "powershell", "homebrew"]
tap = "excelano/homebrew-tap"
publish-jobs = ["homebrew"]
targets = ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu",
"x86_64-apple-darwin", "x86_64-unknown-linux-gnu",
"x86_64-pc-windows-msvc"]
hosting = "github"
From that, cargo-dist generated a 343-line GitHub Actions workflow that runs
when a version tag is pushed. It builds each target on a runner of the right
operating system, archives each binary with the README and license, computes
checksums, generates a shell installer and a PowerShell installer that
download the right archive for the machine they run on, writes a Homebrew
formula and pushes it to a tap, and creates the GitHub release with all of it
attached. It also added a profile to Cargo.toml:
[profile.dist]
inherits = "release"
lto = "thin"
Link-time optimization shrinks the Linux binary from 526,744 bytes to 492,032. The release build itself, measured on the machine this was written on, takes 0.54 seconds from clean, which is the preface’s “half a second”.
Chapter 1’s design table says single static binary, no runtime, no shared libraries. On Linux that is not quite what the build produces:
$ ldd target/release/ved
linux-vdso.so.1
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
/lib64/ld-linux-x86-64.so.2
Rust’s standard library links the platform’s C library dynamically on the
-gnu targets, so ved needs glibc and libgcc, which every Linux system with a
package manager has. The Debian package says so, with depends = "libc6, libgcc-s1". A binary with no shared libraries at all comes from the
x86_64-unknown-linux-musl target, which links a C library statically, and
which ved does not build. The design table states what the author wanted. The
.deb metadata states what is true, and it is the one a package manager reads.
17.6 What a release contains
The v0.2.1 release on GitHub has nineteen files:
| File | Bytes |
|---|---|
ved-x86_64-unknown-linux-gnu.tar.xz | 186,796 |
ved-aarch64-unknown-linux-gnu.tar.xz | 171,904 |
ved-x86_64-apple-darwin.tar.xz | 178,832 |
ved-aarch64-apple-darwin.tar.xz | 160,424 |
ved-x86_64-pc-windows-msvc.zip | 164,455 |
a .sha256 for each of those five | |
sha256.sum | 578 |
ved-installer.sh | 53,752 |
ved-installer.ps1 | 21,482 |
ved.rb, the Homebrew formula | 2,354 |
ved_0.2.1-1_amd64.deb | 174,640 |
ved_0.2.1-1_arm64.deb | 154,504 |
source.tar.gz and its checksum | 45,639 |
dist-manifest.json | 18,180 |
The shell installer is more than a quarter the size of the compressed program
it downloads. That is
not a criticism of it; it detects the platform, downloads, verifies, and puts
the binary on the PATH, which is a lot of shell. It is a reminder that the
code around a release is code, with its own bugs, and that it runs on machines
the author has never seen.
The checksums are for integrity, not authenticity. A checksum published on the
same page as the file it describes proves the download was not corrupted. It
does not prove that the page was not changed, since anyone who could replace
the archive could replace the checksum. Authenticity needs a signature made
with a key the attacker does not have, and ved’s releases are not signed. The
Debian packages acquire a signature in chapter 18, from the apt repository’s
key, which is the first point in the chain where someone could tell a real
ved from a substitute.
17.7 The release notes
The body of the v0.2.1 release on GitHub, generated by cargo-dist, is install
instructions and a table of downloads. It does not say what changed.
cargo-dist fills that section from a changelog file, and ved has none. A user
looking at the release page to decide whether to upgrade learns how to install
it and nothing else.
What changed is in the history:
$ git log --reverse v0.2.0..v0.2.1 --format=%s -- src Cargo.toml
docs: state ed compatibility accurately, disclose AI assistance
Run the fleet's Rust CI on every push and PR
Take the command letter as a character, not a byte
Record only the nine groups a BRE can address
Release 0.2.1
The release notes for 0.2.1 are in there, and they are the second through fourth lines, rewritten for someone who does not know what a command letter is: a non-ASCII character typed as a command no longer crashes ved, and a pattern with more than nine groups no longer crashes ved. The first line is about the README, the second is about CI, and the last is the release itself. Twenty-three other commits between the two tags touched only workflows and documentation.
This is why chapter 16 said subject lines should be written for the person
installing the release. The history is the only complete record of what
changed, and the notes have to be made from it, by hand or by a tool. A tool
can only do it if the subjects say which kind of change each one is. The
convention ved’s later history adopted is Conventional Commits, a type before
the subject, fix: and feat: for changes a user would notice and docs:,
ci:, build:, and chore: for everything else. With it, the release notes
are the fix: and feat: subjects since the last tag, and the rest stay out.
The tool that produced 0.3.0’s release notes worked that way, and most of the
subjects since 0.2.1 had no type. The few that did, docs:, build:, and
chore:, were left out. The rest could not be sorted, so all of them went in,
and Support /pattern/ and ?pattern? search addresses sits in the same list as
Dependabot merges move to the organisation’s sweep, in no order a user would
choose.
17.8 A tag is spent
A pushed tag can be deleted and pushed again, and Git will allow it. Nothing
downstream will. crates.io never accepts the same version twice, and yanking a
version only stops new projects from selecting it; the number stays used. A
.deb with a version that is already in an apt repository is refused or, worse,
replaces the old one under the same name for some users and not others. A
WinGet manifest for a version that has been submitted is a duplicate.
So a release is irreversible, in practice, once any channel has it, and the
response to a bad release is the next patch number. That changes how the steps
before the tag should be treated. Everything that can be checked should be
checked before the tag is pushed, because after it the only fix is another
release: the tests, cargo publish --dry-run, a build of each package, and,
for ved, the check that RELEASING.md named as the real risk:
**ved is a clone of `ed`, so compatibility is the release risk.** The tests
cover the command grammar, but the thing that breaks quietly is a real `ed`
script behaving differently under ved.
That is chapter 15’s differential harness, stated as a release step before the harness existed.
17.9 The order of operations
At 0.2.1 a release went like this. Bump version in Cargo.toml and commit.
Tag the commit and push the tag. The tag starts two workflows at once: the
cargo-dist release, which builds and creates the GitHub release, and
publish-crate.yml, which runs cargo publish if a crates.io token is
available and skips cleanly if not. Then dispatch the Debian package workflow by
hand, for a reason its comment records:
# cargo-dist creates the release with the default GITHUB_TOKEN and GitHub fires
# no `release: published` for a token-created release, so this is dispatched by
# hand after one:
#
# gh workflow run deb.yml -f tag=v0.2.1
GitHub does not let events caused by a workflow’s own token start other
workflows, to prevent loops, so a workflow triggered by “a release was
published” never fires for a release another workflow published. The
workflow_dispatch trigger is the escape hatch, and the manual step is the
cost. Then promote the .deb files into the apt repository, and submit the
WinGet manifest. Those two are chapter 18.
Every step after the tag has a different owner: GitHub’s runners, crates.io,
the apt repository, Microsoft’s package repository. A release is a sequence of
handoffs, and the procedure is the list of them in order with what to check at
each one. ved’s RELEASING.md held the parts specific to ved and pointed to a
shared document for the rest, and chapter 19 is about what happened when that
procedure moved out of the repository entirely.
17.10 What release bought
A program that anyone can install on five platforms without a Rust toolchain, in a form that identifies its version, from a page that lists every file and its checksum. The mechanism is a tag, a manifest that was correct from the first day, and a generated workflow.
It also put the program in front of people whose machines are not the author’s, and that is when the gaps between what the project says and what it does start to cost something. The minimum Rust version was whatever the last cleanup needed. The binary was not as static as the design said. The release page did not say what had changed. Each of those is a fact a user needed and could not get, and each is one line in a file, written down once.
Exercise 17-1. Add rust-version to examples/ved/Cargo.toml. Install the
toolchain it names with rustup toolchain install, build with it, and then
find the oldest toolchain that builds examples/ch05-write. Explain the
difference.
Exercise 17-2. Build ved for x86_64-unknown-linux-musl, check it with
ldd, and compare its size with the -gnu build. Decide which one the
Debian package should contain, and why it is not obvious.
Exercise 17-3. Write the release notes for every release from 0.1.0 to 0.2.1 from the history alone, one sentence per user-visible change, written for someone who has never seen the code. Then write the rule that would let a tool produce your list.
Exercise 17-4. Run cargo package --list in examples/ved and in the
workspace root. Decide what should not be in each, and add the include or
exclude field that keeps it out.
Exercise 17-5. Write the pre-tag checklist for a program you maintain: the checks that can still be fixed before the version number is spent. For each one, decide whether a machine can run it, and if so, why it is on a list instead of in CI.
18. Packaging
A release is a set of files on GitHub. Almost nobody installs software by downloading a file from GitHub. They type a command into a package manager they already have, and they expect the same package manager to tell them when there is a new version. Packaging is the work of putting a release into the shapes those programs expect, and then putting it there again for every release after.
At 0.2.1, ved’s README lists seven ways to install it:
| Channel | The user types | Built by | First version |
|---|---|---|---|
| Debian and Ubuntu | sudo apt install ved | cargo-deb, in CI | 0.1.2 |
| Homebrew | brew install ved | cargo-dist | 0.2.0 |
| curl installer | curl ... install.sh | sh | cargo-dist | 0.1.0 |
| WinGet | winget install Excelano.ved | cargo-dist, then a manifest | 0.1.5 |
| PowerShell installer | irm ... | iex | cargo-dist | 0.1.0 |
| crates.io | cargo install ved | the user’s own compiler | 0.2.0 |
| Source | make build && sudo make install | the user’s own compiler | 0.1.0 |
Each row is a separate product with its own users, its own update mechanism, its own failure modes, and its own copy of what ved is called and what it does. This chapter goes through them in order of how much they ask of the person installing, from most to least, and ends with what having seven of them cost.
18.1 From source
PREFIX ?= /usr/local
.PHONY: build install uninstall clean test
build:
cargo build --release
test:
cargo test
install:
@test -f target/release/ved || { echo "Run 'make build' first."; exit 1; }
install -d $(PREFIX)/bin
install -m 755 target/release/ved $(PREFIX)/bin/ved
uninstall:
rm -f $(PREFIX)/bin/ved
clean:
cargo clean
A Makefile for a Rust program looks redundant, since cargo build does the
building. It is there for the other half: sudo make install is what a Unix
user expects to type to put a program in /usr/local/bin, and PREFIX=/usr
is what a distribution packager expects to be able to pass.
The install target does not build. The first version did, and it failed on
the first machine it was tried on, for a reason its fix records: sudo make
install was failing because root doesn’t have cargo in its PATH. Cargo is
installed per user, under ~/.cargo, and sudo runs as root with root’s
environment. Separating the two targets means building as yourself and copying
as root, which is also the safer arrangement, because a build runs code from
the crate and its build scripts and should not run with privileges it does
not need. The guard line refuses to install a binary that has not been built
rather than letting install fail with a less useful message.
18.2 crates.io
cargo install ved downloads the source of the latest version from crates.io,
compiles it on the user’s machine, and puts the binary in ~/.cargo/bin. It
is the easiest channel to publish to, since a release is cargo publish, and
the most demanding to install from, since it needs a working Rust toolchain of
the right version. Chapter 17’s missing rust-version is a bug in this
channel and no other: every other channel ships a binary someone else
compiled.
What is uploaded is the crate’s source, as cargo package assembles it, and
the version on crates.io is permanent. ved’s first crates.io version is 0.2.0;
the six releases before it never went there. That is visible on the crate’s
page and is a fair summary of how channels arrive in a project: one at a time,
each when somebody asked for it.
18.3 Piping a script into a shell
curl -fsSL https://raw.githubusercontent.com/excelano/ved/main/install.sh | sh
The curl installer is the channel with the least friction for a user who has no package manager configured, and the most trust. The script runs with the user’s permissions, it is fetched at the moment it is run, and the user has not read it. Everything a package manager does to establish that a package is what it claims to be, the signed index, the pinned key, the recorded checksum, is replaced by trusting the server and the TLS connection to it.
ved’s install.sh is one command that fetches and runs a second script, the
installer cargo-dist generates for each release, which detects the platform,
downloads the right archive, checks its checksum against the one published
beside it, and installs to ~/.cargo/bin. The shim exists so that installing
and uninstalling have the same shape of URL, and uninstall.sh removes the
binary from where the installer put it.
The history of that shim is short and has four entries. It was added on the day of the first release. It was removed the same day, by a commit whose message says per-language idiom wins over cross-portfolio URL symmetry. It was restored six weeks later to match the author’s other projects. And it was retired just after 0.2.1, with the message one less thing to maintain. Four commits, two positions, each defensible, and none of them informed by how many people used it, because nothing measured that. A channel is cheap to add and its cost is ongoing, and without a way to tell whether anyone uses it, the decision to keep it is a matter of taste that can be re-argued indefinitely.
18.4 Homebrew
class Ved < Formula
desc "The verbose ed — an ed clone with friendly errors and a built-in help system"
homepage "https://excelano.com/ved/"
version "0.2.1"
if OS.mac?
if Hardware::CPU.arm?
url "https://github.com/excelano/ved/releases/download/v0.2.1/ved-aarch64-apple-darwin.tar.xz"
sha256 "4297e83fd811e228e64ab85e2f0c564d369408dd63fc56c30ba8cee5c9277a64"
end
# ... Intel macOS, then ARM and Intel Linux ...
end
license "MIT"
# ...
def install
# ...
bin.install "ved"
end
end
A Homebrew formula is a Ruby class that says where to get a program and how to
install it. Homebrew’s own formulae usually build from source, or install a
prebuilt “bottle” that Homebrew’s servers built. This one does neither: it
points straight at the release archives on GitHub and checks each against a
SHA-256 written into the formula. cargo-dist generates it at release and
pushes it to a tap, excelano/homebrew-tap, which is a Git repository of
formulae that users add with brew tap.
The checksum in the formula is the first point in this chapter where a
checksum means something. Chapter 17 said a checksum published beside its file
proves only that the download was not corrupted. This one is in a different
repository, committed when the release was made, so replacing the archive on
GitHub without also changing the tap makes brew install fail. That is not a
signature, since whoever controls both repositories can change both, but it
moves the trust from “whoever can upload a release asset” to “whoever can push
to the tap”.
18.5 Debian packages and an apt repository
A .deb is an archive of files with their destinations, plus a control file
that tells dpkg what the package is called, what version it is, and what it
needs. cargo-deb builds one from Cargo.toml, using the package metadata and
a section of its own:
[package.metadata.deb]
maintainer = "..."
extended-description = """
ved is a verbose clone of ed, the original Unix line editor, written in
pure-stdlib Rust. ..."""
section = "editors"
priority = "optional"
depends = "libc6, libgcc-s1"
assets = [
["target/release/ved", "usr/bin/", "755"],
["README.md", "usr/share/doc/ved/README.md", "644"],
["LICENSE", "usr/share/doc/ved/copyright", "644"],
]
and the result is three files:
$ dpkg-deb -c ved_0.2.1-1_amd64.deb
./usr/share/doc/ved/copyright
./usr/share/doc/ved/README.md
./usr/bin/ved
depends is chapter 17’s ldd output written down, and it is correct. The
version has a -1 after it, the Debian revision, which counts packagings of
the same upstream version and is what lets a packaging fix ship without
pretending the program changed.
Two things a Debian user expects are missing. There is no manual page. Debian’s
policy is that every program in /usr/bin has one, and a user who types man ved after installing is told there is no entry, while man ed works. The
README is in /usr/share/doc/ved, which is where Debian puts documentation and
where almost nobody looks. And copyright is the MIT license text, which is
what the file must contain at minimum, rather than the machine-readable format
Debian’s own packages use. Neither is an error for a third-party repository.
The first is a gap in the program’s documentation, of the kind chapter 16
counted: the README, the tutorial, the help, and --help are four places that
describe ved, and the one place Unix users look is the one that is empty.
The .deb files are attached to the GitHub release, and a user could download
and dpkg -i one. That is not what makes them useful. What makes them useful is
an apt repository: a directory served over HTTPS containing the packages and an
index of them, with the index signed. A user adds it once:
curl -fsSL https://excelano.com/apt/setup.sh | sudo sh
and the script does three things: fetches the repository’s public key into
/usr/share/keyrings/excelano-archive-keyring.gpg, writes a source line that
names that key,
deb [signed-by=/usr/share/keyrings/excelano-archive-keyring.gpg] https://excelano.com/apt stable main
and runs apt-get update. From then on sudo apt install ved works, and apt upgrade brings each new version without the user doing anything.
This is the point in the chain where authenticity arrives. apt refuses an index
whose signature does not verify against the key, and every package’s checksum
is in the signed index, so a substituted ved fails to install unless the
attacker also has the private key. The signed-by option limits the key to
this one source, so the Excelano key cannot vouch for packages that claim to
come from Debian, which is the reason that form replaced the older global
apt-key mechanism. The weak point is the first step: the key itself arrives
over HTTPS by curl | sudo sh, so the user is trusting the server once, at
setup, and the signature from then on.
The repository keeps the current version of each package and the one before
it, so a bad release can be rolled back with apt install ved=<version>.
That is the apt answer to chapter 17’s spent tags: the version number cannot be
reused, but the previous one is still there to go back to.
18.6 WinGet
WinGet is Windows’ package manager, and its packages are manifests in a single
public Git repository, microsoft/winget-pkgs. Publishing a version means
opening a pull request that adds three YAML files under
manifests/e/Excelano/ved/0.2.1/. The installer manifest says where the
program is and how to install it:
PackageIdentifier: Excelano.ved
PackageVersion: 0.2.1
InstallerType: zip
NestedInstallerType: portable
NestedInstallerFiles:
- RelativeFilePath: ved.exe
PortableCommandAlias: ved
ReleaseDate: 2026-09-15
Installers:
- Architecture: x64
InstallerUrl: https://github.com/excelano/ved/releases/download/v0.2.1/ved-x86_64-pc-windows-msvc.zip
InstallerSha256: 77B0DB94E95349E05097A7853B56947E20E2C0E67B96F9AD0EE124DCCD71253F
A portable package is an executable with no installer of its own. WinGet
unpacks the zip, puts ved.exe where it keeps portable programs, and adds the
alias ved to the user’s path. The checksum is in the manifest, which is in
Microsoft’s repository, so it is the Homebrew arrangement again, with a third
party holding the copy.
The pull request is reviewed by automation before a person sees it: the
installer is downloaded, scanned, and installed in a sandbox, and the program
is run. That pipeline is the part of this channel the author does not control,
and ved’s history has two traces of it. A workflow was added to scan the
release with Microsoft Defender before submitting, so that a rejection could be
predicted, and was deleted a month later with the message the scan never
predicted winget’s validation. And RELEASING.md recorded that WinGet’s
validation reports an executable error for ved by design, with a recipe for
getting past it, and an instruction not to change the program to avoid it. Both
are what a channel with a gatekeeper looks like from the outside: a check that
cannot be run locally, and a list of things learned about it the hard way.
The second manifest, the locale file, holds the descriptive text, and it has a problem that is not WinGet’s:
PackageName: ved
ShortDescription: The verbose ed, a drop-in ed clone with friendly errors and a built-in help system
A drop-in ed clone. Chapter 16 told how the README’s claim of strict drop-in compatibility was corrected to close compatibility so most scripts written for real ed run against ved unchanged, in July. The WinGet manifests for 0.1.5, 0.2.0, 0.2.1, and 0.3.0 all say drop-in, because the description was written into the manifest when the package was first submitted and has been carried forward with every version since. The correction reached the README, the crate description, and the Debian package. It did not reach the channel whose metadata lives in somebody else’s repository. Filed as ved #30.
The same locale file’s ReleaseNotes field is the body of the GitHub release,
which chapter 17 found was install instructions, so winget show Excelano.ved
tells a Windows user how to install ved with curl | sh and Homebrew.
18.7 Six descriptions
Count the places ved’s one-sentence description lives at 0.2.1. There are six.
Cargo.toml’s description, which crates.io shows. The extended-description
in the same file, which apt show shows. The Homebrew formula’s desc,
generated from Cargo.toml at each release. The WinGet locale manifest’s
ShortDescription, copied forward by hand. The README’s first paragraph. The
tutorial’s first paragraph.
Three of those are Cargo.toml or generated from it, and stay in step with it.
The rest are copies, and a copy is correct until the original changes. Chapter
16’s rule, state each fact once, applies to packaging with more force than to
documentation, because the copies are in places the author does not see every
day, and some of them are in repositories the author does not own. The repair
is to generate every channel’s metadata from one source at release time, the
way the Homebrew formula already is, so that changing the description in
Cargo.toml changes it everywhere at the next release.
18.8 What a channel costs
Each row of the table at the top of this chapter is, at every release: an artifact to build, a step to run, a credential that can expire, a reviewer or a validation that can reject it, and a set of users who expect the new version to arrive. The work is not in setting a channel up, which is an afternoon. It is in the nine releases after.
At 0.2.1, ved paid that for seven channels and five platforms, and it had no
measure of which were used. The next chapter is about what happened when the
cost was counted: by 0.3.0, the curl installer, the Homebrew formula, the macOS
builds, and cargo-dist itself were gone, and each removal is a commit with a
one-line reason. The general lesson is to add a channel when someone needs it,
to know how you would tell whether they still do, and to treat removing one as
a normal release decision rather than a failure.
18.9 What packaging bought
A program that installs with the command its users already know, on Debian, Ubuntu, macOS, and Windows, and that updates with the command they already run. A signed path from the build to the user’s disk, for the users of the apt repository. And on every channel, a copy of the program’s name, its description, and its promises, held by a system that does not know when the original changes.
Exercise 18-1. Write a manual page for ved in man(7) format, add it to
the .deb assets so it installs as /usr/share/man/man1/ved.1.gz, and check
it with man -l. Then decide what should be in it that is not in H, and what
should be in H that is not in it.
Exercise 18-2. Build the .deb with cargo deb and run lintian on it.
Sort what it reports into what a third-party repository should fix and what it
can ignore, and say why for each.
Exercise 18-3. Generate the WinGet locale manifest from Cargo.toml with a
script, so that the description cannot drift. Decide which fields come from
Cargo.toml, which from the release, and which are written once by hand.
Exercise 18-4. Write the Makefile’s install target again so that it also
installs the manual page from exercise 18-1, and an uninstall that removes
both. Check that make install PREFIX=/tmp/ved-test works without sudo.
Exercise 18-5. Pick a program you maintain and list its channels. For each, write down how you would find out how many people installed from it last month. If you cannot, decide whether that is a reason to remove it.
19. Living With It
0.2.1 shipped on September 15. 0.3.0 shipped on November 11. Between them the program gained a feature the plan had promised since slice three, its regex engine was rewritten to work in characters, its test suite grew by half, and its release machinery, three of its seven install channels, and its macOS builds were removed. None of that was planned at 0.2.1. All of it is what happens to a program after people can install it.
The code is examples/ch19-living, which is ved 0.3.0. Every earlier chapter
described 0.2.1, which is examples/ved. This chapter is about the difference,
and about the documents that decide what a program becomes once the plan that
built it has run out: the issue tracker, the backlog, and the list of what the
program will not do.
19.1 Where the findings went
Four of ved’s issues were opened on the same day:
| Issue | Opened | Closed | Title |
|---|---|---|---|
| #7 | 2026-09-14 | 2026-09-27 | Support /pattern/ and ?pattern? search addresses |
| #8 | 2026-09-14 | 2026-09-15 | Panic on non-ASCII command character loses the buffer |
| #9 | 2026-09-14 | 2026-09-15 | Panic on a pattern with ten or more capturing groups |
| #10 | 2026-09-14 | 2026-09-27 | Byte-oriented regex corrupts multi-byte UTF-8 on substitute |
September 14 is the day chapters 1 through 9 of this book were written, and each of those issues is a finding from one of them: chapter 4’s search addresses, chapter 5’s panic, chapter 9’s tenth group, and chapter 9’s corruption. The two panics were fixed the next day and shipped as 0.2.1, which is why chapters 5 and 9 could say the bugs they found lasted until the chapter was written. The other two took two weeks and shipped in 0.3.0.
Writing about a program in detail is a code review with a reader in mind, and it finds what code review finds: the places where the code and the account of it disagree. The useful habit is the one visible in the dates. A finding that goes into the tracker the day it is made is a finding that gets fixed. A finding left in prose is a paragraph.
19.2 The interim fix, then the real one
Chapter 9 found that s/f./Z/ on café destroyed the é without a word, and
suggested two fixes: a cheap one that refuses any substitution whose match
boundaries fall inside a character, and an expensive one that teaches the
engine to work in characters. Exercise 9-2 asked for the cheap one. 0.3.0 did
both, a day apart.
The first commit, on September 26, is titled Refuse a substitution that splits
a multi-byte UTF-8 character. It checks the match boundaries against
str::is_char_boundary and returns an error instead of a damaged line. It
converts silent corruption into a refusal, which is the property chapter 9 said
an editor most needs, and with its tests it is under a hundred lines.
The second, the next day, is Make the BRE engine character-aware, not
byte-oriented, and its message is a small case study in why the cheap fix came
first. Making . and bracket expressions consume a whole character was the
obvious change, and it was not enough:
That alone isn't sufficient: Regex::find's unanchored search tried
every byte offset, so a failed attempt starting at a real character
boundary could still fall through to trying the bytes inside that
character as further starting offsets, with Dot's byte fallback
happily accepting one — reopening the exact bug one level up, in the
search loop instead of a single atom.
The same gap was in substitute_all’s empty-match step, chapter 10’s loop,
which advanced by one byte. With all three fixed, the commit says, a
substitution can no longer produce a byte range that splits a character, so
the boundary check added in #10 as an interim safety net is now unreachable
and comes out. The line chapter 10 showed in run_substitute became
String::from_utf8(new_bytes).expect(...), an assertion that the invariant
holds rather than a repair for when it does not.
The order is the lesson. The interim fix stopped the data loss with a change
small enough to be obviously correct, and it made the real fix safe to attempt,
because a mistake in the rewrite would now produce an error rather than a
corrupted file. The real fix then deleted the interim one, which is how an
interim fix is supposed to end. The $ corruption from chapter 10, a
substitution that appended a stray character, disappeared in the same commit,
because the loop now pushes the character at the match instead of the byte at
the old position.
19.3 Sixty tests
0.3.0 has 185 tests, against 125. Sorted by what they exercise:
| Area | Tests added |
|---|---|
parse_args | 8 |
Commands through dispatch: w, r, e, d, g, v, H, Q, and the setup for a, i, c | 29 |
| Search addresses | 9 |
| Character-aware matching and substitution | 14 |
Chapter 15 found that parse_args and half the commands had no tests at all,
and 0.3.0 closed most of that gap. The character tests are the best in the
suite: names like four_dots_span_cafe_but_five_do_not and
class_member_match_is_whole_sequence_not_shared_lead_byte state a fact about
the specification, and each one tests behavior that 0.2.1 got wrong.
Most of the others assert what the program already did. That is chapter 15’s pattern, and two of the names show it:
fn edit_of_a_missing_file_wipes_the_buffer_as_a_new_file() {
fn write_refuses_to_overwrite_a_non_utf8_source() {
The first makes e discarding the buffer a tested property, in a release where
e still discards a modified buffer with no warning, which chapter 13 found.
The second holds in place the guard that chapter 13 showed blocks only false
positives. Both are accurate descriptions of the code, and both will have to be
changed by whoever fixes the behavior they describe. A test written by running
the code protects the code’s behavior, including the behavior that is a bug,
and that is a real cost of a suite that grows this way.
Run against GNU ed with chapter 15’s harness and the same three thousand
single-command scripts, 0.3.0 leaves a different file in 439 cases, against
516 for 0.2.1. The 77 that went away are the s/$/!/g row, the corruption the
character rewrite fixed. Every other row in chapter 15’s table is unchanged.
19.4 The list the book adds
Chapters 10 through 18 were written after 0.3.0 shipped, so their findings are
not in the tracker yet. They are in the position chapter 9’s were in on
September 14: written down, not yet filed. There are eighteen of them, from a
file named q to a tutorial that teaches a command ved does not have, and
eleven of the code bugs among them were in 0.1.0. Chapter 20 is about what
they are, chapter 21 about fixing them, and chapter 22 about the release that
ships the fixes. The rest of this chapter is about the documents that sit
beside the tracker.
19.5 The backlog
The other document that decides what a program becomes is the list of things
it does not do. ved’s is BACKLOG.md, kept outside the repository since the
commit chapter 16 described, and it is organized by why each item is not done
rather than by when it will be:
## Queued
## High-impact, unscheduled
## Smaller / conditional
## Gated on the pure-stdlib posture
## Rejected by project identity
That structure is the best idea in the file. “Not done” covers several different states, and a list that does not distinguish them invites the same argument about each item every time it is read. Queued means someone has decided to do it. Unscheduled means it is wanted and nothing has made it urgent. Gated means it would happen if a constraint changed. Rejected means it will not happen while the program is what it is, and saying so in writing is what stops it being re-proposed.
Chapter 4 said search addresses sat at the top of this file, and they did, with a note about what they would cost:
### Search addresses — `/pattern/`, `?pattern?`
The highest-remaining-impact item. The address parser handles line numbers, `.`,
`$`, and offsets, but not regex search. Adding it connects the existing BRE
engine (`src/bre.rs`) to the address resolver. If the pure-stdlib gate is ever
bent, this is the most likely reason.
Search addresses shipped in 0.3.0 with no dependency at all. The engine was
already in the program, and connecting it to the address resolver was about
eighty lines in address.rs. The entry’s prediction about the gate was wrong,
and it had been wrong since the engine existed. The item was waiting on nothing
except being picked up, and the note implied it was waiting on a decision. The
backlog still lists it, under a status line dated July.
That is two lessons about a file whose purpose is to be read later. The reason an item is not done is the part that decides whether anyone does it, so the reason has to be checked as carefully as the item. And a backlog is a list of what is not done, so a done item is deleted from it, in the commit that does it, rather than left for a status line to qualify.
Chapter 8 said the backlog recorded its non-failing compiler, the regex
compiler that accepts [abc without an error, as a debt. It does not. Neither
does the file mention chapter 8’s Star(Atom) limitation except as \(...\)*
under smaller, or chapter 9’s step limit for pathological patterns. Those
are the entries this chapter would add to it.
19.6 Undo
Chapter 11 said this chapter would say why ved has no u. The backlog lists it
under high-impact, unscheduled, and the author’s separate list of
limitations files it with Ctrl-C handling as waiting on the same deps gate.
The second of those is wrong. Chapter 11 showed that every change to the buffer
goes through three methods, and that a single-level undo is a snapshot of
lines and current taken before each command that changes them, which is a
dozen lines of standard library code. There is no gate. The first is right, and
it is the same answer chapters 6 and 9 gave for their unfinished work: nothing
has forced it.
The two documents disagreeing about the same item is a small instance of chapter 16’s rule. A fact about the program that is stated in two places will eventually be stated two ways, and the one filed behind a gate is the one less likely to be picked up.
19.7 What the constraint cost
The preface said chapter 1 explains why ved has no dependencies and this chapter explains the two features that has cost. They are both in the backlog, and they are the two items that a dependency would make possible and the standard library does not.
Ctrl-C. Traditional ed catches the interrupt signal and uses it to abandon
what is being typed: Ctrl-C in input mode discards the partial text and returns
to command mode. ved has no signal handler, so Ctrl-C kills the process and
takes the buffer with it, which is the opposite of the protection the
double-q gives. Rust’s standard library has no portable way to install a
signal handler. The options are a crate, libc through FFI, or hand-written
extern "C" declarations per platform. The backlog files it under gated: it
would go through the day the constraint did.
An editable input block. A proposal to let the user move a cursor within
the lines being typed in input mode, editing them before the terminating .,
needed raw terminal mode, an escape-sequence parser, and window-size handling,
none of which the standard library has. This one is filed under rejected, and
the reason is not the dependency alone: it would change what ved is, from a
line editor to something on the way to a screen editor. The idea was built
instead as a separate program, nved, written in Go, where it is the point.
Those are the two features. The costs paid along the way were smaller and are
scattered through the book: the encoding sniffer duplicated from a crate the
author already maintained (chapter 13), the argument parser that does not
understand -- (chapter 13), the benchmark done with Instant (chapter 15),
and a regex engine that took three chapters and backtracks exponentially, which
the regex crate would not, at the price of having no backreferences.
What it bought is in the same chapters. A release build in half a second, a
binary with no supply chain beyond the compiler, a Cargo.lock with one
package in it, and, for anyone packaging the program for a distribution, one
source package with nothing else to package first. And it bought the book:
every line of ved can be read, including the parts that would otherwise have
been someone else’s crate, which is why chapters 7 through 9 could be written
at all.
The general version is the one chapter 1 gave. A constraint is worth having
when it answers questions in advance, and ved’s answered these four cleanly:
inline the sniffer, park Ctrl-C, build nved, write the engine. It cost two
features that a user would notice, and it was chosen with that cost visible.
19.8 The procedure leaves the repository
At 0.2.1, ved’s repository held its release procedure: RELEASING.md, the
cargo-dist workflow, the crates.io and Debian workflows, a parameter file for
the tools that ran them. At 0.3.0 it holds a CI workflow that runs by hand and
a small file naming what to build, which is not committed. The rest moved into
release tools shared by the author’s projects and run from the author’s own
machines.
The commit that deleted RELEASING.md gives the reason in two sentences:
A document beside the tool is what a session on the Mac or the Windows
machine reads instead of running it, and what drifts from it.
That is chapter 16’s argument applied to procedure. A document describing how to release is a second copy of the procedure, and the copy is what someone reads at the moment it matters, and it drifts. Make the procedure a program, and the program is the only copy.
The trade is real in both directions. One procedure for every project means a correction reaches all of them, and a release does not depend on remembering what this repository’s notes said. It also means the repository no longer says how it is released, so a contributor who is not the author cannot cut one, and a reader of the repository cannot learn from it what chapter 17 described. For a project with one maintainer and a dozen siblings, the first side wins. For a project that hopes for a second maintainer, it is a cost to count.
Continuous integration changed the same way. The workflow that chapter 17 described running on every push now runs when it is started by hand, before a release or after a change worth checking. A check that runs on every push and is red for reasons nobody fixes stops being read, and its author decided that a check run deliberately and read every time was more useful than one run constantly and ignored. The cost is that a broken commit is no longer flagged the moment it is pushed, and the release is the backstop.
19.9 The channels, counted
Chapter 18 ended by saying the cost of seven channels had not been counted at 0.2.1. By 0.3.0 it had:
| Channel or artifact | Removed | Commit subject |
|---|---|---|
| curl installer | 2026-09-15 | Retire the curl installer: apt, Homebrew, winget and cargo are the paths |
| Defender scan before WinGet | 2026-09-15 | Delete the Defender scan caller: the scan never predicted winget’s validation |
| Homebrew formula | 2026-11-11 | build: stop publishing a Homebrew formula |
macOS builds, cargo-dist | 2026-11-11 | build: release without cargo-dist or macOS builds |
The 0.3.0 README lists four ways to install: Debian and Ubuntu, Windows, Cargo,
and building from source. The release builds for x86-64 and ARM Linux and for
x86-64 Windows, and the release page carries two .deb files and a Windows
zip.
Each removal has a one-line reason, and the reasons share a shape: the channel
cost something at every release and returned less than it cost. The curl
installer duplicated what the package managers did. The Defender scan did not
predict what it was meant to predict. The Homebrew formula pointed at macOS
archives, and the macOS archives, the PowerShell installer, and the Linux
tarballs went with cargo-dist.
Removing a channel has a cost the commits do not state, and it falls on the
people who used it. The Homebrew tap now holds only a README. A user who
installed ved 0.2.1 with brew install keeps 0.2.1, and brew upgrade has no
newer version to offer them and no way to say why. A macOS user who installed
from the release archives finds no macOS archive for 0.3.0. Neither was told,
because the channels have no way to reach their users except by delivering an
update, and the update is what stopped. Filed as ved
#31.
That is the reason chapter 18 said to know how you would measure a channel
before adding it, and the remedy for a project that did not is modest: when a
channel ends, say so in the place its users will look. A last release on that
channel whose notes say where to go next, or a line in the README’s install
section saying the channel was retired and naming its replacement. cargo install ved works on macOS, and a sentence saying so would have reached the
people the removal affected.
19.10 What living with it bought
A program that is better than it was when it shipped, in the ways a user notices: search addresses, a regex engine that respects characters, and two fewer crashes. A test suite half again as large. A release procedure that is the same for every project its author maintains. And a set of channels that matches what the author can support.
ved 0.3.0 is in use, and it has a list of findings this book produced, a backlog with a structure to copy and entries to recheck, and a constraint that has cost two features and paid for them. The work of a program after its first release is a loop: someone reads it closely, writes down what is wrong, and the list goes into the place where lists get done. The next three chapters go around it once.
Exercise 19-1. Before reading chapter 20, turn the findings of chapters 10
through 18 into issues of your own, one per finding, each with a session that
reproduces it against examples/ch19-living and the output GNU ed gives. Then
order them, write down the rule you used, and compare your list with section
20.1.
Exercise 19-2. Rewrite ved’s backlog for 0.3.0: delete what shipped, add what chapters 8 through 18 found, and check the stated reason on every item that remains. Count how many reasons changed.
Exercise 19-3. Implement Ctrl-C in input mode for Linux only, with
extern "C" declarations for signal and an AtomicBool, and no crate.
Measure what it cost in lines and in unsafe blocks, and decide whether the
constraint should bend for it.
Exercise 19-4. Write the README paragraph that tells a Homebrew user what happened to ved’s formula and how to keep getting updates. Then decide where else it needs to appear for that user to see it.
Exercise 19-5. Pick a program you shipped more than six months ago. List what changed since, sorted the way section 19.9 sorts removals: what it cost each release, what it returned, and who was told when it stopped.
20. Bugs
Chapter 19 ended with a list of findings and the claim that they belong in a tracker. This chapter is about what was on the list: what the bugs were, how long they had been there, what caused them, how they were found, and how to tell a bug from a difference that is meant. Chapter 21 fixes them and chapter 22 ships the fixes.
The program in this chapter is still 0.3.0, examples/ch19-living. Every
session below was run against it.
20.1 The list
On November 21, the day the first draft of this book was finished, each finding from chapters 10 through 19 went into ved’s tracker as its own issue, with a session that reproduces it and the reference output it should match. Five more were filed the same day, while the fixes were being made: two from reading the POSIX specification of ed, two found by the differential harness, and one for what the harness found that nobody had explained yet. One more was found while this chapter was being written, which section 20.6 is about.
| Issue | Finding | Found in |
|---|---|---|
| #14 | wq writes a file named q and does not quit | ch. 14 |
| #15 | write, edit, and read act on files named rite, dit, ead | ch. 14 |
| #16 | The tutorial teaches write notes.txt | ch. 16 |
| #17 | e discards a modified buffer, and a failed e empties it | ch. 13 |
| #18 | CRLF line endings are rewritten as LF | ch. 13 |
| #19 | g marks numbers, not lines | ch. 12 |
| #20 | 0a and 5a append after the current line | ch. 11 |
| #21 | An escaped delimiter becomes a metacharacter | ch. 10 |
| #22 | ^ matches again under g; an empty match after a real one is replaced | ch. 10 |
| #23 | s/a/b without its closing delimiter is an error | ch. 10 |
| #24 | A count or unknown suffix after s is ignored | ch. 10 |
| #25 | A UTF-8 file containing +ACI- cannot be saved in place | ch. 13 |
| #26 | Exit status 0 after an error | ch. 14 |
| #27 | No -s, and confirmations mixed into a script’s output | ch. 14 |
| #28 | No declared minimum Rust version | ch. 17 |
| #29 | The help omits e, r, and Q, and misstates three defaults | ch. 14 |
| #30 | The WinGet manifest still says drop-in | ch. 18 |
| #31 | Nothing tells a macOS user what happened to their channel | ch. 19 |
| #32 | A replacement of % alone is not the previous replacement | POSIX |
| #33 | End of input on a modified buffer quits without a warning | POSIX |
| #34 | The current line after g/re/d is wrong | harness |
| #35 | j with one address moves the current line | harness |
| #36 | The differences the harness still finds | harness |
| #38 | l writes a tab as \011 instead of \t | ch. 14, again in ch. 20 |
Every issue in ved’s tracker was opened by its author. No user has reported a
bug. That does not mean no user hit one. It
means that a user who saves a file with wq and finds it unchanged, or opens
a Windows file and saves it back with different line endings, has no reason to
think the editor is wrong, and less reason to go and say so.
20.2 How long they shipped
Each issue has a reproduction, so each can be run against every release. The
script that does it is tools/bugs-by-release.sh: for each issue it runs the
session against one binary and prints BUG if the binary still behaves the
way the issue describes. Every tagged release from 0.1.0 to 0.3.0 was built
from its tag and checked:
| Issue | 0.1.0 | 0.1.5 | 0.2.0 | 0.2.1 | 0.3.0 |
|---|---|---|---|---|---|
#14 wq | BUG | BUG | BUG | BUG | BUG |
#15 write | BUG | BUG | BUG | BUG | BUG |
#17 e | BUG | BUG | BUG | BUG | BUG |
| #18 CRLF | BUG | BUG | BUG | BUG | BUG |
#19 g marks | BUG | BUG | BUG | BUG | BUG |
#20 0a | BUG | BUG | BUG | BUG | BUG |
| #21 escaped delimiter | BUG | BUG | BUG | BUG | BUG |
#22 ^ under g | BUG | BUG | BUG | BUG | BUG |
| #23 closing delimiter | BUG | BUG | BUG | BUG | BUG |
| #24 count suffix | BUG | BUG | BUG | BUG | BUG |
| #25 UTF-7 refusal | ok | ok | BUG | BUG | BUG |
| #26 exit status | BUG | BUG | BUG | BUG | BUG |
#32 % | BUG | BUG | BUG | BUG | BUG |
| #33 end of input | BUG | BUG | BUG | BUG | BUG |
#34 after g/re/d | BUG | BUG | BUG | BUG | BUG |
Fourteen of the fifteen were in the first release, on May 14, and survived
every release after it: nine releases over six months, including 0.2.1, which
fixed two panics, and 0.3.0, which rewrote the regex engine. The fifteenth, the
UTF-7 refusal, was added in 0.2.0 by the feature that was meant to protect
users from a different problem. j did not exist before 0.1.5, so #35 starts
there.
The table says something about where bugs come from that is easy to misread. None of these bugs was introduced by a careless change to working code. Each was there from the day its feature was written, and each survived because nothing after that day looked at the feature again. The slice plan from chapter 1 built a feature, tested the cases its author had in mind, and moved on, which is the right way to build a program and leaves these behind. A program’s bugs are mostly the ones it was born with.
20.3 What caused them
Read as a list of symptoms, the issues look unrelated: a file named q, a
line in the wrong place, a stray !. Read as a list of causes, they fall into
a handful of patterns, each of which has a shape you can look for in code of
your own.
A parser that interprets what it should pass on. The scanner that finds
the end of each field in s/re/new/ also turned \ followed by the delimiter
into the bare delimiter (chapter 10). That is right when the delimiter is /
and wrong when it is ., because the backslash that made the dot literal was
gone before the regex compiler saw it. The tell was the scanner’s own comment,
which said it preserved escapes for the next stage, and then didn’t preserve
one of them (#21).
Context thrown away. The global substitution loop searched each remaining piece of the line as if it were a whole line:
match re.find(&text[pos..]) {
so ^ matched at the start of every piece, and the loop had no record of
where the previous match had ended (#22). Slicing is cheap and looks harmless.
What it costs is everything the callee could have known about where the slice
came from.
A position that goes stale. g recorded the line numbers of the matching
lines and visited them after earlier commands had changed the numbering
(chapter 12):
marked.push(n);
A number is a position, and positions change when lines are inserted or
deleted above them (#19). The same mistake in a smaller place: the fast path
for g/re/d deleted from the bottom up, which keeps the numbers valid, and so
left the current line where the top-down order would not have (#34).
An error that was dropped. The a command needed a line to append after
and got it from a resolver that rejects address 0:
if !buf.is_empty()
&& let Ok(r) = spec.resolve(buf)
{
buf.set_current(r.end);
}
if let Ok is the most innocent-looking way there is to discard an error, and
here it turned 0a into “append wherever the cursor is” (#20).
A convenience that changes the data. str::lines splits on \n and also
removes a \r before it. For a program that reads text and never writes it
back, that is a kindness. For an editor, it is a conversion applied to every
Windows file on the way in, undone by nothing on the way out (#18).
A match that is too loose. The dispatcher’s second stage takes the first
character as the command and the rest as its argument. That made write into
w with the filename rite, and wq into w with the filename q (#14,
#15). The suffix parser asked whether a g appeared anywhere after the
replacement and ignored everything else, so a count and a typo both ran as a
plain s (#24). Each accepted input it did not understand and did something
plausible with it, which is worse than failing, because it looks like working.
The wrong order. e emptied the buffer and then loaded the file into it.
When the load failed, there was nothing left to go back to (#17). The repair
is a general rule: build the new state somewhere else, and
replace the old one only when the new one is complete. Chapter 5 said it about
writing files; it holds for anything that replaces something.
A guard that guards nothing. 0.2.0 refused to overwrite a file that had
been detected as UTF-7 or UTF-16. Following the detections through load_file
shows that a UTF-16 file never loads, so the only files the guard ever
stopped were ones that had loaded as valid UTF-8, which lose nothing by being
written back (#25). The guard was written for a danger, and nobody checked
that the danger could reach it.
A document typed rather than captured. The tutorial teaches write
(#16). The README’s quick start showed a byte count that did not match its own
file. The help listed seventeen entries and left out three commands that the
dispatcher accepts (#29). Each was written by someone describing what the
program does, and none was produced by running it. Chapter 16 made this
argument; the list shows how many places it applies.
Behavior learned from an implementation instead of the specification.
ved was written by comparing it with GNU ed, command by command, and it
matched GNU ed on the commands that were compared. POSIX specifies things
nobody thought to compare: the optional closing delimiter (#23), the count
suffix (#24), % (#32), end of input acting as q (#33), a nonzero exit
status after an error (#26). None of them was a bug in what ved did. Each was
something ved did not know it was supposed to do.
20.4 What found them
| Method | Issues |
|---|---|
| Comparing ved with GNU ed by hand, command by command | #19, #20, #21, #22, #23, #24, #26, #27, #38 |
| Reading the code closely enough to explain it | #14, #17, #18, #25 |
| Checking a document against the binary | #15, #16, #29, #31 |
| Building on older toolchains | #28 |
| Reading the published package metadata | #30 |
| Reading the POSIX specification | #32, #33 |
| The differential harness | #34, #35, #36 |
| The test suite | none |
The last row is the one to think about. ved 0.3.0 had 185 tests, every one of them passed, and every bug in the table above was present. The fuzzer is not in the table either, for a different reason: by 0.3.0 the panics had been fixed, and a million runs found none. It found a new one in chapter 21, which is the reason to keep running it.
Writing the book was the most productive method, for a specific reason. Explaining a function requires reading every line of it with a question in mind: what does this do with an input its author did not think of? That is a code review. A book is a code review that cannot skip the dull parts, because a chapter has to cover the whole command. You do not need to write a book to get the effect. You need a reader who will ask that question of every line, and the cheapest one available is you, a week later, explaining the code to someone in writing.
20.5 Why the tests did not
Three reasons, each visible in the suite.
The inputs were the author’s. Every test buffer was ASCII, every line
ended in \n, and every test ran one command. CRLF (#18), the escaped
delimiter (#21), and the stale marks (#19), which need a second command to
show, could not appear.
The layer that failed had no tests. The exit status (#26), end of input
(#33), and what reaches standard output (#27) belong to the loop in
run_repl, and every test called dispatch. Chapter 15 named this layer as
the one nobody tested. It is where four of the issues were.
Three tests recorded bugs. list_tab_becomes_octal asserts that a tab
lists as \011, which POSIX says is \t (#38). join_single_line_is_silent_noop
asserted that a one-address j returned an empty Print, which the loop
printed as a blank line. And 0.3.0 added this one, while fixing chapter 9’s
corruption:
let mut buf = buf_with(&["café"]);
let act = dispatch("s/[a-z]*/X/g", &mut buf);
assert!(!matches!(act, Action::Error(_)));
assert_eq!(buf.line(1), Some("XXéX"));
The test was written to prove that a multi-byte character survives a
substitution, and it does prove that. Its expected value came from running
the code, and the code had #22’s bug, so the value has one X too many: sed
prints XéX. A test whose expected value comes from the code under test
cannot disagree with it. Chapter 15 said so in general. This is the
particular case, written into ved’s suite two months before chapter 15 was.
20.6 The finding the book forgot
Chapter 19 said that a finding left in prose is a paragraph. Chapter 14 found
that l lists a tab as \011 where POSIX and GNU ed write \t, said so in a
sentence, and chapter 15 used it as its example of a test that agrees with
the code. It was not in chapter 19’s list, because that list was compiled
from the chapters’ explicit findings and this one was phrased, both times, as
a point about something else. It was not filed on November 21
with the rest. It was found again while section 20.5 was being written, three
chapters later, and filed as #38.
That is the argument for the habit, made by the book against itself. The findings that get lost are not the important ones that everybody remembers. They are the ones that were noticed in passing, while making some other point, by someone who meant to come back to them.
20.7 Which ed
A bug is a difference from what the program should do, so a list of bugs depends on a reference. ved’s has been GNU ed, which is installed on the machine, answers any question in a millisecond, and is what chapter 1 meant by “sitting on the machine to compare against.” The same sentence in chapter 1 says that POSIX defines what ed does. Most of this book treated those as the same thing. They are not, and neither is a third reference: the original.
Seventh Edition Unix, from 1979, runs today under the SIMH PDP-11 simulator,
and its ed is the one Ken Thompson’s design became before anyone
standardized it. tools/v7/ boots it and types ed commands at its console.
Running the disputed cases on all three gives this:
| Question | POSIX | Seventh Edition | GNU ed 1.21.1 |
|---|---|---|---|
| Exit status after an error | nonzero | 0 | 1 |
| The rest of a script after an error | not specified | dropped | dropped from a file, run from a pipe |
, meaning 1,$ | yes | an error | yes |
wq | not in POSIX | an error | yes |
s/a/b with no closing delimiter | allowed, and prints | an error | allowed |
A count, s/a/X/2 | yes | an error | yes |
% as the replacement | yes | a literal % | yes |
s/a*/X/g on baaac | not specified | XbXcX | refuses: “Infinite substitution loop” |
0i | not specified | an error | as 1i |
3,1a | appends after 1 | an error | appends after 1 |
The current line after 2j | unchanged | 2 | unchanged |
A \r before the newline | not addressed | kept | kept |
l of a carriage return | \r | \15 | \r |
The table has a shape. Where POSIX speaks, GNU ed almost always agrees with it, and the Seventh Edition often does not, because POSIX was written later and fixed things. The exit status row is the clearest case: POSIX’s rationale says that “some historical implementations returned exit status zero even if command errors had occurred; this is not allowed,” and the Seventh Edition is one of them. Where POSIX is silent, the Seventh Edition and GNU ed can disagree with each other, and the empty-match row is a case where GNU ed is the odd one out.
So ved now has a rule, written into its notes and its commit messages. POSIX decides. Where POSIX says “unspecified,” the Seventh Edition decides, because it is the closest thing there is to what ed is. GNU ed is the comparison that runs in a millisecond, never the definition, and where it differs from both, the difference is written down rather than copied.
Some differences from all three are deliberate: ved’s confirmations, its
messages, H printing a reference instead of toggling verbose errors, and the
long-form command names. A deliberate difference is not a bug, and the way to
keep it from being mistaken for one is to write it down once, where a reader
of the code or the documentation will find it. A difference nobody wrote down
is a bug until someone decides otherwise.
20.8 What order to fix them in
The issues were numbered in the order they were filed, and the order was a
rule. A change that loses the user’s text without a message comes first,
ranked by how many users reach it: wq ends a great many ed scripts, and the
tutorial is the first thing a new user reads. After those come text that ends
up wrong but present, then what scripts see, then the packaging and
documentation that describe the program to people who have not installed it.
The rule is short because it has to be applied quickly, to a list that will grow. Two refinements were needed in practice. A fix that other fixes depend on goes first regardless of rank: the long forms (#15) changed the dispatcher that the help text (#29) and the tutorial (#16) describe. And a finding that changes behavior some user may rely on, like the exit status (#26), is ranked by the harm of the current behavior, not by the risk of changing it; the risk belongs to the release, which is chapter 22’s subject.
20.9 A report that can be fixed
Here is #20, as filed:
`a` ignores an address it cannot resolve and appends after the current
line. `0a`, the usual way to put text at the top of a file, puts it at
the bottom:
$ printf 'one\ntwo\n' > f.txt
$ printf '0a\nNEW\n.\nw\nq\n' | ved f.txt; echo "exit $?"
8
wrote 12 bytes to f.txt
exit 0
$ cat 'f.txt'
one
two
NEW
GNU ed puts NEW first. [...]
The `a` arm in `dispatch` calls `spec.resolve(buf)`, which rejects 0
because ranges start at 1, and discards the error with `if let Ok`.
It has four parts, and each one saves the person fixing it a step. A sentence saying what is wrong, in the user’s terms. A session that anyone can paste into a shell, with the output it produced, so the first thing the fixer does is see it fail. The reference’s output for the same input, so there is no argument about what right looks like. And the cause, where the reporter knows it, which turns the fix from a search into an edit.
The sessions were not typed. Each was generated by a script that ran the
commands and pasted what came out, for the same reason chapter 16 gave for the
tutorial: a report that cannot be reproduced exactly is a report that starts
an argument. One issue was wrong anyway. #15 first claimed that GNU ed accepts
wfoo. Checking it while fixing #15 showed that GNU ed rejects it, as chapter
14 had said, and the issue was corrected before the fix was written. A report
is a claim, and it is checked like one.
Exercise 20-1. Run tools/bugs-by-release.sh against examples/ved and
examples/ch19-living. Then pick one issue and find the commit that
introduced it with git bisect in ved’s history, using the reproduction from
the issue as the test. How many of the fourteen were born in the commit that
first wrote their feature?
Exercise 20-2. Take the causes in section 20.3 and search a program of
your own for each one: a let Ok or .ok() that discards an error from user
input, a lines() on data you write back, a slice passed to a function that
needs to know where it came from, a stored index into a collection that
changes. Count what you find, and file each one.
Exercise 20-3. Write the tests that would have caught #18, #19, and #26,
with expected values from POSIX or the Seventh Edition rather than from
running ved. Run them against examples/ch19-living and watch them fail.
Exercise 20-4. Find three more rows for the table in section 20.7: cases
where POSIX, the Seventh Edition, and GNU ed might disagree. Run them with
tools/v7/ and /usr/bin/ed, and decide what ved should do for each.
Exercise 20-5. Find a test in a project of your own whose expected value was produced by running the code. Replace the value with one from an independent source and see whether the test still passes.
21. Fixing Them
Chapter 20 ended with twenty-four issues in an order. This chapter fixes
them: the procedure, then the fixes that teach something, in the order they
were made. The code is examples/ch21-fixed, which is ved 0.4.0, and every
fix is one commit in ved’s history, on a branch named fix/book-findings,
merged as pull request #37.
21.1 The procedure
Each fix followed the same steps, and the steps were the point:
- Run the session from the issue against the current binary and watch it fail. An issue that does not reproduce is a different conversation.
- Write the test first, with its expected value taken from a reference, not from the code. Section 20.5 showed what happens otherwise.
- Make the smallest change that turns the test from failing to passing without breaking another.
- Run the whole suite,
cargo fmt --check, andcargo clippy -- -D warnings. - Run the session from the issue again, against the built binary.
- Commit, with a message that says what was wrong, what changed, and which
reference decided, ending in
Fixes #N.
And after the last fix, two checks that no single fix can do: the differential harness from chapter 15, to find what the fixes changed that nobody asked them to, and the fuzzer, to find what they broke. Both found something.
Two rules shaped the commits. One issue per commit, so that a commit can be
reverted without reverting anything else, and so that the history can be
read as the list of issues. And the reasoning goes in the commit message,
where it stays attached to the change, rather than in a comment, where it
describes a change that is no longer visible. A reader of git log for 0.4.0
gets twenty-three short essays on what was wrong with ved and why the fix is
the fix.
21.2 Two lines: wq
The smallest fix is the most common case of the most damaging bug. wq
reached the w arm with the argument q, and the w arm wrote a file by
that name (#14). The fix is to look for the q first:
'w' => match args.strip_prefix('q') {
Some(file) if file.is_empty() || file.starts_with(char::is_whitespace) => {
match run_write(&spec, buf, file) {
Action::Confirm(msg) => Action::ConfirmAndQuit(msg),
other => other,
}
}
_ => run_write(&spec, buf, args),
},
A wq that cannot write returns the write’s error and does not quit, which
is what GNU ed does and the only safe choice. A new Action,
ConfirmAndQuit, tells the loop to print the byte count and leave.
Checking wq against the references found that it is not in POSIX. The
specification’s rationale lists it among “the BSD ed commands W, wq, and z”
that it leaves out, and Seventh Edition ed answers it with ?. ved keeps it,
because scripts written for GNU and BSD ed end with it, and because the
alternative, an error, would still be better than what 0.3.0 did. The commit
message says so, which is what section 20.7 asked for: a difference from the
reference that is written down.
21.3 The rule first, then the feature: long forms
write, edit, and read (#15) could have been fixed by adding three
strings to a match arm. That would have fixed the three words and left the
cause: w followed by anything at all is a write to a file named after the
anything, so wnotes.txt writes notes.txt. GNU ed and Seventh Edition ed
both reject that. ved now does too, and once a filename command needs
whitespace after its letter, the long forms cannot collide with a filename:
fn split_command(rest: &str) -> Option<(char, &str)> {
for (long, letter) in [("edit", 'e'), ("read", 'r'), ("write", 'w')] {
if let Some(args) = rest.strip_prefix(long)
&& (args.is_empty() || args.starts_with(char::is_whitespace))
{
return Some((letter, args));
}
}
let mut chars = rest.chars();
let first = chars.next()?;
let args = chars.as_str();
let takes_filename = matches!(first, 'e' | 'E' | 'r' | 'w');
let is_wq = first == 'w'
&& args
.strip_prefix('q')
.is_some_and(|f| f.is_empty() || f.starts_with(char::is_whitespace));
if takes_filename && !is_wq && !(args.is_empty() || args.starts_with(char::is_whitespace)) {
return None;
}
Some((first, args))
}
The order of the two changes is the lesson. Fixing a symptom without the rule
that produced it leaves the next symptom in place, and here the next symptom
was already visible: a user who types writenotes.txt, without the space,
would have got a file named ritenotes.txt from the alias-only fix.
This fix also fixed the tutorial. The tutorial teaches write notes.txt and
edit filename; with the long forms implemented and e fixed (below), what
it teaches is now what the program does. Replaying every session in the
tutorial against the new binary, rather than reading it, found two more
errors in it, a capture-group example that searched for text an earlier step
had changed and a byte count that was never right. Both are now pasted from a
run. The issue (#16) stayed open until the evening, because the tutorial is
also published on two websites, and those copies change only when they are
deployed.
21.4 Build, then swap: e
e had two bugs and they needed different kinds of fix (#17). The first was
an order:
let mut fresh = Buffer::new();
let action = match load_file(&filename, &mut fresh) {
Ok(LoadOutcome::Loaded(bytes)) => Action::Confirm(format!("{bytes}")),
Ok(LoadOutcome::NewFile) => Action::Confirm(format!("{filename}: new file")),
Err(e) => return Action::Error(e),
};
*buf = fresh;
action
The old buffer is replaced only after the new one exists. A load that fails returns before the assignment and leaves the old buffer, its modified flag, and the user’s afternoon of work where they were.
The second was missing behavior. POSIX says that e on a modified buffer
warns, sets a flag it calls changed-and-warned, and takes effect if it is
repeated with nothing in between, which is the same rule as q, and the same
flag. Seventh Edition ed behaves that way. Chapter 13’s scratch fix added only
E, the form that skips the check, because the double-e needs the loop’s
warning state, which dispatch cannot see. The shipped fix keeps dispatch
stateless by letting it ask:
let action = match dispatch(trimmed, &mut buffer) {
Action::EditModified(args) if modified_warned => run_edit(&mut buffer, &args),
other => other,
};
dispatch returns EditModified for an e on a modified buffer. The loop
warns the first time and runs the edit if the next command is another e.
The loop’s quit_warned became modified_warned and serves both commands,
as POSIX’s one flag does. Chapter 6 argued that dispatch should hold no
state, and this is what that argument costs and buys: one more variant in
Action, and a dispatcher that can still be tested without a loop.
21.5 A fix that changes the data structure: marks
The g bug (#19) could not be fixed inside run_global. The loop needs to
visit the lines it matched, and the only way to find a line after other lines
have moved is for the mark to move with it. Chapter 12 showed how the Seventh
Edition does it, with a mark bit in each line’s entry in the buffer’s table.
ved now does the same:
struct Line {
text: String,
marked: bool,
}
Buffer holds a Vec<Line> instead of a Vec<String>, and gains three
methods, set_mark, take_mark, and clear_marks. run_global sets a mark
on each matching line and then takes them one at a time; take_mark returns
the first marked line by its number at that moment and clears it.
What makes the fix hold is not in run_global. Chapter 3 put every change to
the lines behind three methods, append_after, delete_range, and
replace_line, and the mark now rides on those. append_after inserts an
unmarked line, so marks below it move down with their lines. delete_range
drains lines and their marks together. replace_line changes the text and
leaves the mark. No command needed to learn about marks, because no command
touches the vector. The module boundary from chapter 3 was paid for in that
chapter and collected on here.
One command did need to change. m moved lines by copying their text,
deleting them, and inserting the copies, which loses the marks on the lines
it moves. It now uses a fourth primitive, move_range, which moves the Line
values themselves, so a marked line that m moves keeps its mark. The
Seventh Edition’s m moves table entries, mark bits included, for the same
effect.
take_mark searches for the first marked line, and searching from the top
each time would make g/^/m0 on a large file quadratic in a new way. Buffer
keeps first_mark, a position no mark is above, which the primitives lower
when they could have moved a mark above it. Chapter 15’s benchmark command,
g/^/m0 on 100,000 lines, took 7.09 seconds on 0.3.0 and 7.06 on the fix.
The differential harness, run after this fix, found one more: g/re/d left
the current line after the first deleted line, where GNU ed and Seventh
Edition ed leave it after the last (#34). The fast path for a plain d
deletes from the bottom up, which keeps the numbers valid without marks and
is cheap, and so got the current line from the wrong end. It was in 0.3.0, it
had nothing to do with marks, and it became visible only when the harness had
fewer, louder differences to report.
21.6 A fix that changes an API: find_at
The anchor and empty-match bugs (#22) came from searching slices of a line as if they were lines. The fix gives the regex engine a way to search the whole line from a position:
pub fn find_at(&self, text: &[u8], start: usize) -> Option<Match> {
let elements = &self.elements;
let anchored = !elements.is_empty() && matches!(elements[0], Element::Caret);
let elems = if anchored { &elements[1..] } else { elements };
if anchored && start > 0 {
return None;
}
// ... the search loop from `find`, starting at `start`
}
and find becomes find_at(text, 0). With that, one function replaces the
two that substituted the first match and every match, and takes a count for
#24:
while search <= text.len() {
let Some(m) = re.find_at(text, search) else {
break;
};
let step = if m.start == m.end {
bre::char_width(&text[m.start..]).max(1)
} else {
0
};
if m.start == m.end && prev_end == Some(m.start) {
search = m.start + step;
continue;
}
seen += 1;
if seen >= nth {
result.extend_from_slice(&text[copied..m.start]);
result.extend_from_slice(&bre::expand_replacement(replacement, &m, text));
copied = m.end;
replaced = true;
if !global {
break;
}
}
prev_end = Some(m.end);
search = m.end + step;
}
The skip in the middle is the rule for an empty match where the previous
match ended, and it is the one case in this chapter that POSIX does not
decide. GNU ed refuses s/a*/X/g with “Infinite substitution loop”. Seventh
Edition ed answers XbXcX on baaac, and so does sed, so ved follows the
Seventh Edition, as the rule in section 20.7 says.
Making the change broke one test,
global_substitute_with_star_that_can_match_empty_preserves_characters, which
expected XXéX. Section 20.5 explained why that value was wrong. When a fix
breaks a test, the first question is which of the two is wrong, and the answer
comes from the reference, not from the side that changed most recently. Here
sed gave XéX, and the test changed.
21.7 Fixes that change what someone sees
Some fixes change behavior that a user may have come to rely on, and those need a reason that outweighs that risk, written where the user will see it.
CRLF (#18). Splitting on \n alone keeps the \r in the line, so a
Windows file is written back with its own line endings. The cost is that
s/e$/E/ no longer matches a line that ends in \r, and l shows the
\r. That is also how GNU ed and Seventh Edition ed behave. The alternative,
detecting the style at load and restoring it at write, would hide the \r
from patterns, but it would normalize a file with mixed endings, which is a
choice neither ed makes.
Exit status (#26). Any ? now makes the exit status 1, including the
modified-buffer warning. POSIX requires it and says outright that historical
implementations which exited 0 are not allowed. A script that ran ved and
ignored its errors used to succeed and will now fail. That is the fix.
-s (#27). The flag needed one condition in the loop, but the loop could
not tell a line the user asked to see from a line ved says about a command.
Both were Print. So the fix starts with the type:
enum Action {
// ...
/// Output the user asked for, such as the lines `p` prints.
Print(String),
/// What ved says about a command it carried out, such as a byte
/// count. `-s` suppresses these.
Confirm(String),
/// The results of the commands `g` ran, in order.
Batch(Vec<Action>),
Error(String),
}
Every byte count and confirmation became Confirm. s confirms the line it
changed, and prints it when given p, l, or n, which is what POSIX’s s
does. g used to join its commands’ output into one string, which would have
lost the difference, so it returns a Batch. Then -s is one line in one
function:
Action::Confirm(msg) => {
if !silent {
let _ = writeln!(out, "{msg}");
}
false
}
Chapter 14 predicted that shape, and Appendix C lists it as a step: put the
distinction in the types, and the flag is trivial. POSIX’s -s suppresses
only byte counts, because ed has nothing else to suppress. ved’s
confirmations have no ed equivalent, so -s suppresses them too, and the
output matches ed -s byte for byte on the scripts it was checked with.
j with one address (#35). POSIX says it does nothing and leaves the
current line unchanged. GNU ed agrees. Seventh Edition ed moved the current
line to the address, as ved did. This is the one case where the original and
the standard disagree and the standard was followed against the original,
because POSIX speaks.
21.8 A fix that removes code
The UTF-7 refusal (#25) was fixed by deleting it: the non_utf8_source
field, the two Buffer methods that read and wrote it, the check in
run_write, and the test that held it in place. The commit added 22 lines and
removed 54. The warning and its iconv hint stayed, because a Scoutbook
export is still worth pointing out; the refusal went, because the only files
it could ever refuse were ones that were not UTF-7.
Deleting a safety check feels worse than adding one, and the feeling is the
reason to write down the argument. The commit message traces the two
detections through load_file and shows that the guarded case cannot reach
the guard. A later reader who wonders why ved does not refuse to overwrite a
UTF-7 file can find the answer in the history, with the reasoning attached.
21.9 The fix that broke something
Making the closing delimiter optional (#23) was twelve lines, and it had a test, and the suite passed. The fuzzer, run after the last fix, found this:
PANIC substitution result is valid UTF-8: FromUtf8Error { bytes: [151, 106,
e.g. ["sé*×j\\"] on [""]
1 distinct panics in 1000000 runs
s takes the first byte of its argument as the delimiter, and é is two
bytes. In 0.3.0 the same input failed as “unterminated replacement”, because
the second delimiter was never found. With the closing delimiter optional,
the replacement ran to the end of the line and began with the second half of
é, and rebuilding the line as UTF-8 panicked. A change that was correct for
every input anyone had thought about turned an error into a crash for one
nobody had, which is the profile chapter 5 gave for latent panics and chapter 15
gave for the fuzzer’s reason to exist.
The fix is a rule about delimiters, in its own commit:
fn valid_delimiter(delim: u8) -> bool {
delim.is_ascii() && !matches!(delim, b' ' | b'\n')
}
POSIX allows any character except space and newline. ved scans fields byte by
byte, so it also needs the delimiter to be one byte, and GNU ed rejects a
multi-byte delimiter too. The first version of this fix also rejected
backslash, on the theory that it would make every field an escape. GNU ed
accepts s\a\b\, POSIX does not exclude it, and the scanner checks for the
delimiter before it checks for an escape, so the theory was wrong and the
commit was amended before the branch was pushed. A million fuzzer runs on the
result find no panics.
The order of the checks mattered here, and it makes a rule: the fuzzer runs after the last fix, not after the first. Each fix changes the input space the others see, and a crash introduced by fix eleven is invisible to a fuzzer that ran after fix three.
21.10 Fixing the documents
Three fixes were to documents, and each was made the way chapter 16 said documentation should be: by running the program and pasting what it printed.
The help (#29) gained e, E, r, Q, wq, the long forms, the search
addresses, and the right default address for g, v, and w. It also
gained a test, which chapter 14 proposed and nobody had written:
fn help_mentions_every_command_the_dispatcher_accepts() {
let Action::Print(help) = run_help() else {
panic!("help should print");
};
for cmd in [
"a", "i", "c", "d", "p", "n", "l", "j", "m", "t", "s", "g", "v", "w", "wq", "r",
"e", "E", "q", "Q", "H",
] {
// ... assert that some line of the help starts with `cmd`
}
}
The list in the test is a third copy of the command set, which is the objection chapter 14 raised. It stays, because when it drifts it fails, and the help drifted silently for six months.
The README’s quick start (#31) had been typed. It is now a session captured through a terminal, so the prompt, the byte counts, and the confirmations are what ved prints. And the install section now says what a macOS user does: install with Cargo, and leave the retired Homebrew tap, whose users would otherwise sit on 0.2.1 with no sign that anything had changed.
21.11 What it came to
| Commit | Issue | Lines added | Removed |
|---|---|---|---|
wq writes the file and quits | #14 | 42 | 1 |
write, edit, read, and no filename glued to w, e, r | #15 | 68 | 4 |
e warns, and a failed e keeps the buffer | #17 | 68 | 20 |
| The help lists every command | #29 | 43 | 19 |
| The tutorial, captured from a run | #16 | 8 | 5 |
| CRLF line endings are kept | #18 | 29 | 3 |
g and v mark lines | #19 | 160 | 36 |
0a, and a past the end | #20 | 68 | 18 |
| An escaped delimiter is the literal character | #21 | 44 | 29 |
^ once, and no empty match after a real one | #22 | 84 | 55 |
| The closing delimiter is optional | #23 | 12 | 4 |
The count, and p, l, n | #24 | 117 | 29 |
% | #32 | 22 | 1 |
| Exit status | #26 | 96 | 7 |
| End of input warns | #33 | 26 | 1 |
-s | #27 | 165 | 92 |
| The UTF-7 refusal removed | #25 | 22 | 54 |
rust-version | #28 | 7 | 1 |
| The README | #31 | 16 | 10 |
| A delimiter must be one ASCII byte | none | 33 | 0 |
The current line after g/re/d | #34 | 17 | 0 |
j with one address | #35 | 2 | 3 |
Twenty-one issues, twenty-three commits counting the README’s command table
and the delimiter fix, which had no issue because the bug it fixed never
shipped. The largest fix is -s, because it changed a type that every
command returns. The second largest is the marks, because it changed a data
structure. Everything else is under 120 lines, and most of the lines in every
commit are tests.
Measured on the result, against 0.3.0:
| 0.3.0 | 0.4.0 | |
|---|---|---|
| Lines of Rust | 3,625 | 4,367 |
| Unit tests | 185 | 215 |
| Tests that run the binary | 0 | 10 |
| Single-command scripts that differ from GNU ed, of 3,000 | 425 | 99 |
| Scripts of one to three commands that differ, of 3,000 | 787 | 180 |
| Fuzzer panics in a million runs | 0 | 0 |
All 99 remaining single-command differences are s/[ab]*/-/g, the case where
GNU ed refuses and ved follows the Seventh Edition. Of the 180, 84 are the same
case; the rest were filed as #36, and section 22.6 is about what they turned
out to be. The harness numbers use seed 1, so they are comparable with each
other and not with chapter 15’s, which used a different one.
The test count rose by 40, and the bugs fixed number 21. That ratio is the procedure in section 21.1 made visible: every fix began with a test that failed, and most began with several, because a bug that was found by one input usually has neighbors.
Exercise 21-1. Pick one issue and fix it in examples/ch19-living
without looking at this chapter’s code: reproduce it, write the test with an
expected value from POSIX or the Seventh Edition, make the change. Then
compare your fix with ved’s commit for it, and list what each does that the
other does not.
Exercise 21-2. The first_mark hint in section 21.5 is maintained by the
four primitives. Write a property test, with the xorshift generator from
chapter 15, that applies random sequences of append_after, delete_range,
move_range, and set_mark to a buffer, and checks after each step that no
marked line sits above first_mark.
Exercise 21-3. Run tools/difftest.py against examples/ch21-fixed with
MAXC=3 and twelve examples. Take one difference that is not
s/[ab]*/-/g, decide which program is right using the order of authority in
section 20.7, and either fix ved or write down why it differs.
Exercise 21-4. The fuzzer’s alphabet has no w, e, or r, so that it
cannot write files. Add E and r with filenames from a fixed set of paths
inside a temporary directory, run it, and report what it finds.
Exercise 21-5. Implement #38 in examples/ch21-fixed: l writes \t,
\r, and the other C escapes POSIX names, and folds long lines. Decide the
folding width and write down why, then compare your version with ved 0.4.1’s,
which section 22.6 describes.
22. Shipping the Fixes
A fix on a branch helps nobody. This chapter takes the twenty-three commits from chapter 21 to the people who have ved installed: the version number, the merge, the release, the four channels, what the release notes said, and what the release could not reach. It happened on November 21, the same day as the fixes, and every output quoted here is from that run.
22.1 Which number
Chapter 17’s rule is that the version says what changed for the person using
the program. Three of 0.4.0’s changes are new things a user can do: the long
forms, %, and -s. Those make it at least a minor release. Several more
change what an existing input does: a script that ignored errors now exits 1,
a Windows file keeps its line endings, 0a puts text somewhere else, a
one-address j no longer moves the cursor. Each of those is a bug fix, and
each could break a script that relied on the bug.
Before 1.0, Cargo’s rules treat a minor release as the breaking one, so
0.3.0 to 0.4.0 is the number that says “read the notes before you
upgrade,” and it is what build-release minor produced. After 1.0, the same
set of changes would raise a harder question. The usual reading of semantic
versioning is that a change to documented behavior is breaking, and a change
to undocumented, wrong behavior is a fix, and ved’s exit status was
documented by nothing except its own code. A project that reaches 1.0 needs
that line drawn in writing before the first release that tests it, because
drawing it during the release is how a project talks itself out of a fix.
22.2 One branch, one merge
The fixes were made on a branch and merged as one pull request, #37, rather
than committed to main one at a time. The branch kept main releasable while
twenty-three commits were in progress, and it let one commit be rewritten
safely: the delimiter fix in section 21.9 was amended, and the messages that
said “as in ed” were corrected to name which ed, both before anything was
pushed. Rewriting history that nobody else has is housekeeping. Rewriting
history that somebody has pulled is a problem for them.
The merge closed every issue whose fix said Fixes #N. The tutorial’s fix
said Refs #16 instead, and the issue stayed open on purpose. The tutorial
was fixed in the repository, but the copies on anderix.com and excelano.com
are separate files that change only when those sites are deployed, and
closing the issue before then would have claimed that a reader of either site
saw the fix. It closed when they were deployed, the same evening. The WinGet
description (#30) has no commit in ved at all, because it is not in ved’s
repository, which section 22.5 explains.
22.3 The release
build-release minor -y, run from ved’s root, did the release. Its output,
trimmed:
==> pushing main
==> building debs
/home/anderix/repos/tools/ved/target/distrib/ved_0.4.0-1_amd64.deb
/home/anderix/repos/tools/ved/target/distrib/ved_0.4.0-1_arm64.deb
==> building ved-x86_64-pc-windows-msvc.zip on winwork
ved-x86_64-pc-windows-msvc.zip
==> tagging v0.4.0
==> creating the release
https://github.com/excelano/ved/releases/tag/v0.4.0
==> uploading 3 assets
==> verifying the release
ved-x86_64-pc-windows-msvc.zip
ved_0.4.0-1_amd64.deb
ved_0.4.0-1_arm64.deb
0.4.0
Before any of that, it bumped Cargo.toml and ran the tests, all 225 of
them, so the commit that the tag points at is one that passed. Then three
more commands, one per channel, each of which ends by checking the live
channel rather than trusting its own success:
$ ship-apt -y
...
==> verifying live
amd64 ved 0.4.0-1
arm64 ved 0.4.0-1
==> excelano/ved 0.4.0 is live on apt
$ ship-crates -y
...
==> verifying crates.io
ved 0.4.0
$ ship-winget -y
...
==> submitting Excelano.ved 0.4.0
https://github.com/microsoft/winget-pkgs/pull/486054
Chapter 17 described a release procedure that lived in a document; chapter 19 described it moving into programs. This is what that bought on a release day: four commands, run by the person who wrote the fixes, with nothing remembered and nothing skipped. The WinGet line ends at a pull request because WinGet’s catalogue is a repository someone else reviews, and the release reaches Windows users when a moderator merges it.
22.4 What the notes said
build-release writes the release notes from the commit subjects since the
last tag, which is why chapter 16 asked for subjects written for the person
installing the release. The GitHub release for 0.4.0 begins:
- J with one address leaves the current line where it was
- G/re/d leaves the line after the last deletion current
- A delimiter that is not one ASCII byte is an error, not a panic
- A UTF-8 file containing +ACI- can be saved in place
- -s prints only what the commands ask for
- End of input on a modified buffer warns, as q does
- Exit nonzero when any command failed
...
- E warns before discarding a modified buffer, and a failed e keeps it
- Write, edit and read long forms, and no filename glued to w, e or r
- Wq writes the file and quits
Two things in it are wrong, and neither was visible until the notes existed.
The tool removes the fix: prefix and capitalizes what is left, which is
right for an English sentence and wrong for a subject that begins with an ed
command. j, g, and wq became J, G, and Wq, which a reader can
probably decode. e became E, which is a different command: the note says
that E warns before discarding a buffer, and E is the one command that
does not. The same subjects went into the Debian package’s changelog. The
fix for the next release is in the subjects, not the tool: a subject for a
program whose commands are single letters starts with a word, such as “the
e command warns before discarding a modified buffer”, so that the first
letter is safe to capitalize.
The second is what is missing. The notes list feat and fix commits and
leave out docs and build, by design, because those are changes to the
repository rather than to the program. That left out the README’s new
instructions for macOS users, which exist only to reach people who installed
with Homebrew, and the declared minimum Rust version, which is the first
thing a user with an old toolchain will hit. A change a user needs to hear
about is a user-facing change whatever directory it is in, and its type
should say so. The two commits should have been fix:, and the rule they
broke is the one chapter 17 quoted: fix: and feat: are for changes a user
would notice, which is a question about the user, not about which files the
change touches.
Both were corrected the same evening. The GitHub release’s notes were edited, with each command letter kept lowercase in code style and the two missing lines added. The Debian changelog was not, and cannot be: it is inside the packages, and a package changes only with a new version. A generated document that is wrong in one place is wrong in every place it was copied to before anyone read it, and the copies that cannot be edited are the ones to think about before the generator runs.
22.5 What the release could not reach
The WinGet description (#30). The first 0.4.0 manifest still called ved
“a drop-in ed clone.” ship-winget builds each manifest with komac update,
which copies the previous version’s description forward, so the text from the
first submission had been carried into every version since, and 0.4.0 was no
exception. The fix went into the release tool rather than the manifest: for a
repository with one WinGet package, ship-winget now sets the description
from Cargo.toml’s description on every submission, so the description has
one source and a correction reaches WinGet at the next release without anyone
remembering to make it.
The 0.4.0 pull request was then closed and submitted again with the new tool, the same evening, with the corrected description and the corrected notes. That broke one of the tool’s own rules, one pull request per package per day. The rule was the fleet’s, not WinGet’s, whose guide asks only that a version never have two pull requests open at once, and the first one had been closed. A rule a project made for itself can be set aside when its reason does not apply. Telling the rules a project made from the rules it was given is what makes that safe.
The websites (#16). The two published copies of the tutorial are not the repository’s file, so the release did not change them. Each got the same corrections by hand and was deployed that evening, and then the issue closed. Doing it turned up two more pages: ved’s page on excelano.com and its card on the home page still called it a drop-in clone and said that any script written for ed runs unchanged, the claim the README had dropped in July. They were corrected in the same deploy. Chapter 18 counted six copies of ved’s one-sentence description; these were two more that nobody had listed, and a correction reaches only the copies on the list.
Homebrew users. Chapter 19 found that people who installed 0.2.1 with
brew were left on it, with no way to learn that anything had changed. 0.4.0
does not reach them either, because no channel they use carries it. The
README now tells them what to do, and the README is the one place they are
unlikely to look. The only message that reaches a user of a dead channel is
one sent before it dies.
What the tracker still held. #36 listed the differences the harness still
found, and #38 the l escapes. Both were filed after the branch was planned,
so 0.4.0 shipped with them open, which is the normal case. The useful
property is that they were known, written down, and linked from the chapter
that found them, which is what made the next section short.
22.6 0.4.1
The two open issues were fixed the same night, on a second branch merged as pull request #39, and released as 0.4.1. A patch release, because nothing in it adds a command; it makes five existing behaviors match the reference.
#36 turned out to have three causes, none of them the one its description guessed.
The g and j case was not about g: +1m-1 from line 1 failed because an
offset that landed on 0 was rejected even where 0 is a valid address. An s
with an invalid address was recorded for a bare s to repeat, because ved
parsed the command before it resolved the address, where ed does the
reverse. And , on an empty buffer was rejected for a and i, where POSIX
bounds only the final address, which there is 0. Each was a commit with a
test whose expected values came from GNU ed’s output, and after them the
harness, run without its empty-match command, finds 3 differing scripts in
3,000.
All three are one case: m to the last line of its own range, such as
1m1. GNU ed accepts that as a move that changes nothing. POSIX says it is
an error “if address falls within the range of moved lines,” and Seventh
Edition ed rejects it, so ved does too, and #36 closed with that decision
written on it. A harness that ends at a short list of differences, each with
a reason, is a harness that has done its job; it was never going to end at
zero, because the reference is not the specification.
#38 made l write \t, \r, and the other escapes POSIX names, and fold
long lines. POSIX leaves the folding width open, so ved folds where GNU ed
does, measured by running it on lines of 75, 76, and 77 characters, and the
output now matches GNU ed’s byte for byte, folds included. The test that had
held the octal tab in place was replaced by one whose expected value is GNU
ed’s output.
Two of the commit subjects began with a command, l and ,, and would have
come out of the release-notes generator as “L writes” and “, on an empty
buffer.” They were reworded to begin with a word before the branch was
pushed, which is section 22.4’s lesson applied once, and 0.4.1’s notes read
correctly as generated.
The WinGet pull request for 0.4.0 was still waiting for a moderator. Only the
current version is owed a manifest, so it was closed and 0.4.1 submitted in
its place, with the description from Cargo.toml. A Windows user goes from
0.3.0 to 0.4.1 directly, and loses nothing by skipping a version they never
had.
22.7 The loop
The loop chapter 19 described, someone reads the program closely, writes down what is wrong, and the list goes into the place where lists get done, has now gone around once, and it can be measured. Eighteen findings from chapters 10 to 19 went into the tracker on one day, and reading the specification added two more. Twenty issues were closed the same day, one commit each, each with a test whose expected value came from a reference, and a twenty-first, the tutorial, closed when the websites were deployed. Two more bugs were found by the tools that checked the fixes, and one was introduced by a fix and caught before it shipped. The release went out through four channels and verified each, and the notes that went with it had two mistakes, corrected that evening, that the next release can avoid.
None of that needed anything this book has not shown. The tracker is chapter 19’s. The order is chapter 20’s rule. The procedure is chapter 15’s tests and harness and fuzzer, aimed at a list instead of at a program. The release is chapter 17’s, run by the tools chapter 19 described. What the loop adds is the habit of going around it: of treating the close reading as the start of the work rather than the end of it.
ved 0.4.1 is a better program than 0.3.0 in the ways chapter 20 listed, and its tracker has no open issues. It still has bugs. They are in the commands nobody has read closely yet, which is where chapter 20 said they would be, waiting for the next person who explains the code to somebody in writing.
Exercise 22-1. Rewrite the subjects of the twenty-three commits so that the release notes read correctly after the type is removed and the first letter capitalized. Then decide whether the tool or the subjects should change, and write down why.
Exercise 22-2. Write the 0.4.0 entry of a CHANGELOG.md by hand, for a
user deciding whether to upgrade. Include what can break a script that
relied on 0.3.0’s behavior, and compare it with the generated notes.
Exercise 22-3. Draft the policy section 22.1 asks for: what counts as a breaking change for ved after 1.0. Apply it to every commit in 0.4.0 and count how many would have required a major version.
Exercise 22-4. The fix for #30 takes the description from Cargo.toml
only when a repository ships one WinGet package. Design what a release tool
should do for a repository that ships several, each with its own
description, without keeping a second copy of any of them.
Appendix A: The Finished Program
This is a map of examples/ved, which is ved 0.2.1, the program chapters 1 to
18 describe. It is meant to be read with the source open beside it. Every
number here was measured from that crate.
A.1 The files
| Module | Lines | Code | Tests | Owns |
|---|---|---|---|---|
main.rs | 1,287 | 928 | 359 | The loop, the arguments, the dispatcher, and every command |
bre.rs | 1,064 | 467 | 597 | The regex engine and the replacement expander |
address.rs | 233 | 233 | 0 | Address parsing and resolution |
buffer.rs | 156 | 156 | 0 | The text and the state that belongs to it |
enc.rs | 131 | 94 | 37 | Encoding detection for files that are not UTF-8 |
| Total | 2,871 | 1,878 | 993 |
“Tests” is everything from the #[cfg(test)] line to the end of the file.
There are 125 tests: 90 in bre.rs, 32 in main.rs, and 3 in enc.rs. The
crate has no dependencies, and a release build takes about half a second.
A.2 The types
Buffer (buffer.rs, chapters 3 and 5). The lines as a Vec<String>, the
current line, whether the text differs from the file, the remembered filename,
the last substitution, and the record of a file loaded as non-UTF-8. Every
field is private. Lines change only through append_after, delete_range, and
replace_line.
Address, Spec, Range (address.rs, chapter 4). Address is one
address as typed: a number, ., $, or an offset from the current line.
Spec is what the user typed in front of a command, zero, one, or two
addresses. Range is what a Spec means against a particular buffer, a pair
of 1-indexed, inclusive line numbers.
Action (main.rs, chapters 2, 3, 5, and 6). What the loop should do
after a command: Quit, ForceQuit, EnterInputMode, Done, Print(String),
or Error(String). Every command returns one, and only the loop acts on it.
PrintMode (main.rs, chapter 14). Plain, Numbered, or List, for
p, n, and l, which share one function.
LoadOutcome (main.rs, chapter 13). Loaded(bytes) or NewFile, so that
the caller can tell an empty file from a missing one.
Regex, Match, Element, Atom, Caps (bre.rs, chapters 7 to 9). A
compiled pattern is a flat Vec<Element>. An Element is one atom, a starred
atom, an anchor, a group marker, or a backreference. An Atom is a literal
byte, ., or a bracket class. Caps holds nine group positions and is copied
on every recursive call, which is how backtracking discards failed captures. A
Match is a pair of byte offsets plus the captures.
Encoding (enc.rs, chapter 13). UTF-7, UTF-16 little-endian, or UTF-16
big-endian, as detected by a byte-order mark or the UTF-7 marker.
A.3 How a line of input travels
main calls parse_args, which returns a prompt and a filename, and passes
both to run_repl. If there is a filename, run_repl loads it with
load_file and prints the byte count. Then it loops.
Each iteration writes the prompt, unless the loop is in input mode, and reads
one line. It strips the \n and any \r before it, and nothing else. In input
mode, a lone . leaves the mode and any other line is appended after the
current line with Buffer::append_after. In command mode, the line goes to
dispatch.
dispatch trims the line and handles bare Enter, which prints the next line.
It calls Spec::parse, which takes any addresses off the front and returns the
rest. If nothing is left, the command is a bare address and prints that line.
Otherwise the rest is matched in two stages. The first stage matches the whole
remainder exactly, for commands that take no argument and for their long names:
q, a, i, c, d, p, n, l, j, H, Q. The second takes the
first character as the command letter and passes everything after it as the
argument: e, r, g, v, s, w, m, t. Anything else is unknown command.
Each command resolves its Spec with the default it needs, changes the buffer
through its methods, and returns an Action. g and v call dispatch
again, once per marked line. Back in the loop, the Action is printed, turned
into a ? line, used to enter input mode, or used to quit, and every arm except
Quit resets the unsaved-buffer warning.
A.4 Commands
| Command | Long form | Default address | Implemented by | Chapter |
|---|---|---|---|---|
| (address alone) | run_print | 4 | ||
| Enter | .+1 | dispatch | 3 | |
a | append | . | dispatch, then input mode | 3, 11 |
i | insert | . | dispatch, then input mode | 11 |
c | change | .,. | dispatch, then input mode | 11 |
d | delete | .,. | run_delete | 11 |
p | print | .,. | run_print | 3, 4 |
n | number | .,. | run_print | 4 |
l | list | .,. | run_print, render_list_line | 14 |
j | join | .,.+1 | run_join | 11 |
m dest | .,. | run_move | 11 | |
t dest | .,. | run_transfer | 11 | |
s/re/new/[g] | .,. | run_substitute | 10 | |
s | .,. | run_substitute, repeating the last | 10 | |
g/re/cmd | 1,$ | run_global | 12 | |
v/re/cmd | 1,$ | run_global | 12 | |
w [file] | 1,$ | run_write | 5, 13 | |
e [file] | run_edit | 13 | ||
r [file] | $ | run_read | 13 | |
q | quit | the loop | 5 | |
Q | the loop | 14 | ||
H | help | run_help | 14 |
A.5 Addresses and patterns
Addresses, from chapter 4: a line number, ., $, +n and -n from the
current line, + and - alone for one line, two addresses separated by a
comma, , for 1,$, ; for .,$, and a trailing comma for “to the end”.
m and t accept 0 as a destination.
Patterns, from chapters 7 to 9: literal characters, ., * after a single
atom, ^ and $ anchors, bracket expressions with ranges and negation and
POSIX’s rules for ] and -, backslash escapes, \( and \) groups,
backreferences \1 to \9, and octal escapes \000 to \077. Matching is
leftmost-longest, by recursive backtracking, on bytes.
Replacements, from chapter 10: & for the whole match, \1 to \9 for
groups, \& and \\ for literal characters, and octal escapes.
A.6 What it does not do
GNU ed commands that ved does not implement: u, =, k, f, x, z, !,
and h, and wq, which ved reads as w with the filename q (chapter 14).
Address forms it does not accept: search addresses, 'x marks, and offsets
attached to an address, such as $-5. Pattern features it does not support:
\(...\)*, \{n,m\}, character classes such as [[:alpha:]], and word
boundaries. Version 0.3.0 added search addresses and made matching work on
characters instead of bytes, and 0.4.0 fixed what this book found that behaves
differently from ed; chapters 19 to 22 have both lists.
Appendix B: The Slices
Chapter 1 listed the twelve slices the plan divided ved into. This appendix
records how they were built: which commit holds each one in ved’s history,
which crate under examples/ holds it in this book, and which chapter covers
it. The hashes are from the excelano/ved repository.
B.1 The twelve slices
| # | Slice | Commit | Date | Crate | Chapter |
|---|---|---|---|---|---|
| 1 | REPL loop, -p/--prompt | 0851663 | 2026-04-10 | ch02-repl | 2 |
| 2 | Buffer, a, ., p, ,p | d766818 | 2026-04-10 | ch03-buffer | 3 |
| 3 | Addresses, current line, n | d766818 | 2026-04-10 | ch04-addresses | 4 |
| 4 | w and q, the double q | d766818 | 2026-04-10 | ch05-write | 5 |
| 5a | The regex engine, step 1 | 515d4b9 | 2026-04-11 | ch07-pike | 7 |
| 5a | The regex engine, steps 2 to 5 | 62c33ad | 2026-04-12 | ch08-bre | 8, 9 |
| 5b | s | dec3f54 | 2026-04-12 | ch10-substitute | 10 |
| 6 | d and i | 7f3369b | 2026-04-12 | ch11-editing | 11 |
| 7 | g and v | c107e27 | 2026-04-12 | ch12-global | 12 |
| 8 | Long-form aliases | a4539c4 | 2026-04-12 | ch13-files | 14 |
| 9 | Confirmations, Q | a4539c4 | 2026-04-12 | ch13-files | 14 |
| 10 | H | a4539c4 | 2026-04-12 | ch13-files | 14 |
| 11 | Files, e, r | a4539c4 | 2026-04-12 | ch13-files | 13 |
| 12 | l | d8d02cb | 2026-06-11 | ved | 14 |
Slices two to four were one commit, and so were slices eight to eleven. The
crates for slices four, five, and onward match a commit file for file. The
crates for slices two and three, ch03-buffer and ch04-addresses, match no
commit: they were made for this book by taking the slice two-to-four commit
and removing the later slices from it, so that chapters 3 and 4 each have a
program that builds and runs at the point the chapter ends. Slices eight to
eleven have one crate between them, because the chapters that cover them, 13
and 14, describe that commit from two directions.
Slice 12 was planned with the others and built a month after the first
release, in 0.1.4, so its code is only in examples/ved.
The dates show the plan’s slices were unequal, as chapter 1 said they would be. Slices one to four took a day. The regex engine took two. Slices 5b to 11, seven slices including files and the help system, were built on one day.
B.2 After the plan
The slices ended at 0.1.0. Everything after was added in response to use:
| Version | Added | Chapter |
|---|---|---|
| 0.1.1 | c | 11 |
| 0.1.2 | A missing file is a new file | 13 |
| 0.1.3 | Greedy *, leftmost-longest | 7 |
| 0.1.4 | l (slice 12) | 14 |
| 0.1.5 | j, m, t, octal escapes, bare s | 10, 11 |
| 0.2.0 | Encoding warnings, the overwrite refusal | 13 |
| 0.2.1 | The command-letter panic, the tenth-group panic | 5, 9 |
| 0.3.0 | Search addresses, character-aware matching | 19 |
| 0.4.0 | The fixes for this book’s findings; -s, %, write, edit, read | 20, 21, 22 |
| 0.4.1 | l escapes and folding; the harness’s last differences | 22 |
examples/ved is 0.2.1, examples/ch19-living is 0.3.0, and examples/ch21-fixed is 0.4.0.
B.3 The crates
| Crate | Lines | Tests | State of the program |
|---|---|---|---|
ch02-repl | 123 | 0 | A loop that can quit |
ch03-buffer | 252 | 0 | Text in and out |
ch04-addresses | 487 | 0 | Addresses and ranges |
ch05-write | 609 | 0 | Saving and the unsaved-buffer guard |
ch07-pike | 832 | 23 | Pike’s matcher, not yet connected |
ch08-bre | 1,434 | 69 | The full engine, not yet connected |
ch10-substitute | 1,711 | 76 | s |
ch11-editing | 1,768 | 76 | d and i |
ch12-global | 1,864 | 76 | g and v |
ch13-files | 2,006 | 76 | Files, aliases, help, Q |
ved | 2,871 | 125 | Release 0.2.1 |
ch19-living | 3,625 | 185 | Release 0.3.0 |
ch21-fixed | 4,367 | 225 | Release 0.4.0 |
Every crate builds and runs on its own, with cargo run -p <crate> from
examples/, and cargo test there runs all of them.
Appendix C: From Empty Directory to Installed
The book in one table per stage, for a program of your own. Each row is a step, what it produces, and the chapter that explains it. The steps are in the order ved took them, adjusted where ved’s order turned out to be wrong.
C.1 Before any code
| Step | Produces | Chapter |
|---|---|---|
| Write the one-sentence description | A sentence to test every later decision against | 1 |
| Find the external specification: a standard, a file format, an existing program | Answers to “what should this do?” that are not opinions | 1 |
| Write the decision table, including what the program will not do | Constraints that answer questions in advance | 1 |
| Slice by capability, each slice a working program | A plan that can stop at any point and leave something usable | 1 |
cargo new, then fill in every metadata field in Cargo.toml | A manifest that can be published without edits | 1, 17 |
| Decide where reasoning goes: commit messages, not source | A repository that describes the present | 1, 16 |
C.2 Building it
| Step | Produces | Chapter |
|---|---|---|
Make main return an ExitCode, and parse arguments strictly | Exit statuses scripts can rely on | 2 |
| Make the command function return a value describing what to do | A command language testable without a terminal | 2 |
| Put each invariant behind a module boundary | State that only a few methods can change | 3 |
Keep one place where 1-indexed meets 0-indexed, and return Option for user-supplied positions | No off-by-one at the boundaries, no panic on a typo | 3 |
| Separate parsing from resolving | Errors reported against the right cause | 4 |
| Let each command choose its own default | No flag parameters on a shared function | 4 |
| Index strings by character, never by a literal byte offset into input you did not inspect | No panic on the first non-ASCII character | 5 |
| Build replacements before swapping them in | A failed operation that leaves the old state intact | 5, 13 |
| Hard parts first in isolation, with their own tests, before wiring them in | An engine that can be trusted when it is connected | 7, 8, 9 |
| Keep marks, cursors, and positions attached to the things they refer to | Loops that survive the operations they perform | 12 |
| Treat input from files as foreign: line endings, encodings, missing final newlines | Files that come back the way they went in | 13 |
C.3 Saying what happened
| Step | Produces | Chapter |
|---|---|---|
| Write every message in the user’s terms as the command is written | No sweep at the end | 5, 14 |
| Route each kind of output through one function | A consistent voice, and a plural that is right everywhere | 14 |
| Distinguish requested output, confirmations, and errors in the types | A -s flag that is one line in the loop | 14 |
| Exit non-zero when a non-interactive run had an error | Scripts that can detect failure | 14 |
| Reject what you do not understand, in flags, suffixes, and arguments | Typos that fail instead of meaning something else | 10, 11, 14 |
C.4 Checking it
| Step | Produces | Chapter |
|---|---|---|
| Unit tests at the command boundary, asserting on state, not wording | A suite that does not fight message changes | 15 |
| One integration test per responsibility of the outer loop | Coverage of the layer unit tests cannot see | 15 |
| Expected values from the specification, never from running the code | Tests that can disagree with the code | 15 |
| A differential harness against the reference implementation | The disagreements nobody thought to test | 15 |
| A fuzzer over the input language | The crashes nobody would type on purpose | 15 |
| A benchmark of the data structure at ten times the expected size | A measured boundary instead of a feeling | 15 |
cargo fmt --check, cargo clippy -- -D warnings, cargo test in CI | A gate between a laptop and a release | 17 |
| Build on the declared minimum Rust version as well as stable | A rust-version that is true | 17 |
C.5 Writing it down
| Step | Produces | Chapter |
|---|---|---|
| README in the order of the reader’s questions: what, why, install, start, reference | The interface for everyone who is not you | 16 |
| Every terminal session captured from a real run, and re-run when the program changes | Documentation that cannot teach a command that does not exist | 16 |
| Module comments in the present tense; history in commit messages | Comments that stay true | 16 |
| Each fact stated once, and every other place pointing to it | Seven descriptions that cannot disagree | 16, 18 |
| A manual page | man working after apt install | 18 |
| A backlog sorted by why each item is not done | Decisions that are not re-argued | 19 |
C.6 Releasing it
| Step | Produces | Chapter |
|---|---|---|
| Pick the version by what changed for users, including behavior and output | A number that means something | 17 |
| Run everything checkable before the tag | No release that needs an immediate patch | 17 |
| Write the release notes from typed commit subjects | A release page that says what changed | 16, 17 |
| Tag, build every target, publish checksums | A release anyone can download and verify | 17 |
| Publish to crates.io | cargo install | 17, 18 |
C.7 Getting it to people
| Step | Produces | Chapter |
|---|---|---|
A Makefile whose install does not build | sudo make install that works | 18 |
A .deb with correct depends, and a signed apt repository | apt install, apt upgrade, and authenticity | 18 |
A WinGet manifest generated from Cargo.toml | winget install, with a description that matches | 18 |
| Add each channel only when someone needs it, with a way to tell whether they still do | Channels you can afford at every release | 18 |
| When a channel ends, say so where its users will look | Users who know where to go next | 19 |
C.8 After
| Step | Produces | Chapter |
|---|---|---|
| Read the program closely, as if writing a book about it | The findings the tests missed | 19 |
| Put each finding in the tracker the day it is made | Findings that get fixed | 19 |
| Stop data loss with a small fix first, then fix the design | A safe place to make the large change | 19 |
| Delete backlog items when they ship, and recheck the reasons on the rest | A backlog that describes what is left | 19 |
| Decide which reference wins when the specification, the original, and the implementation on your machine disagree | Bug reports nobody argues with | 20 |
| Fix one issue per commit, test first, with the expected value from the reference | A history that reads as the list of fixes | 21 |
| Run the harness and the fuzzer after the last fix, not the first | The bugs the fixes made | 21 |
| Write commit subjects that survive being turned into release notes | Notes that say what changed, in the user’s terms | 22 |
| Close an issue when users can see the fix, not when the code has it | A tracker that says what is still wrong for users | 22 |