A guarantee is only as strong as the one place in the code that enforces it. In this lesson you open the source tabs and find that place for each promise the ledger makes. The project is split so that each module owns one kind of decision, and data only moves forward once the module before it has checked it.
types.rs owns item validation. Item::try_from trims, checks length and characters, and lowercases. Draft has public fields so the parser can fill it, but Batch has private fields and only one constructor, Draft::validate(self). Because validate consumes the draft, nothing can keep using an unchecked draft after it has been turned into a batch, and every &Batch the ledger receives is valid by construction. Checking once at the boundary and then carrying the proof in the type is what "parse, don't validate" means.
codec.rs bounds each input line to 256 bytes before it allocates the whole line, then parses a complete batch or nothing. ParseError has its own variants for syntax and numbers, and wraps a ValidationError from types.rs, exposing it through source as on Day 5.
ledger.rs holds the state. apply checks receipts first, then the receipt limit, then stages a clone of the stock, validates each staged quantity with checked arithmetic and the owned Rule, and only then commits stock and records the ordered changes. Its errors live in a separate ApplyError, because they are about state, not about text.
app.rs is the console loop. It turns both error types into the same Line N: message output and prints the final report through the borrowed entries iterator.
lib.rs declares the modules for Cargo. The browser compiles a single file, so main.rs uses include!("lib.rs") to paste those same module declarations into one binary. Both builds run identical code.
Trace a normalized retry
Trace normalized retriesRustinclude!("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:2
1 widget:2
1 widget:3
Text
Batch 1: AppliedBatch 1: ReplayedLine 3: batch ID was used for different changesStockwidget=2Receipts: 1
Line 2 is spelled differently from line 1, yet it replays. The comparison in apply never sees spelling: by the time a Batch exists, both names have become the same Item.
Trace the parser's all-or-nothing rule
The parser applies the same atomic idea to text that the ledger applies to state: a batch with one bad change produces no batch at all.
Trace whitespace and partial parsesRustinclude!("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 a:1
2 b:1;c:x
3 b:1;;c:1
4 B :2 ; c: 3
Text
Batch 1: AppliedLine 2: invalid batch ID or deltaLine 3: use ID item:delta;item:deltaBatch 4: AppliedStocka=1b=2c=3Receipts: 2
Line 2's first change, b:1, was valid, but c:x failed, so parse returned an error and the ledger never saw b. Line 3 has an empty part between two semicolons, which has no : and is a syntax error. Line 4 shows the trimming rules: spaces around names, deltas and separators are all accepted, and B normalizes to b.
Design choices worth questioning
Item::try_from uses a Cow to lowercase only when an uppercase byte is present. Because Item stores an owned String, the borrowed case still allocates at into_owned. The Cow saves a second allocation in the uppercase case and makes the "change only if needed" decision explicit, but a plain to_ascii_lowercase() would cost the same single allocation here. The pattern pays off fully when the caller can keep the borrowed form, as in the Day 2 lesson on Cow.
The ledger stores its rule as Box<dyn Rule>. That keeps Ledger a plain, non-generic type that can swap rules at runtime, at the cost of one dynamic call per change. A generic Ledger<R: Rule> would let the compiler inline the rule but would make every function that touches a ledger generic too.
The rule is also called on staged values, including values from batches that later fail. A boxed Rule could keep internal state through interior mutability, such as a counter in a Cell, and that state would not roll back. The transaction protects only the ledger's own stock and receipts; side effects inside a rule are the rule author's responsibility. The supplied MaxQuantity only reads its limit, so it is safe.
Exercise
Trace the accepted payload
Explain why the second line of the first trace replays even though its spelling differs from the first. Then explain why reversing two different changes under the same ID produces a conflict. Find where the receipt is recorded relative to the stock commit, and say what would go wrong if the two lines were swapped and a later step could fail.
Hint 1: the idea
The receipt stores validated Change values in their original order. Spelling has been normalized away before the ledger compares anything.
Hint 2: a first step
Find Item::try_from in types.rs and the comparison between previous and batch.changes() in ledger.rs.
Worked solution
Both spellings become the same owned Item before reaching the ledger, so the identical normalized changes match the stored receipt. Vec equality compares elements in order, so reversed changes conflict, which is correct because the order of changes can change the outcome when a limit is involved. The receipt insertion follows the stock replacement, after every staged change has passed, and recoverable validation errors return before either statement. Both commit statements are infallible today, so swapping them changes nothing yet; but if a fallible step were ever added between them, recording the receipt first could leave a receipt for a batch whose stock never changed, and its retry would replay a change that never happened.
Completion is saved in this browser only. It does not measure mastery.