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 (seehints) are written in flow style, seeset_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, seeset_compat). - strings with line breaks are literal block scalars (
|), the style of individual strings can be requested (seestyle). - bytes are written as
!!binary(seeset_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"
);Implementations§
Source§impl SerializerConfig
impl SerializerConfig
Sourcepub const fn new() -> SerializerConfig
pub const fn new() -> SerializerConfig
Creates the default configuration.
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 set_indent(&mut self, indent: Indent)
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"
);Sourcepub const fn set_indent_sequences(&mut self, yes: bool)
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.
Sourcepub const fn set_flow(&mut self, policy: FlowPolicy)
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"
);Sourcepub const fn set_fold_width(&mut self, width: Option<usize>)
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).
Sourcepub const fn set_quote_style(&mut self, style: QuoteStyle)
pub const fn set_quote_style(&mut self, style: QuoteStyle)
Sets how strings are quoted that cannot be written plain.
Sourcepub const fn set_quote_all(&mut self, yes: bool)
pub const fn set_quote_all(&mut self, yes: bool)
Quotes all strings, including strings with line breaks.
Sourcepub const fn set_multiline(&mut self, style: MultilineStyle)
pub const fn set_multiline(&mut self, style: MultilineStyle)
Sets how strings with line breaks are written.
Sourcepub const fn set_null_style(&mut self, style: NullStyle)
pub const fn set_null_style(&mut self, style: NullStyle)
Sets how null is written.
Sourcepub const fn set_compat(&mut self, version: Version)
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");Sourcepub const fn set_binary(&mut self, yes: bool)
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.
Sourcepub const fn set_timestamp_tag(&mut self, yes: bool)
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.
Sourcepub const fn set_document_start(&mut self, yes: bool)
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 ---.
Sourcepub const fn set_version_directive(&mut self, yes: bool)
pub const fn set_version_directive(&mut self, yes: bool)
Starts documents with a %YAML 1.2 directive.
Sourcepub const fn set_end_documents(&mut self, yes: bool)
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");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 given value.
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 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
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 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");