Skip to content

Add a Stock Query and Use Cargo

The Course
•
30 min study

A design proves itself when you change it. In this lesson you add a feature to the stock ledger, a low-stock line in the report, and notice how little of the code you need to touch. The ledger already exposes entries(), a borrowed iterator over (&Item, u32) pairs in name order, exactly like the Day 5 query. Because it borrows instead of copying and hides the BTreeMap behind impl Iterator, a new report can be built on it without changing ledger.rs at all, and without any risk to the stock: a shared borrow cannot modify anything.

Then you download the project and run it with Cargo, which is where a library like this would actually live.

Exercise

Report low stock

After the entry loop in app.rs and before the receipts line, print the names of items with a quantity below 3, sorted by name. Use Low stock: none when no items match. Use the ledger’s entries iterator and keep the existing stock unchanged. For the sample, the line should be Low stock: gadget. "Below 3" is strict: an item with exactly 3 units is not low.

Your working space Rust
include!("lib.rs"); fn main() -> std::io::Result<()> { app::run(std::io::stdin().lock(), std::io::stdout().lock()) } pub mod app; pub mod codec; pub mod ledger; pub mod types; #[cfg(test)] mod checks; #[cfg(test)] mod tests { #[test] fn ledger_contract() { super::checks::run(); } } use std::borrow::Cow; use std::fmt; pub const MAX_CHANGES: usize = 8; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Item(String); #[derive(Clone, Debug, PartialEq, Eq)] pub enum ValidationError { Item, ZeroDelta, ZeroId, BatchSize, } impl fmt::Display for ValidationError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { let message = match self { Self::Item => "use an item of 1–24 ASCII letters, digits, hyphens or underscores", Self::ZeroDelta => "delta must be nonzero", Self::ZeroId => "batch ID must be positive", Self::BatchSize => "use 1–8 changes per batch", }; formatter.write_str(message) } } impl std::error::Error for ValidationError {} impl TryFrom<&str> for Item { type Error = ValidationError; fn try_from(text: &str) -> Result<Self, Self::Error> { let text = text.trim(); if text.is_empty() || text.len() > 24 || !text.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_') { return Err(ValidationError::Item); } let normalized: Cow<'_, str> = if text.bytes().any(|byte| byte.is_ascii_uppercase()) { Cow::Owned(text.to_ascii_lowercase()) } else { Cow::Borrowed(text) }; Ok(Self(normalized.into_owned())) } } impl Item { pub fn as_str(&self) -> &str { &self.0 } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Change { item: Item, delta: i64, } impl Change { pub fn new(item: Item, delta: i64) -> Result<Self, ValidationError> { if delta == 0 { return Err(ValidationError::ZeroDelta); } Ok(Self { item, delta }) } pub fn item(&self) -> &Item { &self.item } pub fn delta(&self) -> i64 { self.delta } } pub struct Draft { pub id: u32, pub changes: Vec<Change>, } #[derive(Debug)] pub struct Batch { id: u32, changes: Vec<Change>, } impl Draft { pub fn validate(self) -> Result<Batch, ValidationError> { if self.id == 0 { return Err(ValidationError::ZeroId); } if self.changes.is_empty() || self.changes.len() > MAX_CHANGES { return Err(ValidationError::BatchSize); } Ok(Batch { id: self.id, changes: self.changes }) } } impl Batch { pub fn id(&self) -> u32 { self.id } pub fn changes(&self) -> &[Change] { &self.changes } } use crate::types::{Batch, Change, Item}; use std::collections::BTreeMap; use std::fmt; #[derive(Debug, PartialEq, Eq)] pub enum ApplyError { RetryConflict, ReceiptLimit, Arithmetic, Quantity, Policy, ItemLimit, } impl fmt::Display for ApplyError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { let message = match self { Self::RetryConflict => "batch ID was used for different changes", Self::ReceiptLimit => "receipt limit reached", Self::Arithmetic => "arithmetic overflow", Self::Quantity => "quantity must fit a nonnegative u32", Self::Policy => "quantity rejected by policy", Self::ItemLimit => "item limit reached", }; formatter.write_str(message) } } impl std::error::Error for ApplyError {} pub trait Rule { fn allows(&self, item: &Item, quantity: u32) -> bool; } pub struct MaxQuantity(pub u32); impl Rule for MaxQuantity { fn allows(&self, _item: &Item, quantity: u32) -> bool { quantity <= self.0 } } #[derive(Debug, PartialEq, Eq)] pub enum Outcome { Applied, Replayed, } pub struct Ledger { stock: BTreeMap<Item, u32>, receipts: BTreeMap<u32, Vec<Change>>, rule: Box<dyn Rule>, max_items: usize, max_receipts: usize, } impl Ledger { pub fn new(rule: Box<dyn Rule>, max_items: usize, max_receipts: usize) -> Self { Self { stock: BTreeMap::new(), receipts: BTreeMap::new(), rule, max_items, max_receipts } } pub fn apply(&mut self, batch: &Batch) -> Result<Outcome, ApplyError> { if let Some(previous) = self.receipts.get(&batch.id()) { return if previous == batch.changes() { Ok(Outcome::Replayed) } else { Err(ApplyError::RetryConflict) }; } if self.receipts.len() >= self.max_receipts { return Err(ApplyError::ReceiptLimit); } let mut staged = self.stock.clone(); for change in batch.changes() { let old = i64::from(*staged.get(change.item()).unwrap_or(&0)); let next = old.checked_add(change.delta()).ok_or(ApplyError::Arithmetic)?; let next = u32::try_from(next).map_err(|_| ApplyError::Quantity)?; if !self.rule.allows(change.item(), next) { return Err(ApplyError::Policy); } staged.insert(change.item().clone(), next); if staged.len() > self.max_items { return Err(ApplyError::ItemLimit); } } self.stock = staged; self.receipts.insert(batch.id(), batch.changes().to_vec()); Ok(Outcome::Applied) } pub fn entries(&self) -> impl Iterator<Item = (&Item, u32)> { self.stock.iter().map(|(item, quantity)| (item, *quantity)) } pub fn receipt_count(&self) -> usize { self.receipts.len() } } use crate::types::{Batch, Change, Draft, Item, ValidationError, MAX_CHANGES}; use std::fmt; use std::io::{self, BufRead, Read}; pub const MAX_LINE_BYTES: usize = 256; #[derive(Debug)] pub enum ParseError { Syntax, Number, Validation(ValidationError), } impl fmt::Display for ParseError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Syntax => formatter.write_str("use ID item:delta;item:delta"), Self::Number => formatter.write_str("invalid batch ID or delta"), Self::Validation(error) => write!(formatter, "{error}"), } } } impl std::error::Error for ParseError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Self::Validation(error) => Some(error), _ => None, } } } impl From<ValidationError> for ParseError { fn from(error: ValidationError) -> Self { Self::Validation(error) } } pub fn parse(text: &str) -> Result<Batch, ParseError> { let text = text.trim(); let (id, body) = text.split_once(char::is_whitespace).ok_or(ParseError::Syntax)?; let id = id.parse::<u32>().map_err(|_| ParseError::Number)?; let mut changes = Vec::new(); for part in body.split(';') { if changes.len() == MAX_CHANGES { return Err(ValidationError::BatchSize.into()); } let (item, delta) = part.trim().split_once(':').ok_or(ParseError::Syntax)?; let item = Item::try_from(item)?; let delta = delta.trim().parse::<i64>().map_err(|_| ParseError::Number)?; changes.push(Change::new(item, delta)?); } Ok(Draft { id, changes }.validate()?) } pub fn read_line(input: &mut impl BufRead) -> io::Result<Option<String>> { let mut bytes = Vec::new(); let count = input.take((MAX_LINE_BYTES + 1) as u64).read_until(b'\n', &mut bytes)?; if count == 0 { return Ok(None); } if count > MAX_LINE_BYTES { return Err(io::Error::new(io::ErrorKind::InvalidData, "line exceeds 256 bytes")); } let line = String::from_utf8(bytes) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "input must be UTF-8"))?; Ok(Some(line)) } use crate::codec; use crate::ledger::{Ledger, MaxQuantity}; use std::io::{self, BufRead, Write}; pub fn run(mut input: impl BufRead, mut output: impl Write) -> io::Result<()> { let mut ledger = Ledger::new(Box::new(MaxQuantity(1000)), 32, 32); let mut line_number = 0; while let Some(line) = codec::read_line(&mut input)? { line_number += 1; if line.trim().is_empty() { continue; } match codec::parse(&line) { Ok(batch) => match ledger.apply(&batch) { Ok(outcome) => writeln!(output, "Batch {}: {outcome:?}", batch.id())?, Err(error) => writeln!(output, "Line {line_number}: {error}")?, }, Err(error) => writeln!(output, "Line {line_number}: {error}")?, } } writeln!(output, "Stock")?; for (item, quantity) in ledger.entries() { writeln!(output, "{}={quantity}", item.as_str())?; } writeln!(output, "Receipts: {}", ledger.receipt_count())?; output.flush() } 1 Widget:5;gadget:2 2 widget:1;gadget:-3 1 widget:5;gadget:2 3 widget:-2
Hint 1: the idea

The map’s iterator already has the order the report needs, so there is nothing to sort.

Hint 2: a first step

Filter entries by quantity, map the matching items to their borrowed names, and collect those names into a Vec<&str>. join on a slice of &str builds the comma-separated list.

Worked solution

Insert this before the line that prints the receipt count.

Rust
let low: Vec<&str> = ledger.entries()
    .filter(|(_, quantity)| *quantity < 3)
    .map(|(item, _)| item.as_str())
    .collect();
let label = if low.is_empty() { String::from("none") } else { low.join(", ") };
writeln!(output, "Low stock: {label}")?;

Test an empty ledger, an item with exactly 3 units, and two low-stock names added in reverse alphabetic order, such as 1 zebra:1;alpha:2, which should print Low stock: alpha, zebra. An item that drops to zero, such as widget after 3 widget:-5, still has its slot and so counts as low stock.

If you keep this extension, run the check entry from the previous lesson as well: check_stream compares the complete application transcript, so it fails until you add the new Low stock: none line to its expected text. That failure is the transcript check doing its job, since the program's output really did change.

Where should the query live?

The solution puts the filter in app.rs. The alternative is a library method such as Ledger::below(&self, limit: u32) returning impl Iterator<Item = &Item>. Both are reasonable, and the choice depends on who needs the rule. If "low stock" is a policy of this one console report, it belongs in the application, and the library stays smaller and more general. If several callers need the same definition, a library method prevents each of them from writing a slightly different filter, with one using < and another <=. A good default is to start in the application and move code into the library once a second caller appears.

Notice also what the solution does not do. It collects borrowed &str names rather than cloning them into Strings, because the list is used immediately while the ledger is still alive. It does not sort, because entries already yields names in order. And it checks is_empty before joining, so the "none" case is a deliberate branch rather than an empty string after a colon.

Run the library locally

Download the original stock ledger. Extract the ZIP and open a terminal in the directory containing Cargo.toml. With Rust 2024 support installed, run the application, check binary and library test.

Shell
cargo run --quiet < sample.txt
cargo run --quiet --bin check-ledger
cargo test --lib

Cargo.toml declares one library and two binaries. The library's root is lib.rs, which declares the four modules. The stock-ledger binary is main.rs, the default for cargo run, and the check-ledger binary is check.rs. Locally, both binaries could simply use the library crate. They use include!("lib.rs") instead so the exact same files also compile as a single browser program; that is a constraint of this course, not a pattern you need in your own projects.

The library test is enabled by #[cfg(test)], which compiles the checks module and the tests module only for cargo test, and #[test] marks ledger_contract as a test function. That one test calls checks::run, the same routine as the check binary, so the browser and Cargo verify the same guarantees.

Another crate on your machine can use the ledger by adding a path dependency, such as stock-ledger = { path = "../stock-ledger" }, to its own Cargo.toml. Cargo turns the hyphen into an underscore for the crate name, so that code imports stock_ledger::ledger::Ledger. Only the items marked pub are visible from outside, which is why Batch can be constructed only through Draft::validate, in every crate that uses it.

Keep the copy you changed

Apply your low-stock extension to the downloaded app.rs, update the transcript in checks.rs, and run all three commands again. Seeing cargo test fail before the transcript update, then pass after it, is the same evidence loop you practiced on Day 6, now with real tooling.

Was this article helpful?

Your response is saved on this device.