token_read/lib.rs
1//! This is a simple crate that allows for easy parsing of whitespace delimited files.
2//!
3//! It is primarily intended for competitive programming, where such files are commonly used as
4//! inputs due to being easy to parse in C and C++. This crate aims to bring this ease to Rust.
5//!
6//! # Sample usage
7//!
8//! ## Input
9//!
10//! ```txt
11//! 42
12//! Benjamin 2536000
13//! 0 1 1 2 3 5 8 13 21 34
14//! ```
15//!
16//! ## Code
17//!
18//! ```no_run
19//! use std::io::stdin;
20//!
21//! use anyhow::Result;
22//! use token_read::TokenReader;
23//!
24//! fn main() -> Result<()> {
25//! let mut input = TokenReader::new(stdin().lock());
26//!
27//! let (n,): (usize,) = input.line()?; // Read a single value
28//! let (name, points): (String, u64) = input.line()?; // Read several values
29//! let values: Vec<u64> = input.line()?; // Read an array of values
30//! let tuples: Vec<(u32, f64)> = input.take(3).collect::<Result<_, _>>()?; // Read several lines of values
31//!
32//! // Do some processing
33//!
34//! Ok(())
35//! }
36//' ```
37
38mod count;
39mod error;
40pub mod impls;
41mod iter;
42mod reader;
43mod to_tokens;
44
45pub use count::LineCount;
46pub use error::{ParseTokenPatternError, ReadLineError, ReadTokensError};
47pub use iter::Take;
48pub use reader::TokenReader;
49pub use to_tokens::ToTokens;
50
51#[cfg(doc)]
52use std::str::FromStr;
53
54/// A trait for types parsable from an iterator of whitespace delimited tokens.
55///
56/// Implementations are provided for tuples and collections of types implementing [`FromStr`].
57pub trait FromTokens: Sized {
58 type Error;
59
60 /// Parses a value from an iterator of string tokens.
61 fn from_tokens<'a, I>(tokens: I) -> Result<Self, Self::Error>
62 where
63 I: Iterator<Item = &'a str>;
64}