Menu
CoddyTech

Final: Sensor Policies

Lesson 48 of 48 in Coddy's Rust for Luau Developers course.

challenge icon

Challenge

Medium

Port the Luau reference, replacing its table-method policy contract with an explicitly implemented Rust trait. Input starts with an i32 integer threshold followed by at most 100 whitespace-separated reading tokens. A token is at most 31 ASCII bytes. Valid readings have an optional leading sign and decimal digits and fit i32; every running total fits i32. reading::parse(text: &str) -> Result<i32, &'static str> accepts the complete token without surrounding spaces and returns Err("invalid") for anything else. Accept::accept(&self, value: i32) -> bool is the policy contract. Above::new(limit: i32) -> Above accepts strictly greater values. Report::new() -> Report starts empty; feed<R: Accept + ?Sized>(&mut self, value: i32, rule: &R) adds accepted readings to count and total, preserving state for rejected readings; count(&self) -> usize and total(&self) -> i32 are observers. Any caller-defined Accept policy, including a trait object, must work. Output count total invalid, using Above for input processing. No readings gives 0 0 0.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, rule.rs, above.rs, report.rs, reading.rs. main.rs holds the supplied input/output code and cannot be edited.

Luau callers can supply a table with a compatible acceptance method. Rust callers supply a type with an explicit trait implementation or a compatible trait object. The reference checks complete ASCII decimal tokens and the signed 32-bit range before accumulating digits; tonumber alone accepts broader numeric formats. Luau number is exact for the stated running-total bounds.

Complete standalone Luau reference program:

-- Luau console reference with strict ASCII and i32 bounds.
local function parse(text: string): number?
    if not text:match("^[+-]?[0-9]+$") then return nil end
    local negative = text:sub(1, 1) == "-"
    local first = (negative or text:sub(1, 1) == "+") and 2 or 1
    local limit = negative and 2147483648 or 2147483647
    local magnitude = 0
    for index = first, #text do
        local digit = text:byte(index) - 48
        if magnitude > math.floor((limit - digit) / 10) then return nil end
        magnitude = magnitude * 10 + digit
    end
    return negative and -magnitude or magnitude
end
local Above = {}
Above.__index = Above
function Above.new(limit) return setmetatable({limit = limit}, Above) end
function Above:accept(value) return value > self.limit end
local Report = {}
Report.__index = Report
function Report.new() return setmetatable({count = 0, total = 0}, Report) end
function Report:feed(value, rule)
    if rule:accept(value) then
        self.count = self.count + 1
        self.total = self.total + value
    end
end
local words = {}
for word in io.read("*a"):gmatch("%S+") do words[#words + 1] = word end
local rule, report, invalid = Above.new(tonumber(words[1])), Report.new(), 0
for index = 2, #words do
    local value = parse(words[index])
    if value == nil then invalid = invalid + 1 else report:feed(value, rule) end
end
print(string.format("%d %d %d", report.count, report.total, invalid))

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod rule;
mod above;
mod report;
mod reading;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
use rule::Accept;
    let p=above::Above::new(-3); assert!(p.accept(-2)); assert!(!p.accept(-3)); assert!(!p.accept(-4));
    assert_eq!(reading::parse("+17"), Ok(17)); assert_eq!(reading::parse("-0"), Ok(0));
    for s in &["", "+", " 3", "2x", "2147483648"] { assert_eq!(reading::parse(s), Err("invalid")); }
    struct Odd;
    impl rule::Accept for Odd { fn accept(&self, value: i32) -> bool { value % 2 != 0 } }
    let policy: &dyn rule::Accept=&Odd;
    let mut r=report::Report::new(); assert_eq!(r.count(),0); assert_eq!(r.total(),0);
    r.feed(-7,policy); r.feed(4,policy); r.feed(9,policy);
    assert_eq!(r.count(),2); assert_eq!(r.total(),2);
    r.feed(0,policy); assert_eq!(r.count(),2); assert_eq!(r.total(),2);
    r.feed(1,&p); assert_eq!(r.count(),3); assert_eq!(r.total(),3);
    assert_eq!(report::Report::new().count(),0);
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}

All lessons in Rust for Luau Developers

Practice on your own: Online Rust compiler