Final: Sensor Policies
Lesson 48 of 48 in Coddy's Rust for C++ Developers course.
Challenge
MediumPort the C++17 reference, replacing its virtual policy interface with an injected Rust trait. The source uses optional parsed values and a virtual destructor; the Rust API reports parse errors with Result and supports both generics and trait objects. 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.
Complete C++17 reference for the same valid input contract:
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <limits>
#include <optional>
#include <stdexcept>
#include <string>
std::optional<std::int32_t> parse(const std::string& token) {
std::size_t start = (!token.empty() && (token[0] == '+' || token[0] == '-')) ? 1 : 0;
if (start == token.size()) return std::nullopt;
if (!std::all_of(token.begin() + start, token.end(), [](char ch) {
return ch >= '0' && ch <= '9';
})) return std::nullopt;
try {
std::size_t used = 0;
long long value = std::stoll(token, &used, 10);
if (used != token.size() || value < std::numeric_limits<std::int32_t>::min()
|| value > std::numeric_limits<std::int32_t>::max()) return std::nullopt;
return static_cast<std::int32_t>(value);
} catch (const std::out_of_range&) { return std::nullopt; }
catch (const std::invalid_argument&) { return std::nullopt; }
}
struct Accept {
virtual ~Accept() = default;
virtual bool accept(std::int32_t value) const = 0;
};
class Above final : public Accept {
std::int32_t limit_;
public:
explicit Above(std::int32_t limit) : limit_(limit) {}
bool accept(std::int32_t value) const override { return value > limit_; }
};
class Report {
std::size_t count_ = 0;
std::int32_t total_ = 0;
public:
void feed(std::int32_t value, const Accept& rule) {
if (rule.accept(value)) { ++count_; total_ += value; }
}
std::size_t count() const { return count_; }
std::int32_t total() const { return total_; }
};
int main() {
std::int32_t threshold;
if (!(std::cin >> threshold)) return 1;
Above rule(threshold);
Report report;
std::size_t invalid = 0;
std::string token;
while (std::cin >> token) {
auto reading = parse(token);
if (reading) report.feed(*reading, rule);
else ++invalid;
}
std::cout << report.count() << ' ' << report.total() << ' ' << invalid << '\n';
}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 C++ Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler