pub struct SerializerConfig { /* private fields */ }Expand description
Configures how values are serialized into delimited text.
The value is a sequence of records. Records are maps (for instance
structs), the keys of the first record are the names of the columns
which are written first (see headers), or sequences
(for instance tuples). Fields are written in the order of the names,
missing fields are empty and keys that are not a column are an error.
Fields cannot hold maps or sequences (see
Separated for lists in a field).
Numbers are written with the shortest text that reads back as the same
value, booleans as true and false, null as an empty field (see
nulls) and bytes as base64 (see
bytes). Fields are quoted if necessary (see
quote_style).
use deser_csv::{SerializerConfig, Terminator};
#[derive(deser::Serialize)]
struct Row {
name: &'static str,
note: Option<&'static str>,
}
let rows =
[Row { name: "a", note: Some("x;y") }, Row { name: "b", note: None }];
let config =
SerializerConfig::new().delimiter(b';').terminator(Terminator::CrLf);
assert_eq!(
config.to_string(&rows).unwrap(),
"name;note\r\na;\"x;y\"\r\nb;\r\n"
);Implementations§
Source§impl SerializerConfig
impl SerializerConfig
Sourcepub const fn new() -> SerializerConfig
pub const fn new() -> SerializerConfig
Creates the default configuration (CSV).
Sourcepub const fn tsv() -> SerializerConfig
pub const fn tsv() -> SerializerConfig
Creates the configuration for tab separated values.
This is the counterpart of
DeserializerConfig::tsv: fields
are separated by tabs, special characters are escaped with
backslashes and null is \N.
let rows = vec![("a\tb", Some(1)), ("c", None)];
let tsv = deser_csv::SerializerConfig::tsv().to_string(&rows).unwrap();
assert_eq!(tsv, "a\\tb\t1\nc\t\\N\n");Sourcepub const fn delimiter(self, delimiter: u8) -> SerializerConfig
pub const fn delimiter(self, delimiter: u8) -> SerializerConfig
Sets the character that separates fields (, by default).
Sourcepub const fn quote(self, quote: Option<u8>) -> SerializerConfig
pub const fn quote(self, quote: Option<u8>) -> SerializerConfig
Sets the character that quotes fields (" by default).
Without quotes, fields that need them are an error (unless they
can be escaped, see escape).
Sourcepub const fn double_quote(self, yes: bool) -> SerializerConfig
pub const fn double_quote(self, yes: bool) -> SerializerConfig
Sets if quotes in quoted fields are doubled (true by default).
Otherwise they are escaped (see escape).
Sourcepub const fn escape(self, escape: Escape) -> SerializerConfig
pub const fn escape(self, escape: Escape) -> SerializerConfig
Sets how characters are escaped (not at all by default).
With an escape character, special characters in unquoted fields are escaped instead of quoting the field.
Sourcepub const fn terminator(self, terminator: Terminator) -> SerializerConfig
pub const fn terminator(self, terminator: Terminator) -> SerializerConfig
Sets the line ending (\n by default, see Terminator).
Sourcepub const fn quote_style(self, style: QuoteStyle) -> SerializerConfig
pub const fn quote_style(self, style: QuoteStyle) -> SerializerConfig
Sets when fields are quoted (QuoteStyle::Necessary by default).
Sourcepub const fn headers(self, yes: bool) -> SerializerConfig
pub const fn headers(self, yes: bool) -> SerializerConfig
Sets if the names of the columns are written before the first
record (true by default).
The names are the keys of the first record (or the given columns,
see columns). Records that are sequences have no
names.
Sourcepub const fn columns(self, names: &'static [&'static str]) -> SerializerConfig
pub const fn columns(self, names: &'static [&'static str]) -> SerializerConfig
Sets the names of the columns (by default they are the keys of the first record).
This is needed if the first record does not have all keys, for instance because records are enums or skip fields. Fields are written in the order of the columns, missing fields are empty.
#[derive(deser::Serialize)]
#[deser(tag = "kind", rename_all = "lowercase")]
enum Shape {
Circle { radius: f64 },
Rect { width: f64, height: f64 },
}
let shapes = [
Shape::Circle { radius: 1.0 },
Shape::Rect { width: 2.0, height: 3.0 },
];
let config = deser_csv::SerializerConfig::new()
.columns(&["kind", "radius", "width", "height"]);
assert_eq!(
config.to_string(&shapes).unwrap(),
"kind,radius,width,height\ncircle,1.0,,\nrect,,2.0,3.0\n"
);Sourcepub const fn nulls(self, nulls: Nulls) -> SerializerConfig
pub const fn nulls(self, nulls: Nulls) -> SerializerConfig
Sets how null is written (Nulls::None by default).
Null is written as an empty field unless it’s Nulls::Text.
Strings that would read back as null are quoted (the empty string
with Nulls::Empty).
Sourcepub const fn flexible(self, yes: bool) -> SerializerConfig
pub const fn flexible(self, yes: bool) -> SerializerConfig
Sets if records can have a different number of fields (false by
default).
Sourcepub const fn escape_formulas(self, yes: bool) -> SerializerConfig
pub const fn escape_formulas(self, yes: bool) -> SerializerConfig
Sets if strings that spreadsheets would run as formulas are escaped
(false by default).
Spreadsheets run fields that start with =, +, - or @ (or a
tab or carriage return) as formulas, which is a problem when a file
contains data of untrusted users (“CSV
injection”).
With this enabled, such strings are prefixed with ' and quoted
(as recommended by OWASP). Numbers are written as they are.
let config = deser_csv::SerializerConfig::new().escape_formulas(true);
let rows = vec![("=1+2", -3)];
assert_eq!(config.to_string(&rows).unwrap(), "\"'=1+2\",-3\n");Sourcepub const fn bytes(self, format: BytesFormat) -> SerializerConfig
pub const fn bytes(self, format: BytesFormat) -> SerializerConfig
Sets how bytes are represented.
By default bytes are written as base64 (BytesFormat::BASE64).
Values can request a different format (see
bytes) which takes precedence.
Sourcepub fn to_string(&self, value: &dyn Serialize) -> Result<String, Error>
pub fn to_string(&self, value: &dyn Serialize) -> Result<String, Error>
Serializes the records of a value.
The value has to be a sequence of records.
Sourcepub fn to_string_with<F>(
&self,
value: &dyn Serialize,
setup: F,
) -> Result<String, Error>where
F: FnOnce(&mut SerializeDriver<'_>),
pub fn to_string_with<F>(
&self,
value: &dyn Serialize,
setup: F,
) -> Result<String, Error>where
F: FnOnce(&mut SerializeDriver<'_>),
Serializes the records of a value with a configured driver.
The callback is invoked with the driver before the serialization
starts, for instance to add Layers.
Source§impl SerializerConfig
impl SerializerConfig
Sourcepub fn writer<W: Write>(&self, writer: W) -> Writer<W, Serializer>
pub fn writer<W: Write>(&self, writer: W) -> Writer<W, Serializer>
Creates a writer of a stream of records (see
deser::io::Writer).
Every value is a record, the names of the columns are written before
the first one (see headers). A record that fails
to serialize is not written.
use deser_csv::SerializerConfig;
#[derive(deser::Serialize)]
struct Row {
name: &'static str,
age: u32,
}
let mut writer = SerializerConfig::new().writer(Vec::new());
writer.write(&Row { name: "jane", age: 42 }).unwrap();
writer.write(&Row { name: "john", age: 23 }).unwrap();
assert_eq!(writer.into_inner(), b"name,age\njane,42\njohn,23\n");