Skip to main content

read_str

Function read_str 

Source
pub fn read_str(input: &str) -> Result<Vec<Vec<String>>, CsvError>
Expand description

Parses CSV text into records, using conservative CsvLimits.

Each record is a Vec<String> of fields. The result is rectangular: every record has the same number of fields as the first, or the read fails. See the crate documentation for the exact accepted grammar.

use reliakit_csv::read_str;

assert_eq!(read_str("a,b\n1,2\n").unwrap(), [["a", "b"], ["1", "2"]]);
assert_eq!(read_str("").unwrap(), Vec::<Vec<String>>::new());
Examples found in repository?
examples/basic.rs (line 44)
42fn main() {
43    // Low-level: parse rows of strings.
44    let rows = read_str("a,b\n1,2\n").unwrap();
45    println!("rows: {rows:?}");
46
47    // Low-level: write rows deterministically (a field is quoted only if needed).
48    let mut writer = CsvWriter::new();
49    writer.write_record(["plain", "needs,quote"]);
50    print!("written: {}", writer.into_string());
51
52    // Typed: round-trip a slice of records through a header + rows.
53    let services = vec![
54        Service {
55            name: "api".into(),
56            port: 8080,
57            enabled: true,
58        },
59        Service {
60            name: "worker, west".into(),
61            port: 9000,
62            enabled: false,
63        },
64    ];
65    let text = to_csv_string(&services);
66    print!("encoded:\n{text}");
67
68    let decoded: Vec<Service> = from_csv_str(&text).unwrap();
69    assert_eq!(decoded, services);
70    println!("round-trip ok: {} record(s)", decoded.len());
71}