Crates.io | token-read |
lib.rs | token-read |
version | 0.2.0 |
source | src |
created_at | 2023-01-11 22:44:52.552432 |
updated_at | 2023-06-02 15:25:30.446346 |
description | A library for reading whitespace delimited files intended for competitive programming |
homepage | |
repository | https://github.com/SvizelPritula/token-read |
max_upload_size | |
id | 756732 |
size | 44,245 |
This is a simple crate that allows for easy parsing of whitespace delimited files.
It is primarily intended for competitive programming, where such files are commonly used as inputs due to being easy to parse in C and C++. This crate aims to bring this ease to Rust.
For complete programs, see the examples in the source repository.
A TokenReader
can be constructed from any type implementing BufRead
, such as a file, standard input or a byte slice.
The easiest way to handle errors is to use anyhow.
use std::io::stdin;
use anyhow::Result;
use token_read::TokenReader;
fn main() -> Result<()> {
let mut input = TokenReader::new(stdin().lock());
// Do IO and computation
Ok(())
}
A tuple of one or more values of any type implementing FromStr
can be read using the line
function.
let (budget, ): (u64, ) = input.line()?;
let (product, cost): (String, u64) = input.line()?;
10000
Sandwich 80
In order to read a line without any modifications, you can use the line_raw
function.
let sentence: String = input.line_raw()?;
All human beings are born free and equal in dignity and rights.
The line
function can also be used to read a variable amount values of a type implementing FromStr
into most standard collections.
let temperatures: Vec<f64> = input.line()?;
let allowed_letters: HashSet<char> = input.line()?;
18.7 19.2 19.4 18.9
A B E I J M N
The take
function can be used to create an iterator consuming a specific number of lines. You can use it to make a simple for
loop.
let (city_count, ): (usize, ) = input.line()?;
for city in input.take(city_count) {
let (name, population): (String, u64) = city?;
}
Alternatively, it can be collected into any data structure.
let (city_count, ): (usize, ) = input.line()?;
let cities: Vec<(String, u64)> = input.take(city_count).collect::<Result<_, _>>()?;
In cases where the input doesn't need to be stored in memory, take_count
can be used instead, as it allows larger line counts than fit in a usize
:
let (city_count, ): (u64, ) = input.line()?;
for city in input.take_count(city_count) {
let (name, population): (String, u64) = city?;
}
3
Prague 1309000
New York 8468000
Tokio 13960000
This crate is available from crates.io. To install, simply run:
cargo add token-read