Collections and iterators
Count requests with HashMap and BTreeMap, rank the top paths and clients with an iterator chain, and meet lifetimes where the code needs them.
- lesson
- 05 of 08
- read
- 15 min
tally still prints individual lines. This lesson turns it into a summarizer: counts per status class, per path and per client address, with the five most frequent paths and clients listed. That takes two kinds of map and an iterator chain that ranks their contents. It is also where lifetimes become visible, first in the ranking code and then in the parser.
Counting with maps
A new module holds the running totals:
use std::collections::{BTreeMap, HashMap};
use crate::entry::{Entry, StatusClass};
pub struct Summary {
pub requests: u64,
pub malformed: u64,
pub bytes: u64,
pub status: BTreeMap<StatusClass, u64>,
paths: HashMap<String, u64>,
clients: HashMap<String, u64>,
}
impl Summary {
pub fn new() -> Summary {
Summary {
requests: 0,
malformed: 0,
bytes: 0,
status: BTreeMap::new(),
paths: HashMap::new(),
clients: HashMap::new(),
}
}
pub fn record(&mut self, entry: &Entry) {
self.requests += 1;
self.bytes += entry.bytes.unwrap_or(0);
*self.status.entry(entry.class()).or_insert(0) += 1;
*self.paths.entry(entry.path.clone()).or_insert(0) += 1;
*self.clients.entry(entry.addr.clone()).or_insert(0) += 1;
}
}A path that begins with crate:: starts at the root of the crate; this is how one module refers to another. record takes &mut self because it changes the summary, and unwrap_or(0) treats a missing size as zero bytes.
HashMap<K, V> is a hash table. entry(key).or_insert(0) looks the key up once and returns a mutable reference to its value, inserting a zero first if the key is new. The leading * dereferences that reference, so that += 1 applies to the number. BTreeMap offers the same interface and keeps its keys in sorted order.
The two maps ask different things of a key. A HashMap key must implement Hash and Eq; a BTreeMap key must implement Ord. String has all of them. StatusClass needs two more derives:
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum StatusClass {A derived Ord orders an enum’s variants as they are declared, so iterating over status yields the 1xx class before 2xx with no further work.
Which map to choose comes down to iteration order. Here is what a loop over the paths map printed on two consecutive runs of the program, with the field made pub for the experiment:
for (path, count) in &summary.paths {
println!("{count:>8} {path}");
} 4 /
2 /favicon.ico
1 /about
3 /static/app.css
1 /admin
3 /api/orders
2 /static/app.jsAnd the second run:
4 /
2 /favicon.ico
3 /static/app.css
3 /api/orders
1 /about
2 /static/app.js
1 /adminA HashMap seeds its hash function randomly, as a defense against input crafted to make keys collide, and its iteration order is arbitrary as a result. Anything printed from a HashMap has to be sorted first.
Ranking with an iterator chain
The top lists are built by one small type and one function, both added to summary.rs:
pub struct Count<'a> {
pub name: &'a str,
pub count: u64,
}fn top(counts: &HashMap<String, u64>, n: usize) -> Vec<Count<'_>> {
let mut ranked: Vec<Count> = counts
.iter()
.map(|(name, count)| Count {
name,
count: *count,
})
.collect();
ranked.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.name.cmp(b.name)));
ranked.truncate(n);
ranked
}Set the 'a and '_ aside for a moment. counts.iter() yields pairs of references, (&String, &u64). map transforms each pair with a closure, an anonymous function written inline with its parameters between | bars. Unlike a fn, a closure can also use variables from the scope around it. Here the parameter list |(name, count)| destructures the pair, and the body builds a Count. collect gathers the results into the collection named by the type annotation, a Vec<Count>.
Iterators are lazy. iter() and map() only describe the work, and nothing runs until collect asks for items. The chain then makes a single pass over the map, however many steps it has.
sort_by takes a closure that compares two elements. b.count.cmp(&a.count) puts larger counts first, and then_with breaks ties by name. The tie-break matters: without it, paths with equal counts would come out in hash order, and the report would differ from run to run. truncate keeps the first n.
A chain suits code that turns one sequence into another. The loop in run both updates the summary and prints warnings, and a for loop says that more plainly.
Lifetimes
Count stores a &str, and a struct that holds a reference has to declare a lifetime parameter. Count<'a> reads: a Count must not outlive the string its name points to. In top, those strings are the keys of the map, so the list that top returns borrows from the map. No name is copied. In exchange, the compiler will not let the map change while the list is in use.
The signature of top expresses this with '_, a placeholder for the lifetime the compiler infers. With one reference among the parameters there is one candidate, and the elision rules assign it to the output. Written out in full, the signature is fn top<'a>(counts: &'a HashMap<String, u64>, n: usize) -> Vec<Count<'a>>. Lifetime annotations never change how long a value lives. They describe how the lifetimes of inputs and outputs relate, so that the compiler can check every caller.
The parser has the mirror image of this problem. Entry owns addr and path as Strings: two allocations per line, for an entry that is dropped as soon as record returns. The fields could borrow from the line instead. Changing their types to &str is not enough:
error[E0106]: missing lifetime specifier
--> src/entry.rs:6:15
|
6 | pub addr: &str,
| ^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
5 ~ pub struct Entry<'a> {
6 ~ pub addr: &'a str,
|
...Apply the suggestion throughout entry.rs. Four places change:
#[derive(Debug)]
pub struct Entry<'a> {
pub addr: &'a str,
pub path: &'a str,
pub status: u16,
pub bytes: Option<u64>,
}impl Entry<'_> {pub fn parse_line(line: &str) -> Result<Entry<'_>, ParseError> { Ok(Entry {
addr,
path,
status,
bytes,
})The two .to_string() calls are gone, because addr and path already are slices of line. A return type of plain Entry would also compile, with a warning that “hiding a lifetime that’s elided elsewhere is confusing”. The <'_> is there for the human reader: it marks a return value that borrows from an argument.
An Entry now dies with its line, so the summary must own its keys. HashMap::entry wants an owned key on every call, which would mean one to_string() per line even though most lines repeat a key that is already in the map. Looking the key up by &str first avoids that:
fn bump(counts: &mut HashMap<String, u64>, key: &str) {
match counts.get_mut(key) {
Some(count) => *count += 1,
None => {
counts.insert(key.to_string(), 1);
}
}
}get_mut accepts a &str for a map keyed by String, so an allocation happens only for a key seen for the first time. The price is a second lookup in that case. Lesson 8 measures the difference.
The report
Summary gets two methods that expose the rankings, and record uses bump:
pub fn record(&mut self, entry: &Entry) {
self.requests += 1;
self.bytes += entry.bytes.unwrap_or(0);
*self.status.entry(entry.class()).or_insert(0) += 1;
bump(&mut self.paths, entry.path);
bump(&mut self.clients, entry.addr);
}
pub fn top_paths(&self, n: usize) -> Vec<Count<'_>> {
top(&self.paths, n)
}
pub fn top_clients(&self, n: usize) -> Vec<Count<'_>> {
top(&self.clients, n)
}The status classes need a printable name, in the impl StatusClass block:
pub fn label(self) -> &'static str {
match self {
StatusClass::Informational => "1xx",
StatusClass::Success => "2xx",
StatusClass::Redirection => "3xx",
StatusClass::ClientError => "4xx",
StatusClass::ServerError => "5xx",
StatusClass::Other => "other",
}
}In main.rs, the new module is declared and imported, and run prints the summary once all lines are in. main itself does not change.
mod entry;
mod error;
mod summary;
use std::env;
use std::fs;
use std::process;
use entry::parse_line;
use error::TallyError;
use summary::Summary;
fn run() -> Result<(), TallyError> {
let paths: Vec<String> = env::args().skip(1).collect();
if paths.is_empty() {
return Err(TallyError::NoInput);
}
let mut summary = Summary::new();
for path in &paths {
let contents = fs::read_to_string(path)?;
for (index, line) in contents.lines().enumerate() {
match parse_line(line) {
Ok(entry) => summary.record(&entry),
Err(err) => {
eprintln!("{path}:{}: {err}", index + 1);
summary.malformed += 1;
}
}
}
}
println!("{:<10}{:>12}", "requests", summary.requests);
println!("{:<10}{:>12}", "malformed", summary.malformed);
println!("{:<10}{:>12}", "bytes", summary.bytes);
println!();
println!("status");
for (class, count) in &summary.status {
println!(" {:<8}{:>12}", class.label(), count);
}
println!();
println!("top paths");
for item in summary.top_paths(5) {
println!("{:>8} {}", item.count, item.name);
}
println!();
println!("top clients");
for item in summary.top_clients(5) {
println!("{:>8} {}", item.count, item.name);
}
Ok(())
}In a format string, {:<10} pads a value to ten columns on the right and {:>12} pads to twelve on the left, which lines the numbers up.
cargo run -q -- access.logaccess.log:8: missing request
access.log:15: missing path
requests 16
malformed 2
bytes 152631
status
2xx 9
3xx 2
4xx 3
5xx 2
top paths
4 /
3 /api/orders
3 /static/app.css
2 /favicon.ico
2 /static/app.js
top clients
7 203.0.113.7
4 198.51.100.23
3 192.0.2.44
2 2001:db8::1f/api/orders and /static/app.css both have three requests, and they appear in the same order on every run.
The output format is now wired into run. The next lesson puts it behind a trait and adds a second format.
Exercises
- Requests for
/search?q=aand/search?q=bshould count as one path. Strip the query string inparse_linewithsplit_once('?'), without allocating. Add both requests to a copy of the sample file; the report should list/searchwith a count of 2. - Add a method
errors(&self) -> u64toSummarythat adds up the 4xx and 5xx counts withfilter,mapandsumonself.status.iter(), and print it as a fourth total. For the sample file the value is 5. - In
run, storesummary.top_paths(5)in a variable, then add the statementsummary.malformed += 1;before the loop that prints it. The compiler should refuse with E0506. Name the borrow that is still alive and the line that keeps it alive.