Parsing and Validation
Lesson 27 of 48 in Coddy's Rust for JavaScript Developers course.
JavaScript number conversion rarely fails loudly. parseInt reads a leading numeric prefix and ignores the rest, Number rejects trailing letters by returning NaN, and Number("") quietly gives 0. Both skip surrounding whitespace. NaN is still a number, so it flows into arithmetic until something checks Number.isNaN. Rust integer parsing returns a Result: it succeeds only when the whole text is a valid integer within the bounds of the requested type, and it does not trim whitespace for you. Call trim first when your grammar allows surrounding spaces. The examples convert three tricky inputs. Decide which textual grammar your API accepts before you pick a conversion. A successful parse is still separate from domain validation: a valid integer may be an invalid age, capacity or identifier. When callers observe the reason, keep a deliberate order between syntax errors and range errors.
Complete standalone JavaScript program:
for (const text of ["12px", "", " 7"]) {
console.log(parseInt(text, 10), Number(text));
}
JavaScript output:
12 NaN
NaN 0
7 7
Complete standalone Rust program:
fn main() {
for text in ["12px", "", " 7"].iter() {
match text.parse::<i32>() {
Ok(value) => println!("{}", value),
Err(_) => println!("invalid"),
}
}
}
Rust output:
invalid
invalid
invalid
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 JavaScript 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