#csv #serialization

no-std serde-csv-core

CSV serialization for no_std crates

4 releases (2 breaking)

0.3.1 May 9, 2024
0.3.0 May 9, 2024
0.2.0 Apr 16, 2023
0.1.1 Apr 3, 2023
0.1.0 Apr 2, 2023

#215 in Embedded development

Download history 129/week @ 2024-06-21 138/week @ 2024-06-28 186/week @ 2024-07-05 219/week @ 2024-07-12 105/week @ 2024-07-19 98/week @ 2024-07-26 207/week @ 2024-08-02 197/week @ 2024-08-09 144/week @ 2024-08-16 116/week @ 2024-08-23 140/week @ 2024-08-30 127/week @ 2024-09-06 38/week @ 2024-09-13 128/week @ 2024-09-20 43/week @ 2024-09-27 159/week @ 2024-10-04

377 downloads per month

MIT/Apache

38KB
809 lines

serde-csv-core

Crates.io Released API docs Continuous integration

CSV serialization and deserialization for no_std crates.

serde-csv-core builds upon csv-core crate. It doesn't require any memory allocations, which means that it's well-suited for embedded environments.

Serialization

Writer serializes one record at a time.

use heapless::String;
use serde::Serialize;

#[derive(Serialize)]
struct Record {
    pub country: String<32>,
    pub city: String<32>,
    pub population: u32,
}

let records = [
    Record {
        country: "Poland".into(),
        city: "Cracow".into(),
        population: 766_683,
    },
    Record {
        country: "Japan".into(),
        city: "Tokyo".into(),
        population: 13_515_271,
    },
];

let mut writer = serde_csv_core::Writer::new();
let mut csv = [0; 128];
let mut nwritten = 0;
for record in &records {
    nwritten += writer.serialize(&record, &mut csv[nwritten..])?;
}

assert_eq!(&csv[..nwritten], b"Poland,Cracow,766683\nJapan,Tokyo,13515271\n");

Deserialization

Reader<N> deserializes one record at a time. N is a capacity of an internal buffer that's used to temporarily store unescaped fields.

use heapless::{String, Vec};
use serde::Deserialize;

#[derive(Debug, PartialEq, Eq, Deserialize)]
struct Record {
    pub country: String<32>,
    pub city: String<32>,
    pub population: u32,
}

let csv = b"Poland,Cracow,766683\nJapan,Tokyo,13515271\n";

let mut reader = serde_csv_core::Reader::<32>::new();
let mut records: Vec<Record, 2> = Vec::new();
let mut nread = 0;
while nread < csv.len() {
    let (record, n) = reader.deserialize::<Record>(&csv[nread..])?;
    records.push(record);
    nread += n;
}

assert_eq!(records, &[
    Record {
        country: "Poland".into(),
        city: "Cracow".into(),
        population: 766_683,
    },
    Record {
        country: "Japan".into(),
        city: "Tokyo".into(),
        population: 13_515_271,
    },
]);

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~2.5MB
~50K SLoC