Skip to content

On Your Own: A Reservation Ledger

The Course
•
40 min study

This is the week's capstone, and it is deliberately not about stock. A guarantee you understand should survive a change of domain, so here you rebuild the ledger's contract for room reservations, with no project code to copy. The new twist is a rule that spans more than one value: each of two rooms holds at most four reservations, and together they hold at most six. A per-item rule like MaxQuantity looks at one number at a time; a shared limit has to look at the whole staged state after every change. That makes the order of changes inside a batch matter, which is exactly why the batch is ordered.

Write it from scratch, plan before you type, and treat the solution as something to compare against afterward.

What you will use

  • Validated input: reject ID 0, an empty batch, a zero delta and an unknown room before any state changes.
  • Checked arithmetic: compute each new count in a wider type and accept it only inside 0..=4.
  • Staging: change a copy of the rooms; [u32; 2] is Copy, so let mut staged = self.rooms; is already an independent copy.
  • Intermediate checks: test the shared total after every change, not only at the end.
  • Receipts with payloads: replay an identical accepted batch, reject a conflicting one, and record only after the commit.
  • Evidence: after every rejection, compare both the rooms and the receipt count with their values before the attempt.

Plan before you type

  1. Write apply(&mut self, id: u32, changes: &[(usize, i32)]) -> Result<bool, &'static str>, where Ok(true) means applied and Ok(false) means replayed.
  2. Reject an invalid ID or empty batch first. Then look up the receipt and return replay or conflict.
  3. Copy the rooms into staged. For each change, reject a zero delta, find the room with get_mut, compute the next count as an i64, check the room limit, assign it, then check the total of both staged rooms.
  4. After the loop, commit self.rooms = staged and insert the receipt.
  5. Write the checks in the order of the scenario below, then add one batch that succeeds only because a release comes before an addition.
Prove it can fail

Move the shared-total check after the loop, so it looks only at the final state. The batch [(1, -1), (0, 1)] still passes, but your check that [(0, 1), (1, -1)] is rejected must now fail. Then move the receipt insertion above the loop: the corrected retry of batch 2 should report conflict. If your checks miss either change, they are not observing the right state.

Mistakes worth checking for

  • A rejected batch changes one room: the code wrote to self.rooms inside the loop instead of to staged.
  • Shared limit passes a batch that exceeds it midway: the total was checked only after the loop.
  • Releasing below zero wraps or panics: the new count was computed in u32; compute in i64 and check the range first.
  • Corrected batch is reported as a conflict: a failed attempt recorded its receipt.
  • Unknown room panics: the code indexed staged[room] instead of using get_mut and returning an error.
Exercise

Your turn

Build a Reservations type with two rooms. Each room can hold at most four reservations, and the combined total can be at most six. An update batch has a positive ID and a nonempty ordered list of signed, nonzero changes to room indices 0 or 1.

Validate every intermediate room count and shared total before committing the entire batch. A failed batch changes neither rooms nor receipts. An identical accepted ID replays, and a conflicting payload fails. IDs from failed batches can be corrected and retried.

Start by reserving three places in each room with batch 1. Reject batch 2 when it releases one place from room 0 and then adds two to room 1, and verify both rooms stay at three. Also reject batch 2 for an unknown room, a zero delta, a negative final count and shared capacity overflow. Correct batch 2 to release one and add one, then retry it identically, and send a conflicting version. Finally show ordering: with rooms at [2, 4], batch 3 [(0, 1), (1, -1)] must fail, and [(1, -1), (0, 1)] must succeed and give [3, 3].

Your working space Rust
use std::collections::BTreeMap;

#[derive(Default)]
struct Reservations {
    rooms: [u32; 2],
    receipts: BTreeMap<u32, Vec<(usize, i32)>>,
}

fn main() {
    // Add an apply method and test the contract.
}
Hint 1: the idea

Stage the fixed-size array and keep the receipt insertion after all per-room and shared checks.

Hint 2: a first step

An array of two u32 values implements Copy, so a local assignment creates an independent staged array. Compute i64::from(*slot) + i64::from(*delta), which cannot overflow, and test it with (0..=4).contains(&next) before converting back.

Worked solution
Run the solution Rust
use std::collections::BTreeMap;

#[derive(Default)]
struct Reservations {
    rooms: [u32; 2],
    receipts: BTreeMap<u32, Vec<(usize, i32)>>,
}

impl Reservations {
    fn apply(&mut self, id: u32, changes: &[(usize, i32)]) -> Result<bool, &'static str> {
        if id == 0 || changes.is_empty() { return Err("invalid batch"); }
        if let Some(previous) = self.receipts.get(&id) {
            return if previous == changes { Ok(false) } else { Err("conflict") };
        }
        let mut staged = self.rooms;
        for (room, delta) in changes {
            if *delta == 0 { return Err("zero change"); }
            let slot = staged.get_mut(*room).ok_or("unknown room")?;
            let next = i64::from(*slot) + i64::from(*delta);
            if !(0..=4).contains(&next) { return Err("room capacity"); }
            *slot = next as u32;
            let total: u64 = staged.iter().map(|value| u64::from(*value)).sum();
            if total > 6 { return Err("shared capacity"); }
        }
        self.rooms = staged;
        self.receipts.insert(id, changes.to_vec());
        Ok(true)
    }
}

fn main() {
    let mut ledger = Reservations::default();
    assert_eq!(ledger.apply(0, &[(0, 1)]), Err("invalid batch"));
    assert_eq!(ledger.apply(1, &[]), Err("invalid batch"));
    assert_eq!(ledger.apply(1, &[(0, 3), (1, 3)]), Ok(true));
    let initial = ledger.rooms;
    for changes in [
        vec![(0, -1), (1, 2)],
        vec![(2, 1)],
        vec![(0, 0)],
        vec![(0, -4)],
        vec![(0, 1)],
    ] {
        let result = ledger.apply(2, &changes);
        println!("{changes:?}: {result:?}");
        assert!(result.is_err());
        assert_eq!(ledger.rooms, initial);
        assert_eq!(ledger.receipts.len(), 1);
    }
    assert_eq!(ledger.apply(2, &[(0, -1), (1, 1)]), Ok(true));
    assert_eq!(ledger.apply(2, &[(0, -1), (1, 1)]), Ok(false));
    assert_eq!(ledger.apply(2, &[(0, 1)]), Err("conflict"));
    assert_eq!(ledger.rooms, [2, 4]);

    let add_first = ledger.apply(3, &[(0, 1), (1, -1)]);
    println!("add first: {add_first:?}");
    assert_eq!(add_first, Err("shared capacity"));
    let release_first = ledger.apply(3, &[(1, -1), (0, 1)]);
    println!("release first: {release_first:?}");
    assert_eq!(release_first, Ok(true));
    assert_eq!(ledger.rooms, [3, 3]);
    assert_eq!(ledger.receipts.len(), 3);
    println!("Reservation checks passed");
}
Text
[(0, -1), (1, 2)]: Err("room capacity")
[(2, 1)]: Err("unknown room")
[(0, 0)]: Err("zero change")
[(0, -4)]: Err("room capacity")
[(0, 1)]: Err("shared capacity")
add first: Err("shared capacity")
release first: Ok(true)
Reservation checks passed

The first rejection is worth a second look: releasing one place from room 0 succeeded in the stage, then adding two to room 1 would have made it five, so the room limit rejected the whole batch and room 0 kept its third reservation. The last two lines show why the batch is ordered: the same two changes fail or succeed depending on whether the release comes first. Because the first attempt at batch 3 failed, it left no receipt, so the reordered batch could reuse the ID. The i64 addition is safe for any u32 count plus an i32 delta, and the receipt history belongs to this in-memory instance only.

Was this article helpful?

Your response is saved on this device.