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

Source

pub const fn new() -> SerializerConfig

Creates the default configuration (CSV).

Source

pub const fn builder() -> SerializerConfigBuilder

Returns a builder for the configuration (see SerializerConfigBuilder).

Source

pub const fn into_builder(self) -> SerializerConfigBuilder

Returns a builder that starts with this configuration.

Source

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.

Source

pub fn context(&self) -> &Context

Returns the context the values are serialized in.

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 set_delimiter(&mut self, delimiter: u8)

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

Source

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

Source

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

Source

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.

Source

pub const fn set_terminator(&mut self, terminator: Terminator)

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

Source

pub const fn set_quote_style(&mut self, style: QuoteStyle)

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

Source

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.

Source

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

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

Source

pub const fn set_flexible(&mut self, yes: bool)

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

Source

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

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.

Source

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

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

pub fn to_writer<W: Write, T: Serialize + ?Sized>( &self, writer: W, value: &T, ) -> 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.