Parsing and Validation
Lesson 27 of 48 in Coddy's Rust for R Developers course.
R as.numeric accepts surrounding whitespace and can return NA with a warning for failed conversion. That mechanism differs from Rust parse returning Result for a requested numeric type. The source accepts the spaces, while Rust first rejects untrimmed text and then succeeds after explicit trim. Numeric conversion is not complete validation: accepted formats may exceed a strict decimal grammar, and a valid number may violate a domain bound. NA, NaN, and infinity need explicit policies rather than being allowed to flow into scalar conditions. Decide whether trimming is permitted and preserve that contract. Type conversion alone does not establish range or application meaning.
R: complete program
text <- " 42 "
value <- as.numeric(text)
cat(value, "\n", tolower(as.character(value < 10)), "\n", sep = "")
Rust: complete program
fn main() {
let text = " 42 ";
println!("{}", text.parse::<i32>().is_err());
println!("{}", text.trim().parse::<i32>().unwrap());
}Missing and nonfinite numeric results need deliberate handling instead of being mistaken for valid parsed integers.
Challenge
EasyImplement pub fn parse_pair(text: &str) -> Result<(i32, i32), String> in parser.rs. Accept exactly two colon-separated fields. Trim surrounding whitespace in each field. Each field must parse as an i32 using Rust decimal integer parsing. Validate in this order: wrong field count gives format; a parse failure in either field gives integer; only after both parse, a value outside -100 through 100 gives range. Errors are owned strings. solve passes the entire input to the API and returns ok:sum or error:reason. A leading plus or minus is accepted by integer parsing; interior whitespace, empty fields and overflow are parse failures.
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, parser.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 parser;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
assert_eq!(parser::parse_pair(" -17 : +23 "), Ok((-17, 23)));
assert_eq!(parser::parse_pair("100:-100"), Ok((100, -100)));
assert_eq!(parser::parse_pair("101:bad"), Err(String::from("integer")));
assert_eq!(parser::parse_pair("101:2"), Err(String::from("range")));
assert_eq!(parser::parse_pair("1:2:3"), Err(String::from("format")));
assert_eq!(parser::parse_pair(":"), Err(String::from("integer")));
assert_eq!(parser::parse_pair(""), Err(String::from("format")));
assert_eq!(parser::parse_pair("2147483648:0"), Err(String::from("integer")));
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for R 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