Failure Recap
Lesson 29 of 48 in Coddy's Rust for C# Developers course.
Challenge
EasyImplement pub fn apply(values: &mut Vec<i32>, batch: &str) -> Result<usize, String> in batches.rs. An empty or all-whitespace batch succeeds with zero additions. Otherwise split on commas, trim each field and parse every field as i32 from left to right; any parse failure returns integer. After all fields parse, reject any value outside -50 through 50 with range. On every error, the original vector must remain exactly unchanged. On success append the batch in order and return its number of values. Existing vector contents need not satisfy the new-batch range. solve starts with an empty vector and treats each input line as one batch; it reports statuses|values. Statuses are ok:n, integer or range, comma-separated; values are comma-separated numbers. An empty input has zero batches and returns |. A final newline is a line terminator, not an additional batch.
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, batches.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod batches;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
let mut values = vec![700, -700];
assert_eq!(batches::apply(&mut values, " 17, -19 "), Ok(2));
let saved = values.clone();
assert_eq!(batches::apply(&mut values, "8,no"), Err(String::from("integer")));
assert_eq!(values, saved);
assert_eq!(batches::apply(&mut values, "51,no"), Err(String::from("integer")));
assert_eq!(values, saved);
assert_eq!(batches::apply(&mut values, "8,51"), Err(String::from("range")));
assert_eq!(values, saved);
assert_eq!(batches::apply(&mut values, " "), Ok(0));
assert_eq!(values, saved);
assert_eq!(batches::apply(&mut values, "-50,50"), Ok(2));
assert_eq!(values, vec![700, -700, 17, -19, -50, 50]);
// 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 Readings6Absence and Failure
Option and MatchingResult and PropagationParsing and ValidationError ContractsFailure RecapPractice on your own: Online Rust compiler