Skip to main content

SerializerConfig

Struct SerializerConfig 

Source
pub struct SerializerConfig { /* private fields */ }
Expand description

Configures how values are serialized to YAML.

YAML allows the same data to be written in many ways. The defaults follow what is common for hand-written YAML:

  • block collections indented by two spaces (see set_indent), sequences in mappings are indented (set_indent_sequences), empty collections are written as {} and []. Compact collections (see hints) are written in flow style, see set_flow.
  • strings are plain if possible, otherwise single-quoted (double-quoted if they need escapes). Strings are quoted if readers of YAML 1.1 would read them as something else (yes, 0777, timestamps, see set_compat).
  • strings with line breaks are literal block scalars (|), the style of individual strings can be requested (see style).
  • bytes are written as !!binary (see set_binary).
use std::collections::BTreeMap;
use deser_yaml::SerializerConfig;

let mut value = BTreeMap::new();
value.insert("items", vec!["a", "yes"]);
assert_eq!(
    deser_yaml::to_string(&value).unwrap(),
    "items:\n  - a\n  - 'yes'\n"
);

const INDENTLESS: SerializerConfig =
    SerializerConfig::builder().indent_sequences(false).build();
assert_eq!(
    INDENTLESS.to_string(&value).unwrap(),
    "items:\n- a\n- 'yes'\n"
);

to_string works like the to_string function.

Implementations§

Source§

impl SerializerConfig

Source

pub const fn new() -> SerializerConfig

Creates the default configuration.

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 set_indent(&mut self, indent: Indent)

Sets how the output is indented.

The default is Indent::Spaces(2), values outside of 1..=9 are clamped. With Indent::None documents are written on a single line in flow style, the flow policy and Layout hints have no effect then:

use deser::Serialize;
use deser_yaml::{Indent, SerializerConfig};

#[derive(Serialize)]
struct Config {
    name: String,
    ports: Vec<u16>,
}

let config = Config { name: "web".into(), ports: vec![80, 443] };
const WIDE: SerializerConfig =
    SerializerConfig::builder().indent(Indent::Spaces(4)).build();
assert_eq!(
    WIDE.to_string(&config).unwrap(),
    "name: web\nports:\n    - 80\n    - 443\n"
);
const LINE: SerializerConfig =
    SerializerConfig::builder().indent(Indent::None).build();
assert_eq!(
    LINE.to_string(&config).unwrap(),
    "{name: web, ports: [80, 443]}\n"
);
Source

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

Indents sequences that are values of mappings.

By default (true) the dashes of such sequences are indented like the keys of nested mappings (key:\n - a). With false they are at the column of the key (key:\n- a), which is how libyaml, PyYAML and kubectl write YAML.

Source

pub const fn set_flow(&mut self, policy: FlowPolicy)

Sets when collections are written in flow style.

This has no effect with Indent::None where everything is written in flow style.

use deser::Serialize;
use deser_yaml::{FlowPolicy, SerializerConfig};

#[derive(Serialize)]
struct Config {
    ports: Vec<u16>,
    groups: Vec<Vec<u16>>,
}

let config = Config {
    ports: vec![80, 443],
    groups: vec![vec![1], vec![2, 3]],
};
const FLOW: SerializerConfig =
    SerializerConfig::builder().flow(FlowPolicy::LeafIfFits(80)).build();
assert_eq!(
    FLOW.to_string(&config).unwrap(),
    "ports: [80, 443]\ngroups:\n  - [1]\n  - [2, 3]\n"
);
Source

pub const fn set_fold_width(&mut self, width: Option<usize>)

Folds long strings at the given width.

Strings without line breaks that are longer than the width are written as folded block scalars (>) with lines that do not exceed the width if possible. Strings are only folded if they read back unchanged. By default strings are not folded. The width is also used for strings with the Folded hint (80 if not set).

Source

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

Sets how strings are quoted that cannot be written plain.

Source

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

Quotes all strings, including strings with line breaks.

Source

pub const fn set_multiline(&mut self, style: MultilineStyle)

Sets how strings with line breaks are written.

Source

pub const fn set_null_style(&mut self, style: NullStyle)

Sets how null is written.

Source

pub const fn set_compat(&mut self, version: Version)

Sets the oldest YAML version that readers of the output may use.

Plain strings are quoted if a reader of this (or a later) version would read them as something else than a string. The default is Version::V1_1: strings like yes, on, 0777, 1:30 or 2001-12-14 are quoted. With Version::V1_2 they are plain.

use deser_yaml::{SerializerConfig, Version};

assert_eq!(deser_yaml::to_string(&"yes").unwrap(), "'yes'\n");
const V1_2: SerializerConfig =
    SerializerConfig::builder().compat(Version::V1_2).build();
assert_eq!(V1_2.to_string(&"yes").unwrap(), "yes\n");
Source

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

Writes bytes as !!binary.

By default (true) YAML is a format with native bytes: bytes are written as base64 with the !!binary tag, also bytes that request a representation for formats without native bytes (see BytesFallback). With false bytes are represented like in JSON: in the format they request or the BytesFormat of the Context.

use deser::adapters::Base64UrlNoPad;
use deser::{BytesFormat, Context};
use deser_yaml::SerializerConfig;

assert_eq!(
    deser_yaml::to_string(&b"\xfb\xff").unwrap(),
    "!!binary +/8=\n"
);
let config = SerializerConfig::builder()
    .binary(false)
    .context(Context::with(BytesFormat::encoded::<Base64UrlNoPad>()))
    .build();
assert_eq!(config.to_string(&b"\xfb\xff").unwrap(), "-_8\n");

More encodings (such as hex) are provided by deser-encoding. Bytes in other formats than base64 (or sequences) need to be deserialized with the same format in the context.

Source

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

Writes date-times with the !!timestamp tag.

Dates and date-times with offset (Datetime) are written as YAML timestamps. By default they are plain which YAML 1.1 readers resolve as timestamps and YAML 1.2 readers as strings (which date / time types accept). With the tag all readers resolve them as timestamps. Local date-times and times are always strings.

Source

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

Always starts documents with ---.

When writing a stream of documents (see deser::io), documents after the first one always start with ---.

Source

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

Starts documents with a %YAML 1.2 directive.

Source

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

Ends documents with a document end marker (...).

When a stream of documents is read (see deser::io), a document is complete once the next document starts or once it’s ended with .... For streams that stay open (like sockets) this allows the reader to see the end of a document without waiting for the next one.

use deser_yaml::{Serializer, SerializerConfig};

const ENDED: SerializerConfig =
    SerializerConfig::builder().end_documents(true).build();
let mut serializer = Serializer::with_config(ENDED);
serializer.serialize(&"a").unwrap();
serializer.serialize(&"b").unwrap();
assert_eq!(serializer.finish(), "a\n...\n---\nb\n...\n");
Source

pub fn to_string<T: Serialize + ?Sized>( &self, value: &T, ) -> Result<String, Error>

Serializes the given value.

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 given 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 YAML documents (see deser::io::Writer).

Every value is written as a document, documents after the first start with ---. The output of large documents is written in parts while they are serialized.

use deser_yaml::SerializerConfig;

let mut writer = SerializerConfig::new().writer(Vec::new());
writer.write(&"a").unwrap();
writer.write(&vec![1, 2]).unwrap();
assert_eq!(writer.into_inner(), b"a\n---\n- 1\n- 2\n");
Source

pub fn to_writer<W: Write, T: Serialize + ?Sized>( &self, writer: W, value: &T, ) -> Result<(), Error>

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