Skip to content

Checkpoint: Validate a Reading Target

The Course
•
30 min study

This checkpoint combines today's ideas in one small type. A reading target says how many pages you plan to read this week, and it remembers how many you have logged so far. Two rules must always hold: the target is positive, and the logged count never exceeds it. You will enforce the first in a constructor and the second in a method, and keep both fields private so no other code can break them.

What you will use

  • A private field behind a module. Target lives in mod targets with private limit and logged fields, so outside code must use your constructor and methods.
  • A checked constructor. new(limit) returns Option<Self>, with None for a zero target and a count that starts at zero.
  • A &mut self method that can reject. log(pages) returns Result<(), LogError>, and a rejected call leaves the count unchanged.
  • Derived Debug, PartialEq and Eq. They let assert_eq! compare results such as Err(LogError::BeyondTarget).

Plan before you type

  1. Inside the module, add impl Target with pub fn new(limit: u32) -> Option<Self>.
  2. Add pub fn logged(&self) -> u32 so main can read the count without touching the field.
  3. Write pub fn log(&mut self, pages: u32) -> Result<(), LogError>. Work out the remaining pages first and reject anything larger, before changing logged.
  4. In main, check that new(0) is None, then build a target of 10 and log 3, 8 and 7, asserting each result and the count after it.
  5. Finish with the boundary: once the target is full, logging even 1 more page must fail.
Prove the checks can fail

Break your method on purpose and run again. Change the test to pages >= remaining and the exact log of 7 must fail an assertion. Move self.logged += pages; above the check and the count assertion after the rejected 8 must fail. If an assertion still passes with a broken method, it is not testing anything.

Mistakes worth checking for

  • The run aborts with "attempt to add with overflow" for a huge page count: the check computed self.logged + pages, which can overflow a u32. Subtract instead: self.limit - self.logged cannot go below zero because the invariant keeps logged at or below limit.
  • Logging exactly the remaining pages is rejected: the comparison uses >= where > is meant.
  • After a rejection, the count has changed: the method updated logged before deciding.
  • main fails with "field logged of struct Target is private": read the count through the getter, not the field.
Exercise

Your turn

Write the constructor, log and the logged getter. In main, check that a zero target cannot be built. For a target of 10: logging 3 succeeds, 8 fails with BeyondTarget and the count stays 3, 7 succeeds and the count becomes 10, and a further 1 fails. Print Target checks passed at the end.

Your working space Rust
mod targets {
    #[derive(Debug, PartialEq, Eq)]
    pub enum LogError {
        BeyondTarget,
    }

    pub struct Target {
        limit: u32,
        logged: u32,
    }
}

fn main() {
    // Construct a target and test both branches of your method.
}
Hint 1: the idea

Compare against the remaining amount before adding. This also avoids overflow if the caller supplies a very large page count.

Hint 2: a first step

Inside the module, add impl Target with a constructor returning Option<Self>, built as Self { limit, logged: 0 }, and a getter returning self.logged.

Worked solution
Run the solution Rust
mod targets {
    #[derive(Debug, PartialEq, Eq)]
    pub enum LogError {
        BeyondTarget,
    }

    pub struct Target {
        limit: u32,
        logged: u32,
    }

    impl Target {
        pub fn new(limit: u32) -> Option<Self> {
            if limit == 0 { None } else { Some(Self { limit, logged: 0 }) }
        }

        pub fn log(&mut self, pages: u32) -> Result<(), LogError> {
            if pages > self.limit - self.logged {
                return Err(LogError::BeyondTarget);
            }
            self.logged += pages;
            Ok(())
        }

        pub fn logged(&self) -> u32 {
            self.logged
        }
    }
}

fn main() {
    assert!(targets::Target::new(0).is_none());
    let Some(mut target) = targets::Target::new(10) else {
        panic!("positive target should work");
    };
    assert_eq!(target.log(3), Ok(()));
    assert_eq!(target.log(8), Err(targets::LogError::BeyondTarget));
    assert_eq!(target.logged(), 3);
    assert_eq!(target.log(7), Ok(()));
    assert_eq!(target.logged(), 10);
    assert_eq!(target.log(1), Err(targets::LogError::BeyondTarget));
    assert_eq!(target.log(u32::MAX), Err(targets::LogError::BeyondTarget));
    println!("Target checks passed");
}
Text
Target checks passed

let Some(...) = ... else extracts a valid target or takes the failure branch, which here would mean the constructor broke a test assumption. The u32::MAX line proves the subtraction-based check cannot overflow. Every rejection leaves logged within limit, so the invariant set by the constructor holds after any sequence of calls. Day 2 turns to borrowing: reading parts of data without copying or owning it.

Was this article helpful?

Your response is saved on this device.