Input limits and safe parsing
Quick answer
Safe Rust protects many memory accesses, but a valid allocation or loop can still exhaust resources. Bound input size, validate format and use checked arithmetic before allocating or processing untrusted data.
Reject early
Length checks must happen before expensive operations. For streaming input enforce a cumulative byte limit while reading, not only after collecting everything. Limit nested structures and decompressed sizes separately. checked_mul returns None if a product does not fit, regardless of build profile. These examples are small validation functions, not complete network defenses.
fn parse_count(s: &str) -> Option<u16> { if s.len() > 5 || !s.bytes().all(|b| b.is_ascii_digit()) { return None; } s.parse::<u16>().ok().filter(|n| *n <= 1000)}fn main() { println!("{:?} {:?}", parse_count("42"), parse_count("99999")); }Expected stdout (not executed):
Some(42) NoneBoth text length and numeric range matter.
fn bytes(rows: usize, cols: usize) -> Option<usize> { rows.checked_mul(cols)?.checked_mul(4).filter(|n| *n <= 4096)}fn main() { println!("{:?} {:?}", bytes(8, 8), bytes(usize::MAX, 2)); }Expected stdout (not executed):
Some(256) NoneNo allocation is attempted on overflow or excess size.
Common mistake
Do not rely on a debug-build overflow panic as input validation.
Try it yourself
Test the exact 4096-byte boundary and an empty numeric field.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Input limits and safe parsing — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A requested buffer size is rows multiplied by columns and four. How can overflow be rejected before allocation?
Input limits and safe parsing — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn parse_count(s: &str) -> Option<u16> { if s.len() > 5 || !s.bytes().all(|b| b.is_ascii_digit()) { return None; } s.parse::<u16>().ok().filter(|n| *n <= 1000) } fn main() { println!("{:?} {:?}", parse_count("42"), parse_count("99999")); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Input limits and safe parsing — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn bytes(rows: usize, cols: usize) -> Option<usize> { rows.checked_mul(cols)?.checked_mul(4).filter(|n| *n <= 4096) } fn main() { println!("{:?} {:?}", bytes(8, 8), bytes(usize::MAX, 2)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.