Expand description
Parse files and lists of stringified things into lists of thingified things.
That is, if you’ve got something Read-y or Iterator-y over u8s,
Strings, or strs, and a type that implements FromStr, you can also
have an Iterator of that type of thing.
Particularly designed to parse files of newline-separated things, like these git integers:
0
1
2
3
4Load your ints with ease:
ⓘ
// Create the file of test data
use std::fs;
let tmp_dir = TempDir::new("tmp").unwrap();
let file_path = tmp_dir.path().join("list");
fs::write(&file_path, "0\n1\n2\n3\n4").unwrap();
// Load from file. Note that each element could result in an individual
// I/O or parse error. Here those are converted into a single `Result<Vec<u32>, _>`.
let v = from_file_lines(&file_path);
let v: Vec<Result<u32, _>> = v.unwrap().collect();
let v: Result<Vec<u32>, _> = v.into_iter().collect();
let v = v.unwrap();
assert!(v == vec![0, 1, 2, 3, 4]);Besides parsing from a newline-separated file there are also functions for parsing from various traits, including iterators.
§Tips
To convert from an iterator of Result to a Result of Vec use collect
with a Result<Vec<_>> type annotation:
use big_s::S;
let a = vec![Ok(S("0")), Ok(S("1")), Ok(S("2"))];
let b: Vec<Result<u32, _>> = parse_list::from_iter(a.into_iter()).collect();
let b: Result<Vec<u32>, _> = b.into_iter().collect();
let b = b.unwrap();
assert!(b == vec![0, 1, 2]);To ignore errors parsing any particular list entry, use
filter_map(Result::ok):
use big_s::S;
use std::io;
use std::num::ParseIntError;
let e: io::Error = io::Error::from(io::ErrorKind::NotFound);
let a: Vec<Result<String, io::Error>> = vec![Ok(S("0")), Err(e), Ok(S("2"))];
let b: Vec<u32> = parse_list::from_iter(a.into_iter())
.filter_map(Result::ok).collect();
assert!(b.len() == 2);
assert!(b[0] == 0);
assert!(b[1] == 2);