Skip to content

Checkpoint: Decode, Query and Report Stock

The Course
•
45 min study

Day 5 was about state crossing a boundary without being disturbed: an error that keeps its cause, a format with exactly one spelling per value, and a query that borrows instead of copying. This checkpoint puts all three in one round trip. Text comes in and is decoded into stock, or rejected with an error that says which line failed and why. A report goes out, built from the borrowed query, in the same format the decoder accepts. If the pieces agree, every report can be decoded again.

What you will use

  • An error with a source: a DecodeError enum whose quantity variant stores the line number and the ParseIntError, and returns it from Error::source, while Display describes only its own level.
  • A strict decoder by round trip: decode leniently, encode the result, and reject the input if the two texts differ.
  • A borrowed query: above yields (&str, u32) pairs in name order without copying the map.
  • Shared borrows: &self methods leave the stock readable after every report.

Plan before you type

  1. Design DecodeError first: one variant for a line with no =, one for a quantity that does not parse, one for text that is not canonical. Decide which variants carry a line number and which one has a source.
  2. Implement Display and Error for it.
  3. Write Stock::decode(text): number the lines, split each one, parse the quantity, and only then check the whole text against encode.
  4. Write report(&self, threshold) on top of above, and nothing else.
  5. In main, decode a canonical snapshot, print reports at the boundary thresholds, decode a report back into stock, then print each rejected input with its whole cause chain.
Prove it can fail

Three mutations, three checks. Change > to >= in above: the report at threshold 5 should now include bolt=5. Remove the encode comparison from decode: nut=2\nbolt=5\n and bolt=05\n should now be accepted, and your expect("rejected") must panic. Make source return None for every variant: the caused by line should disappear. If any of these goes unnoticed, compare complete strings instead of checking is_err() or contains.

Mistakes worth checking for

  • The cause prints twice: Display for the quantity variant includes the ParseIntError text, and the chain walker prints it again from source.
  • Every error says line 1: the number was computed outside the loop, or counted from 0.
  • bolt=05 is accepted: the canonical check is missing, or it compares the stock instead of the text. "05".parse::<u32>() is Ok(5), so only the round trip catches it.
  • A report fails to decode: the lines were joined with "\n" instead of each ending in one, so the last line has no newline and the text is not canonical.
  • The report owns the stock: report(self, ...) takes self by value, and the stock is unusable afterward.
Exercise

Your turn

Add DecodeError, decode and report to Stock. Decode "bolt=5\nnut=2\nwasher=8\n" and assert that encoding it gives the same text. Print the {:?} form of report(t) for t of 1, 5 and 8. Decode report(4) again and assert it holds two items. Then decode each of "bolt=5\nnut\n", "bolt=5\nnut=two\n", "nut=2\nbolt=5\n" and "bolt=05\n", and print each error followed by one caused by: line per source. Finally print the number of items still in the first stock. The output should be:

Text
1: "bolt=5\nnut=2\nwasher=8\n"
5: "washer=8\n"
8: ""
error: line 2: expected name=quantity
error: line 2: bad quantity
caused by: invalid digit found in string
error: snapshot is not in canonical form
error: snapshot is not in canonical form
Items still stored: 3
Your working space Rust
use std::collections::BTreeMap;

struct Stock(BTreeMap<String, u32>);

impl Stock {
    fn above(&self, threshold: u32) -> impl Iterator<Item = (&str, u32)> + '_ {
        self.0.iter()
            .filter(move |(_, quantity)| **quantity > threshold)
            .map(|(name, quantity)| (name.as_str(), *quantity))
    }

    fn encode(&self) -> String {
        self.0.iter().map(|(name, quantity)| format!("{name}={quantity}\n")).collect()
    }
}

fn main() {
    // Add DecodeError, decode and report, then check the round trip and the errors.
}
Hint 1: the idea

Each layer reports only its own failure. The decoder knows the line number, so it wraps the ParseIntError with it instead of replacing it. The report is the query plus formatting, so it cannot disagree with above, and because it uses the snapshot format, decoding it is a free test of both.

Hint 2: a first step

Write the error type and its two trait implementations before decode, and test them by building a DecodeError by hand from "two".parse::<u32>().unwrap_err() and walking its source chain. In decode, map_err with a closure is where the line number and the cause meet.

Worked solution
Run the solution Rust
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;

struct Stock(BTreeMap<String, u32>);

impl Stock {
    fn above(&self, threshold: u32) -> impl Iterator<Item = (&str, u32)> + '_ {
        self.0.iter()
            .filter(move |(_, quantity)| **quantity > threshold)
            .map(|(name, quantity)| (name.as_str(), *quantity))
    }

    fn encode(&self) -> String {
        self.0.iter().map(|(name, quantity)| format!("{name}={quantity}\n")).collect()
    }
}

#[derive(Debug)]
enum DecodeError {
    MissingEquals { line: usize },
    BadQuantity { line: usize, cause: ParseIntError },
    NotCanonical,
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DecodeError::MissingEquals { line } => write!(f, "line {line}: expected name=quantity"),
            DecodeError::BadQuantity { line, .. } => write!(f, "line {line}: bad quantity"),
            DecodeError::NotCanonical => write!(f, "snapshot is not in canonical form"),
        }
    }
}

impl Error for DecodeError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            DecodeError::BadQuantity { cause, .. } => Some(cause),
            _ => None,
        }
    }
}

impl Stock {
    fn decode(text: &str) -> Result<Stock, DecodeError> {
        let mut items = BTreeMap::new();
        for (index, line) in text.lines().enumerate() {
            let number = index + 1;
            let (name, quantity) = line.split_once('=')
                .ok_or(DecodeError::MissingEquals { line: number })?;
            let quantity = quantity.parse::<u32>()
                .map_err(|cause| DecodeError::BadQuantity { line: number, cause })?;
            items.insert(String::from(name), quantity);
        }
        let stock = Stock(items);
        if stock.encode() != text {
            return Err(DecodeError::NotCanonical);
        }
        Ok(stock)
    }

    fn report(&self, threshold: u32) -> String {
        self.above(threshold)
            .map(|(name, quantity)| format!("{name}={quantity}\n"))
            .collect()
    }
}

fn explain(error: &DecodeError) {
    println!("error: {error}");
    let mut current = error.source();
    while let Some(cause) = current {
        println!("caused by: {cause}");
        current = cause.source();
    }
}

fn main() {
    let snapshot = "bolt=5\nnut=2\nwasher=8\n";
    let stock = Stock::decode(snapshot).expect("canonical snapshot");
    assert_eq!(stock.encode(), snapshot);
    for threshold in [1, 5, 8] {
        println!("{threshold}: {:?}", stock.report(threshold));
    }
    assert_eq!(stock.report(5), "washer=8\n");
    let partial = Stock::decode(&stock.report(4)).expect("a report is a snapshot");
    assert_eq!(partial.0.len(), 2);

    for text in ["bolt=5\nnut\n", "bolt=5\nnut=two\n", "nut=2\nbolt=5\n", "bolt=05\n"] {
        explain(&Stock::decode(text).err().expect("rejected"));
    }
    println!("Items still stored: {}", stock.0.len());
}
Text
1: "bolt=5\nnut=2\nwasher=8\n"
5: "washer=8\n"
8: ""
error: line 2: expected name=quantity
error: line 2: bad quantity
caused by: invalid digit found in string
error: snapshot is not in canonical form
error: snapshot is not in canonical form
Items still stored: 3

The quantity variant's Display names the line and the task, and source hands out the ParseIntError, so the walker prints each fact once. The two canonical failures are different spellings that parse cleanly, out of order and with a leading zero; only comparing with encode catches them, and that check cannot drift from the encoder because it is the encoder. report(4) decodes without error because it is built from the same format, which is the round trip the snapshot lesson promised. Every method on Stock takes &self, so the first stock still holds three items at the end. Day 6 asks how you know checks like these would catch a real bug.

Was this article helpful?

Your response is saved on this device.