Skip to main content

SerializerConfig

Struct SerializerConfig 

Source
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

Source

pub const fn new() -> SerializerConfig

Creates the default configuration (CSV).

Source

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");
Source

pub const fn delimiter(self, delimiter: u8) -> SerializerConfig

Sets the character that separates fields (, by default).

Source

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).

Source

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).

Source

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.

Source

pub const fn terminator(self, terminator: Terminator) -> SerializerConfig

Sets the line ending (\n by default, see Terminator).

Source

pub const fn quote_style(self, style: QuoteStyle) -> SerializerConfig

Sets when fields are quoted (QuoteStyle::Necessary by default).

Source

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.

Source

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"
);
Source

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).

Source

pub const fn flexible(self, yes: bool) -> SerializerConfig

Sets if records can have a different number of fields (false by default).

Source

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");
Source

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.

Source

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.

Source

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

Source

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");
Source

pub fn to_writer<W: Write>( &self, writer: W, value: &dyn Serialize, ) -> Result<(), Error>

Serializes the records of a value to a writer.

See to_writer.

Trait Implementations§

Source§

impl Clone for SerializerConfig

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SerializerConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for SerializerConfig

Source§

fn default() -> SerializerConfig

Returns the “default value” for a type. Read more
Source§

impl Eq for SerializerConfig

Source§

impl PartialEq for SerializerConfig

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for SerializerConfig

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.