Evian
Evian

Reputation: 1197

How to read a line from stdin with max input length?

To read a line from Stdin, I could

let mut stdin = std::io::stdin();
let mut input = String::new();
stdin.read_line(&mut input).unwrap();

To read from Stdin with a maximum length, I could do

const MAX_LENGTH: u64 = 256;
let mut stdin = std::io::stdin();
let mut input = String::new();
stdin.take(MAX_LENGTH).read(&mut input).unwrap();

What I want is the combination of the above two requires. Read a line from stdin, and if the input is longer than MAX_LENGTH, the remaining is discarded.

Upvotes: 3

Views: 1342

Answers (1)

rodrigo
rodrigo

Reputation: 98378

read_line is not a member of std::io::Read but of std::io::BufRead, and while stdin does implement the latter, the return of stdin.take() (of type std::io::Take<_>) does not.

But you can convert any Read into a BufRead easily using std::io::BufReader:

const MAX_LENGTH: u64 = 256;
let mut stdin = std::io::stdin();
let mut input = String::new();
let mut bstdin = std::io::BufReader::new(stdin.take(MAX_LENGTH));
bstdin.read_line(&mut input).unwrap();

Upvotes: 2

Related Questions