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 set_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
set_nulls) and bytes as base64 (or the
BytesFormat of the context). Fields are quoted if necessary (see
set_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::builder().delimiter(b';').terminator(Terminator::CrLf).build();
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 builder() -> SerializerConfigBuilder
pub const fn builder() -> SerializerConfigBuilder
Returns a builder for the configuration (see SerializerConfigBuilder).
Sourcepub const fn into_builder(self) -> SerializerConfigBuilder
pub const fn into_builder(self) -> SerializerConfigBuilder
Returns a builder that starts with this configuration.
Sourcepub fn set_context(&mut self, context: Context)
pub fn set_context(&mut self, context: Context)
Sets the context the values are serialized in.
The values of the context are the defaults of the extension values
of the state (see Context), for instance
the BytesFormat. The serializers and
writers created with the configuration use this context. A context set on
the driver takes precedence.
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 set_delimiter(&mut self, delimiter: u8)
pub const fn set_delimiter(&mut self, delimiter: u8)
Sets the character that separates fields (, by default).
Sourcepub const fn set_quote(&mut self, quote: Option<u8>)
pub const fn set_quote(&mut self, quote: Option<u8>)
Sets the character that quotes fields (" by default).
Without quotes, fields that need them are an error (unless they
can be escaped, see set_escape).
Sourcepub const fn set_double_quote(&mut self, yes: bool)
pub const fn set_double_quote(&mut self, yes: bool)
Sets if quotes in quoted fields are doubled (true by default).
Otherwise they are escaped (see set_escape).
Sourcepub const fn set_escape(&mut self, escape: Escape)
pub const fn set_escape(&mut self, escape: Escape)
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 set_terminator(&mut self, terminator: Terminator)
pub const fn set_terminator(&mut self, terminator: Terminator)
Sets the line ending (\n by default, see Terminator).
Sourcepub const fn set_quote_style(&mut self, style: QuoteStyle)
pub const fn set_quote_style(&mut self, style: QuoteStyle)
Sets when fields are quoted (QuoteStyle::Necessary by default).
Sourcepub const fn set_headers(&mut self, yes: bool)
pub const fn set_headers(&mut self, yes: bool)
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 set_columns). Records that are sequences have no
names.
Sourcepub const fn set_columns(&mut self, names: &'static [&'static str])
pub const fn set_columns(&mut self, names: &'static [&'static str])
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::builder()
.columns(&["kind", "radius", "width", "height"]).build();
assert_eq!(
config.to_string(&shapes).unwrap(),
"kind,radius,width,height\ncircle,1.0,,\nrect,,2.0,3.0\n"
);Sourcepub const fn set_nulls(&mut self, nulls: Nulls)
pub const fn set_nulls(&mut self, nulls: Nulls)
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 set_flexible(&mut self, yes: bool)
pub const fn set_flexible(&mut self, yes: bool)
Sets if records can have a different number of fields (false by
default).
Sourcepub const fn set_escape_formulas(&mut self, yes: bool)
pub const fn set_escape_formulas(&mut self, yes: bool)
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::builder().escape_formulas(true).build();
let rows = vec![("=1+2", -3)];
assert_eq!(config.to_string(&rows).unwrap(), "\"'=1+2\",-3\n");Sourcepub fn to_string<T: Serialize + ?Sized>(
&self,
value: &T,
) -> Result<String, Error>
pub fn to_string<T: Serialize + ?Sized>( &self, value: &T, ) -> Result<String, Error>
Serializes the records of a value.
The value has to be a sequence of records.
Sourcepub fn to_string_with<F, T: Serialize + ?Sized>(
&self,
value: &T,
setup: F,
) -> Result<String, Error>where
F: FnOnce(&mut SerializeDriver<'_>),
pub fn to_string_with<F, T: Serialize + ?Sized>(
&self,
value: &T,
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 set_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");