Come back to this page after a few days, not right after finishing the project. Remembering is easiest while everything is fresh, which is exactly why it teaches little then. Pulling an idea out of memory after you have partly forgotten it is what makes it stick. So close the other tabs, keep the hints collapsed, and write each answer before you look at anything.
Each of the three exercises below targets one design guarantee from the week: who owns text, a batch that fails without a trace, and a receipt that makes retries safe. Before you write code, answer its warm-up questions out loud or on paper. After it passes, change one input as suggested and say whether the guarantee still holds, and why. If you get stuck, reread only the lesson named in the section, then try again from a blank editor.
Choose the text owner
Warm-up, from the Day 2 Cow lesson: when can a function return a slice of its input, and when must it allocate? What does the caller learn from a return type of Cow<str> that it would not learn from String?
Your turn
Write normalize(text: &str) -> Cow<'_, str>. Trim surrounding whitespace and allocate only when ASCII lowercase letters must become uppercase. For " BOLT ", "bolt" and " Bolt ", print the input, the result and whether it is borrowed or owned. Expect one borrowed result and two owned ones, all equal to "BOLT".
fn main() {
// Return borrowed or owned text based on the requested change.
}Hint 1: the idea
Trimming can return a slice of the input. Changing byte values requires owned storage.
Hint 2: a first step
Trim first and keep the slice. Then ask one question of it, whether any byte would change, and let the answer pick the variant. To print the kind, match on a reference to the result so it is not moved.
Worked solution
use std::borrow::Cow;
fn normalize(text: &str) -> Cow<'_, str> {
let text = text.trim();
if text.bytes().any(|byte| byte.is_ascii_lowercase()) {
Cow::Owned(text.to_ascii_uppercase())
} else {
Cow::Borrowed(text)
}
}
fn main() {
for text in [" BOLT ", "bolt", " Bolt "] {
let result = normalize(text);
let kind = match &result {
Cow::Borrowed(_) => "borrowed",
Cow::Owned(_) => "owned",
};
println!("{text:?} -> {result:?} ({kind})");
}
}" BOLT " -> "BOLT" (borrowed)
"bolt" -> "BOLT" (owned)
" Bolt " -> "BOLT" (owned)The return type carries either a borrow of the input or a new allocation, and the caller pays for the allocation only when text really changed. The project lowercases instead of uppercasing; the direction is a format decision, the ownership reasoning is the same.
Change one input: what does normalize(" ") return, and which variant? An all-space input trims to the empty string, which contains no lowercase letters, so it is a borrowed empty slice. Decide whether a caller such as Item::try_from should reject it, and where.
Preserve state on rejection
Warm-up, from the Day 4 staging lesson: what is the single statement that commits a batch, and why can it not fail halfway? Why is an assertion on the returned Err not evidence of atomicity?
Your turn
The starter's apply updates the vector in place, and it returns the right error. Run it and look at the stored vector. First add an assertion that the batch [(0, 2), (1, -3)] against [5, 2] leaves the stored vector unchanged, and watch it fail. Then fix apply from memory so the batch fails atomically. Finally run the corrected batch [(0, 2), (1, -2)] and assert the final vector is [7, 0]. Print each result with the stored vector:
Err("out of range") [5, 2]
Ok(()) [7, 0]fn adjust(old: u32, delta: i64) -> Result<u32, &'static str> {
let next = i64::from(old).checked_add(delta).ok_or("overflow")?;
u32::try_from(next).map_err(|_| "out of range")
}
fn apply(stock: &mut Vec<u32>, changes: &[(usize, i64)]) -> Result<(), &'static str> {
for (index, delta) in changes {
let slot = stock.get_mut(*index).ok_or("unknown slot")?;
*slot = adjust(*slot, *delta)?;
}
Ok(())
}
fn main() {
let mut stock = vec![5, 2];
let result = apply(&mut stock, &[(0, 2), (1, -3)]);
println!("{result:?} {stock:?}");
}Hint 1: the idea
The first change succeeds and the second fails, so whatever the first change wrote must be thrown away. That is only possible if it never wrote to stock in the first place.
Hint 2: a first step
Before touching apply, keep a copy of the initial vector and compare it with the stored one after the error; it should fail, showing [7, 2]. Then decide what the loop should modify instead of stock, and which single statement makes the change visible.
Worked solution
fn adjust(old: u32, delta: i64) -> Result<u32, &'static str> {
let next = i64::from(old).checked_add(delta).ok_or("overflow")?;
u32::try_from(next).map_err(|_| "out of range")
}
fn apply(stock: &mut Vec<u32>, changes: &[(usize, i64)]) -> Result<(), &'static str> {
let mut staged = stock.clone();
for (index, delta) in changes {
let slot = staged.get_mut(*index).ok_or("unknown slot")?;
*slot = adjust(*slot, *delta)?;
}
*stock = staged;
Ok(())
}
fn main() {
let mut stock = vec![5, 2];
let initial = stock.clone();
let result = apply(&mut stock, &[(0, 2), (1, -3)]);
println!("{result:?} {stock:?}");
assert_eq!(stock, initial);
let result = apply(&mut stock, &[(0, 2), (1, -2)]);
println!("{result:?} {stock:?}");
assert_eq!(stock, vec![7, 0]);
}Err("out of range") [5, 2]
Ok(()) [7, 0]The in-place starter returned the same Err("out of range") while leaving [7, 2] behind, so an assertion on the return value alone passes for both versions. Only the state comparison tells them apart. The fix stages every change on a copy and commits with one assignment, *stock = staged;, which cannot fail halfway.
Change one input: swap the corrected batch to [(1, -2), (0, 2)]. The result is the same [7, 0], because neither order passes through an invalid intermediate value. Now find an order-sensitive pair for slot 1 alone, such as [(1, -3), (1, 1)] versus [(1, 1), (1, -3)], and predict which one succeeds before running it.
Commit stock and receipt together
Warm-up, from the Day 4 receipts lesson: what should a retry of a batch that already succeeded return, and why must it not apply the changes again? Why does a failed batch leave its ID free, and what would go wrong if it did not?
Your turn
Write submit(&mut self, id, changes) for the Ledger below. A new ID stages the changes as before and, only if every change succeeds, commits the stock and stores the batch as the receipt for that ID, returning Outcome::Applied. A known ID with exactly the same changes returns Outcome::Replayed and changes nothing. A known ID with different changes returns Err("conflict") and changes nothing. A failed batch stores no receipt, so its ID can be used again.
Check this sequence, comparing the whole state, stock and receipts, before and after every call that must not change it:
- Batch 1,
[(0, 2)], is applied to[5, 2]. - Batch 2,
[(0, 1), (1, -3)], fails without of rangeand leaves the state unchanged. - Batch 2,
[(1, -2)], is applied, because the ID is still free. - Batch 1,
[(0, 2)], is replayed without changing the state. - Batch 1,
[(0, 5)], is a conflict and leaves the state unchanged.
Then print the stock and the receipt IDs: [7, 0] receipts [1, 2].
use std::collections::BTreeMap;
fn adjust(old: u32, delta: i64) -> Result<u32, &'static str> {
let next = i64::from(old).checked_add(delta).ok_or("overflow")?;
u32::try_from(next).map_err(|_| "out of range")
}
#[derive(Debug, PartialEq, Eq)]
enum Outcome {
Applied,
Replayed,
}
struct Ledger {
stock: Vec<u32>,
receipts: BTreeMap<u32, Vec<(usize, i64)>>,
}
fn main() {
let ledger = Ledger { stock: vec![5, 2], receipts: BTreeMap::new() };
println!("{:?}", ledger.stock);
}Hint 1: the idea
Answer the ID question before any staging: a known ID never touches the stock, whichever way it goes. For a new ID, both stores change in the same place, after the last check, so there is no moment where one has changed and the other has not.
Hint 2: a first step
Write a small state(&self) method that returns clones of both stores, so every check is one assert_eq! against a saved copy. Then start submit by looking the ID up in receipts and handling the two known-ID outcomes.
Worked solution
use std::collections::BTreeMap;
fn adjust(old: u32, delta: i64) -> Result<u32, &'static str> {
let next = i64::from(old).checked_add(delta).ok_or("overflow")?;
u32::try_from(next).map_err(|_| "out of range")
}
#[derive(Debug, PartialEq, Eq)]
enum Outcome {
Applied,
Replayed,
}
struct Ledger {
stock: Vec<u32>,
receipts: BTreeMap<u32, Vec<(usize, i64)>>,
}
impl Ledger {
fn state(&self) -> (Vec<u32>, BTreeMap<u32, Vec<(usize, i64)>>) {
(self.stock.clone(), self.receipts.clone())
}
fn submit(&mut self, id: u32, changes: &[(usize, i64)]) -> Result<Outcome, &'static str> {
if let Some(stored) = self.receipts.get(&id) {
return if stored.as_slice() == changes { Ok(Outcome::Replayed) } else { Err("conflict") };
}
let mut staged = self.stock.clone();
for (index, delta) in changes {
let slot = staged.get_mut(*index).ok_or("unknown slot")?;
*slot = adjust(*slot, *delta)?;
}
self.stock = staged;
self.receipts.insert(id, changes.to_vec());
Ok(Outcome::Applied)
}
}
fn main() {
let mut ledger = Ledger { stock: vec![5, 2], receipts: BTreeMap::new() };
assert_eq!(ledger.submit(1, &[(0, 2)]), Ok(Outcome::Applied));
let before = ledger.state();
assert_eq!(ledger.submit(2, &[(0, 1), (1, -3)]), Err("out of range"));
assert_eq!(ledger.state(), before);
assert_eq!(ledger.submit(2, &[(1, -2)]), Ok(Outcome::Applied));
let before = ledger.state();
assert_eq!(ledger.submit(1, &[(0, 2)]), Ok(Outcome::Replayed));
assert_eq!(ledger.state(), before);
assert_eq!(ledger.submit(1, &[(0, 5)]), Err("conflict"));
assert_eq!(ledger.state(), before);
let ids: Vec<&u32> = ledger.receipts.keys().collect();
println!("{:?} receipts {ids:?}", ledger.stock);
}[7, 0] receipts [1, 2]The receipt is inserted on the line after self.stock = staged;, and nothing between them can fail, so the two stores move together. Step 3 is the check that a failed batch left its ID free; step 4 proves a replay does not apply (0, 2) again, since the stock would otherwise become [9, 0]. Change to try: move self.receipts.insert(...) above the staging loop. Predict which assertion fails. It is the state comparison after step 2: the error is still out of range, but batch 2's receipt was stored anyway, so a later, valid batch 2 would be reported as a conflict.
Grade yourself honestly
If you needed a hint, or your first version passed its own checks but would also have passed with a broken apply, schedule this page again in a week. The goal is not to finish the exercises; it is to explain each guarantee without looking anything up.
Completion is saved in this browser only. It does not measure mastery.