A text format is a contract between the code that writes it and the code that reads it, often written years apart. "Print the stock somehow" is not a contract. You need explicit rules for separators, ordering, duplicates and the end of the text, or two snapshots of the same stock can differ byte for byte. That breaks everything people do with snapshots: comparing them in tests, diffing them in review, hashing them to detect change.
A format is canonical when every value has exactly one valid text. This lesson's snapshot is a sequence of name=quantity lines, sorted by name, each ending in a newline, including the last. Names are one or more lowercase ASCII letters, which can never contain = or a newline, so the separators are unambiguous without escaping. BTreeMap supplies the sorted order for free; a HashMap would print in an order that can change between runs.
Be precise about what the format carries, too. A snapshot holds stock values only. Receipts are separate state, so restoring a snapshot cannot restore replay protection. A round trip proves only what is inside the format.
Predict and run
Does insertion order change the output?
use std::collections::BTreeMap;
fn encode(stock: &BTreeMap<String, u32>) -> String {
stock.iter().map(|(name, quantity)| format!("{name}={quantity}\n")).collect()
}
fn main() {
let stock = BTreeMap::from([(String::from("nut"), 2), (String::from("bolt"), 5)]);
print!("{}", encode(&stock));
}Check your prediction
bolt=5
nut=2The map sorted the keys when they were inserted, so iteration is already in name order. Reverse the two pairs in BTreeMap::from and compare the encoded String with ==: it is identical. Then add "Bolt" and predict where it lands. Uppercase letters sort before lowercase ones in byte order, which is one reason the format allows lowercase names only.
Writing is easy, reading is where the format leaks
encode produces only canonical text, but a decoder sees whatever it is given. The standard parsers are more forgiving than this format, and every forgiveness is a second spelling of the same value.
fn main() {
for text in ["5", "+5", "05", " 5"] {
println!("{text:?} as u32: {:?}", text.parse::<u32>());
}
let lines: Vec<&str> = "bolt=5\r\nnut=2".lines().collect();
println!("lines: {lines:?}");
}"5" as u32: Ok(5)
"+5" as u32: Ok(5)
"05" as u32: Ok(5)
" 5" as u32: Err(ParseIntError { kind: InvalidDigit })
lines: ["bolt=5", "nut=2"]+5 and 05 both parse to 5, and lines accepts Windows line endings and a missing final newline. A decoder built on these tools reads more than the format allows. You then have a choice. A lenient decoder accepts every spelling and normalizes on the next write, which is friendly to hand-edited files. A strict decoder rejects anything that is not canonical, which is right when the text is a fingerprint, because two different texts would otherwise mean the same stock.
You do not need to re-implement every rule to get strictness. Decode leniently, encode the result, and compare with the input. If they differ, the input was not canonical. This round-trip test is short, and it cannot drift out of sync with the encoder because it uses the encoder.
Duplicates are ambiguity, not a typo
Given bolt=5 and bolt=6, a decoder that keeps the last value silently picks one meaning. BTreeMap::insert returns the previous value, so checking is_some() turns that ambiguity into an error at no extra cost.
Practice
Your turn
Write decode(text: &str) -> Result<BTreeMap<String, u32>, &'static str>. Reject a line without = as "separator", an empty or non-lowercase name as "name", a bad number as "quantity", and a repeated name as "duplicate". Then write is_canonical(text: &str) -> bool using the round-trip test. Print decode(text).map(|s| encode(&s)) for:
"nut=2\nbolt=5\n", which should becomeOk("bolt=5\nnut=2\n")."bolt=5\nbolt=6\n","Bolt=5\n","bolt=x\n"and"bolt\n", which each fail with their reason.
Then print is_canonical for "bolt=5\nnut=2\n" (true), "nut=2\nbolt=5\n", "bolt=05\n" and "bolt=5" (all false).
fn main() {
// Implement decode and encode, then check valid and duplicate input.
}Hint 1: the idea
Build a new map and return it only after every line passes. is_canonical should be one expression: decode, encode, compare.
Hint 2: a first step
Use line.split_once('=') for the separator and name.bytes().all(|byte| byte.is_ascii_lowercase()) for the name, remembering that all is true for an empty name.
Worked solution
use std::collections::BTreeMap;
fn decode(text: &str) -> Result<BTreeMap<String, u32>, &'static str> {
let mut stock = BTreeMap::new();
for line in text.lines() {
let (name, quantity) = line.split_once('=').ok_or("separator")?;
if name.is_empty() || !name.bytes().all(|byte| byte.is_ascii_lowercase()) {
return Err("name");
}
let quantity = quantity.parse::<u32>().map_err(|_| "quantity")?;
if stock.insert(name.to_owned(), quantity).is_some() {
return Err("duplicate");
}
}
Ok(stock)
}
fn encode(stock: &BTreeMap<String, u32>) -> String {
stock.iter().map(|(name, quantity)| format!("{name}={quantity}\n")).collect()
}
fn is_canonical(text: &str) -> bool {
decode(text).is_ok_and(|stock| encode(&stock) == text)
}
fn main() {
for text in ["nut=2\nbolt=5\n", "bolt=5\nbolt=6\n", "Bolt=5\n", "bolt=x\n", "bolt\n"] {
println!("{text:?} -> {:?}", decode(text).map(|stock| encode(&stock)));
}
for text in ["bolt=5\nnut=2\n", "nut=2\nbolt=5\n", "bolt=05\n", "bolt=5"] {
println!("canonical {text:?}: {}", is_canonical(text));
}
}"nut=2\nbolt=5\n" -> Ok("bolt=5\nnut=2\n")
"bolt=5\nbolt=6\n" -> Err("duplicate")
"Bolt=5\n" -> Err("name")
"bolt=x\n" -> Err("quantity")
"bolt\n" -> Err("separator")
canonical "bolt=5\nnut=2\n": true
canonical "nut=2\nbolt=5\n": false
canonical "bolt=05\n": false
canonical "bolt=5": falseThe decoder alone is lenient about order, leading zeros and the final newline, and is_canonical catches all three without a single extra rule. One boundary is worth noticing: the empty string is canonical, because it is exactly the encoding of empty stock. The next lesson reads the same stock through a borrowed query instead of a copy.
Completion is saved in this browser only. It does not measure mastery.