expression
Read a bounded confirmation and default to no
A destructive action must require explicit consent. This model accepts only the word yes followed by a line ending, with a sixteen-byte input limit including the delimiter. EOF, excessive input, malformed bytes and all other answers decline. The prompt is flushed before reading. A real program must abort on oversized input rather than reuse the remaining bytes. Fixture: Expected stdout (not executed): accepted=true Expected stderr: (empty) Expected exit: 0 Common mistake: Treating a blank answer or an I/O failure as permission.
Formal Syntax & Structure
rust syntaxrust
reader.take(17).read_until(b'\n', &mut answer)Working Example
Example Snippetrust
fn main() { use std::io::{BufRead, Read, Write, Cursor}; fn confirm(mut input: impl BufRead, mut prompt: impl Write) -> std::io::Result<bool> { prompt.write_all(b"Continue? [yes/no] ")?; prompt.flush()?; let mut answer = Vec::new(); let n = input.by_ref().take(17).read_until(b'\n', &mut answer)?; Ok(n <= 16 && matches!(answer.as_slice(), b"yes\n" | b"yes\r\n")) } let mut prompt = Vec::new(); let accepted = confirm(Cursor::new(b"yes\n"), &mut prompt).unwrap(); assert_eq!(prompt, b"Continue? [yes/no] "); assert!(!confirm(Cursor::new(b""), Vec::new()).unwrap()); assert!(!confirm(Cursor::new(b"yes"), Vec::new()).unwrap()); assert!(!confirm(Cursor::new(b"01234567890123456789\n"), Vec::new()).unwrap()); println!("accepted={accepted}");}