use std::collections::HashMap;
use std::io::Write;
use crate::error::{Error, ErrorKind};
use crate::limits::Limits;
use crate::value::Value;
mod scalars;
mod tags;
use self::scalars::plain_is_block_safe;
pub(crate) use self::scalars::{
block_scalar_ok, can_fold, double_quoted, emit_double_quoted, expand_folded, is_printable,
looks_like_leading_zero_numeral, needs_explicit_indent, plain_is_safe, plain_text_ok,
single_quoted_ok,
};
pub(crate) use self::tags::{RedefinedHandles, TagDirectives};
#[allow(
clippy::struct_excessive_bools,
reason = "the flags are independent scanner or emitter options, not a state enum"
)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct EmitterOptions {
pub flow: bool,
pub explicit_start: bool,
pub explicit_end: bool,
pub scalar_style: Option<crate::event::ScalarStyle>,
pub indent: usize,
pub indent_sequences: bool,
}
impl EmitterOptions {
#[must_use]
pub const fn with_flow(mut self, value: bool) -> Self {
self.flow = value;
self
}
#[must_use]
pub const fn with_explicit_start(mut self, value: bool) -> Self {
self.explicit_start = value;
self
}
#[must_use]
pub const fn with_explicit_end(mut self, value: bool) -> Self {
self.explicit_end = value;
self
}
#[must_use]
pub const fn with_scalar_style(mut self, value: Option<crate::event::ScalarStyle>) -> Self {
self.scalar_style = value;
self
}
#[must_use]
pub const fn with_indent(mut self, value: usize) -> Self {
self.indent = value;
self
}
#[must_use]
pub const fn with_indent_sequences(mut self, value: bool) -> Self {
self.indent_sequences = value;
self
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PathSegment {
Index(usize),
Key(Value),
}
impl PathSegment {
#[must_use]
pub const fn index(index: usize) -> Self {
Self::Index(index)
}
#[must_use]
pub fn key(key: impl Into<Value>) -> Self {
Self::Key(key.into())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Chomping {
Strip,
Clip,
Keep,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct NodeStyle {
pub scalar_style: Option<crate::event::ScalarStyle>,
pub chomping: Option<Chomping>,
pub flow: Option<bool>,
}
impl NodeStyle {
#[must_use]
pub const fn with_scalar_style(mut self, value: Option<crate::event::ScalarStyle>) -> Self {
self.scalar_style = value;
self
}
#[must_use]
pub const fn with_chomping(mut self, value: Option<Chomping>) -> Self {
self.chomping = value;
self
}
#[must_use]
pub const fn with_flow(mut self, value: Option<bool>) -> Self {
self.flow = value;
self
}
}
#[derive(Clone, Debug, Default)]
pub struct EmitterStyles {
styles: HashMap<Vec<PathSegment>, NodeStyle>,
}
impl EmitterStyles {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn set(&mut self, path: Vec<PathSegment>, style: NodeStyle) {
self.styles.insert(path, style);
}
fn get(&self, path: &[PathSegment]) -> Option<NodeStyle> {
self.styles.get(path).copied()
}
}
impl Default for EmitterOptions {
fn default() -> Self {
Self {
flow: false,
explicit_start: false,
explicit_end: false,
scalar_style: None,
indent: 2,
indent_sequences: false,
}
}
}
pub fn to_string<T: serde::Serialize + ?Sized>(value: &T) -> Result<String, Error> {
to_string_with_limits(value, &Limits::default())
}
pub fn to_string_with_limits<T: serde::Serialize + ?Sized>(
value: &T,
limits: &Limits,
) -> Result<String, Error> {
let value = crate::to_value(value)?;
emit_value_with_limits(&value, limits, EmitterOptions::default())
}
pub fn to_string_with_options<T: serde::Serialize + ?Sized>(
value: &T,
options: &EmitterOptions,
) -> Result<String, Error> {
let value = crate::to_value(value)?;
emit_value_with_limits(&value, &Limits::default(), *options)
}
pub fn to_string_value(value: &Value) -> Result<String, Error> {
to_string_value_with_limits(value, &Limits::default())
}
pub fn to_string_value_with_limits(value: &Value, limits: &Limits) -> Result<String, Error> {
emit_value_with_limits(value, limits, EmitterOptions::default())
}
pub fn to_string_value_with_options(
value: &Value,
options: &EmitterOptions,
) -> Result<String, Error> {
emit_value_with_limits(value, &Limits::default(), *options)
}
pub fn to_string_value_with_styles(value: &Value, styles: &EmitterStyles) -> Result<String, Error> {
emit_value_with_limits_and_styles(value, &Limits::default(), EmitterOptions::default(), styles)
}
pub fn to_string_value_with_limits_and_styles(
value: &Value,
limits: &Limits,
styles: &EmitterStyles,
) -> Result<String, Error> {
emit_value_with_limits_and_styles(value, limits, EmitterOptions::default(), styles)
}
pub fn to_string_value_with_options_and_styles(
value: &Value,
options: &EmitterOptions,
styles: &EmitterStyles,
) -> Result<String, Error> {
emit_value_with_limits_and_styles(value, &Limits::default(), *options, styles)
}
pub fn to_writer_value_with_styles<W: Write>(
writer: &mut W,
value: &Value,
styles: &EmitterStyles,
) -> Result<(), Error> {
emit_value_to_with_styles(
writer,
value,
&Limits::default(),
EmitterOptions::default(),
styles,
)
}
pub fn to_writer_value_with_options_and_styles<W: Write>(
writer: &mut W,
value: &Value,
options: &EmitterOptions,
styles: &EmitterStyles,
) -> Result<(), Error> {
emit_value_to_with_styles(writer, value, &Limits::default(), *options, styles)
}
pub fn to_writer_value_with_limits_and_styles<W: Write>(
writer: &mut W,
value: &Value,
limits: &Limits,
styles: &EmitterStyles,
) -> Result<(), Error> {
emit_value_to_with_styles(writer, value, limits, EmitterOptions::default(), styles)
}
pub fn to_string_documents(values: &[Value]) -> Result<String, Error> {
to_string_documents_with_limits(values, &Limits::default())
}
pub fn to_string_documents_with_limits(values: &[Value], limits: &Limits) -> Result<String, Error> {
let mut output = Vec::new();
emit_documents_to(
Output::direct(&mut output, limits),
values,
limits,
EmitterOptions::default(),
&EmitterStyles::default(),
)?;
String::from_utf8(output).map_err(|error| {
Error::new(ErrorKind::Emitter, "emitter produced invalid UTF-8").with_source(error)
})
}
fn emit_value_with_limits(
value: &Value,
limits: &Limits,
options: EmitterOptions,
) -> Result<String, Error> {
let styles = EmitterStyles::default();
emit_value_with_limits_and_styles(value, limits, options, &styles)
}
fn emit_value_with_limits_and_styles(
value: &Value,
limits: &Limits,
options: EmitterOptions,
styles: &EmitterStyles,
) -> Result<String, Error> {
let mut output = Vec::new();
emit_value_with(
Output::direct(&mut output, limits),
value,
limits,
options,
styles,
)?;
String::from_utf8(output).map_err(|error| {
Error::new(ErrorKind::Emitter, "emitter produced invalid UTF-8").with_source(error)
})
}
fn emit_value_to<W: Write>(
writer: &mut W,
value: &Value,
limits: &Limits,
options: EmitterOptions,
) -> Result<(), Error> {
let styles = EmitterStyles::default();
emit_value_to_with_styles(writer, value, limits, options, &styles)
}
fn emit_value_to_with_styles<W: Write>(
writer: &mut W,
value: &Value,
limits: &Limits,
options: EmitterOptions,
styles: &EmitterStyles,
) -> Result<(), Error> {
emit_value_with(Output::new(writer, limits), value, limits, options, styles)
}
fn emit_value_with<W: Write>(
mut output: Output<'_, W>,
value: &Value,
limits: &Limits,
options: EmitterOptions,
styles: &EmitterStyles,
) -> Result<(), Error> {
limits.validate()?;
validate_options(&options)?;
write_document(&mut output, value, limits, options, styles, false)?;
output.finish()
}
fn emit_documents_to<W: Write>(
mut output: Output<'_, W>,
values: &[Value],
limits: &Limits,
options: EmitterOptions,
styles: &EmitterStyles,
) -> Result<(), Error> {
limits.validate()?;
validate_options(&options)?;
for (index, value) in values.iter().enumerate() {
write_document(&mut output, value, limits, options, styles, index > 0)?;
}
output.finish()
}
#[inline]
fn write_document<W: Write>(
output: &mut Output<'_, W>,
value: &Value,
limits: &Limits,
options: EmitterOptions,
styles: &EmitterStyles,
later: bool,
) -> Result<(), Error> {
let mut directives = TagDirectives::default();
directives.scan(value, limits.max_depth)?;
if !directives.is_empty() {
if later && !options.explicit_end {
output.push_str("...\n")?;
}
output.push_str(&directives.lines())?;
output.push_str("---\n")?;
} else if later || options.explicit_start {
output.push_str("---\n")?;
}
let mut emitter = ValueWriter::new(output, limits, options, styles, directives);
emitter.emit_root(value);
emitter.finish()
}
pub fn to_writer<T: serde::Serialize + ?Sized, W: Write>(
writer: &mut W,
value: &T,
) -> Result<(), Error> {
let value = crate::to_value(value)?;
emit_value_to(
writer,
&value,
&Limits::default(),
EmitterOptions::default(),
)
}
pub fn to_writer_with_limits<T: serde::Serialize + ?Sized, W: Write>(
writer: &mut W,
value: &T,
limits: &Limits,
) -> Result<(), Error> {
let value = crate::to_value(value)?;
emit_value_to(writer, &value, limits, EmitterOptions::default())
}
pub fn to_writer_with_options<T: serde::Serialize + ?Sized, W: Write>(
writer: &mut W,
value: &T,
options: &EmitterOptions,
) -> Result<(), Error> {
let value = crate::to_value(value)?;
emit_value_to(writer, &value, &Limits::default(), *options)
}
pub fn to_writer_value<W: Write>(writer: &mut W, value: &Value) -> Result<(), Error> {
emit_value_to(writer, value, &Limits::default(), EmitterOptions::default())
}
pub fn to_writer_value_with_limits<W: Write>(
writer: &mut W,
value: &Value,
limits: &Limits,
) -> Result<(), Error> {
emit_value_to(writer, value, limits, EmitterOptions::default())
}
pub fn to_writer_value_with_options<W: Write>(
writer: &mut W,
value: &Value,
options: &EmitterOptions,
) -> Result<(), Error> {
emit_value_to(writer, value, &Limits::default(), *options)
}
pub fn to_writer_documents<W: Write>(writer: &mut W, values: &[Value]) -> Result<(), Error> {
to_writer_documents_with_limits(writer, values, &Limits::default())
}
pub fn to_writer_documents_with_limits<W: Write>(
writer: &mut W,
values: &[Value],
limits: &Limits,
) -> Result<(), Error> {
emit_documents_to(
Output::new(writer, limits),
values,
limits,
EmitterOptions::default(),
&EmitterStyles::default(),
)
}
#[derive(Clone, Copy, Debug)]
pub struct Emitter<'a> {
limits: &'a Limits,
options: &'a EmitterOptions,
styles: Option<&'a EmitterStyles>,
}
impl<'a> Emitter<'a> {
#[must_use]
pub const fn new(limits: &'a Limits, options: &'a EmitterOptions) -> Self {
Self {
limits,
options,
styles: None,
}
}
#[must_use]
pub const fn with_styles(mut self, styles: &'a EmitterStyles) -> Self {
self.styles = Some(styles);
self
}
pub fn to_string<T: serde::Serialize + ?Sized>(&self, value: &T) -> Result<String, Error> {
let value = crate::to_value(value)?;
self.value_to_string(&value)
}
pub fn to_writer<T: serde::Serialize + ?Sized, W: Write>(
&self,
writer: &mut W,
value: &T,
) -> Result<(), Error> {
let value = crate::to_value(value)?;
self.value_to_writer(writer, &value)
}
pub fn value_to_string(&self, value: &Value) -> Result<String, Error> {
match self.styles {
Some(styles) => {
emit_value_with_limits_and_styles(value, self.limits, *self.options, styles)
}
None => emit_value_with_limits(value, self.limits, *self.options),
}
}
pub fn value_to_writer<W: Write>(&self, writer: &mut W, value: &Value) -> Result<(), Error> {
match self.styles {
Some(styles) => {
emit_value_to_with_styles(writer, value, self.limits, *self.options, styles)
}
None => emit_value_to(writer, value, self.limits, *self.options),
}
}
pub fn documents_to_string(&self, values: &[Value]) -> Result<String, Error> {
let mut output = Vec::new();
let styles = self.styles.cloned().unwrap_or_default();
emit_documents_to(
Output::direct(&mut output, self.limits),
values,
self.limits,
*self.options,
&styles,
)?;
String::from_utf8(output).map_err(|error| {
Error::new(ErrorKind::Emitter, "emitter produced invalid UTF-8").with_source(error)
})
}
pub fn documents_to_writer<W: Write>(
&self,
writer: &mut W,
values: &[Value],
) -> Result<(), Error> {
let styles = self.styles.cloned().unwrap_or_default();
emit_documents_to(
Output::new(writer, self.limits),
values,
self.limits,
*self.options,
&styles,
)
}
}
fn io_error(error: std::io::Error) -> Error {
Error::new(ErrorKind::Io, "failed to write YAML output").with_source(error)
}
pub(crate) const MAX_IMPLICIT_KEY_CHARS: usize = 128;
const OUTPUT_CHUNK: usize = 8 * 1024;
pub(crate) struct Output<'a, W: Write> {
writer: &'a mut W,
buffered: bool,
direct: bool,
flush_at: usize,
buffer: Vec<u8>,
written: usize,
limits: Limits,
}
impl<'a, W: Write> Output<'a, W> {
pub(crate) fn new(writer: &'a mut W, limits: &Limits) -> Self {
Self {
writer,
buffered: true,
direct: false,
flush_at: OUTPUT_CHUNK,
buffer: Vec::new(),
written: 0,
limits: limits.clone(),
}
}
pub(crate) fn direct(writer: &'a mut W, limits: &Limits) -> Self {
Self {
buffered: false,
direct: true,
..Self::new(writer, limits)
}
}
pub(crate) fn push_str(&mut self, value: &str) -> Result<(), Error> {
let total = self.written.saturating_add(value.len());
self.limits.check_output_bytes(total).map_err(Error::from)?;
self.written = total;
if !self.buffered {
return self.writer.write_all(value.as_bytes()).map_err(io_error);
}
self.buffer.extend_from_slice(value.as_bytes());
if self.buffer.len() >= self.flush_at {
self.flush()?;
}
Ok(())
}
pub(crate) fn hold(&mut self) -> usize {
self.buffered = true;
self.flush_at = usize::MAX;
self.buffer.len()
}
pub(crate) fn insert_held(&mut self, place: usize, text: &str) -> Result<(), Error> {
let total = self.written.saturating_add(text.len());
self.limits.check_output_bytes(total).map_err(Error::from)?;
self.written = total;
self.buffer.splice(place..place, text.bytes());
Ok(())
}
pub(crate) fn release(&mut self) -> Result<(), Error> {
self.buffered = !self.direct;
self.flush_at = OUTPUT_CHUNK;
if self.direct || self.buffer.len() >= OUTPUT_CHUNK {
self.flush()?;
}
Ok(())
}
pub(crate) fn spaces(&mut self, count: usize) -> Result<(), Error> {
const SPACES: &str = " ";
let mut left = count;
while left > 0 {
let chunk = left.min(SPACES.len());
self.push_str(&SPACES[..chunk])?;
left -= chunk;
}
Ok(())
}
fn flush(&mut self) -> Result<(), Error> {
if !self.buffer.is_empty() {
self.writer.write_all(&self.buffer).map_err(io_error)?;
self.buffer.clear();
}
Ok(())
}
pub(crate) fn finish(mut self) -> Result<(), Error> {
self.flush()
}
}
pub(crate) fn validate_options(options: &EmitterOptions) -> Result<(), Error> {
if (2..=9).contains(&options.indent) {
Ok(())
} else {
Err(Error::new(
ErrorKind::Emitter,
format!(
"EmitterOptions::indent must be between 2 and 9, got {}",
options.indent
),
))
}
}
fn nested_tag_error() -> Error {
Error::new(
ErrorKind::Emitter,
"YAML cannot write a tagged value whose payload is also tagged (for example a nested Serde enum)",
)
}
struct ValueWriter<'a, 'w, 's, W: Write> {
output: &'a mut Output<'w, W>,
options: EmitterOptions,
styles: &'s EmitterStyles,
path: Vec<PathSegment>,
limits: Limits,
depth: usize,
error: Option<Error>,
in_flow: bool,
in_key: bool,
directives: TagDirectives,
}
impl<'a, 'w, 's, W: Write> ValueWriter<'a, 'w, 's, W> {
fn new(
output: &'a mut Output<'w, W>,
limits: &Limits,
options: EmitterOptions,
styles: &'s EmitterStyles,
directives: TagDirectives,
) -> Self {
Self {
output,
options,
styles,
path: Vec::new(),
limits: limits.clone(),
depth: 0,
error: None,
in_flow: false,
in_key: false,
directives,
}
}
fn style(&self) -> NodeStyle {
if self.in_key {
NodeStyle::default()
} else {
self.styles.get(&self.path).unwrap_or_default()
}
}
fn scalar_style(&self) -> Option<crate::event::ScalarStyle> {
self.style().scalar_style.or(self.options.scalar_style)
}
fn styles_active(&self) -> bool {
!self.styles.styles.is_empty()
}
fn force_flow(&self) -> bool {
self.style().flow == Some(true)
}
fn push_key(&mut self, key: &Value) {
if self.styles_active() {
self.path.push(PathSegment::Key(key.clone()));
}
}
fn push_index(&mut self, index: usize) {
if self.styles_active() {
self.path.push(PathSegment::Index(index));
}
}
fn pop_path(&mut self) {
if self.styles_active() {
self.path.pop();
}
}
fn fail(&mut self, error: Error) {
if self.error.is_none() {
self.error = Some(error);
}
}
fn push_str(&mut self, value: &str) {
if self.error.is_some() {
return;
}
if let Err(error) = self.output.push_str(value) {
self.error = Some(error);
}
}
fn push(&mut self, value: char) {
let mut buffer = [0_u8; 4];
self.push_str(value.encode_utf8(&mut buffer));
}
fn indent(&mut self, indent: usize) {
if self.error.is_some() {
return;
}
if let Err(error) = self.output.spaces(indent) {
self.error = Some(error);
}
}
fn enter(&mut self) -> bool {
if self.error.is_some() {
return false;
}
self.depth += 1;
if let Err(error) = self.limits.check_depth(self.depth) {
self.depth -= 1;
self.fail(Error::from(error));
return false;
}
true
}
fn leave(&mut self) {
self.depth -= 1;
}
fn push_tag(&mut self, tagged: &crate::tag::TaggedValue) -> bool {
if matches!(tagged.value, Value::Tagged(_)) {
self.fail(nested_tag_error());
return false;
}
match self
.directives
.token(&tagged.tag, RedefinedHandles::default())
{
Ok(token) => {
self.push_str(&token);
true
}
Err(error) => {
self.fail(error);
false
}
}
}
fn finish(&mut self) -> Result<(), Error> {
self.error.take().map_or(Ok(()), Err)
}
fn emit_root(&mut self, value: &Value) {
if self.style().flow.unwrap_or(self.options.flow) {
self.emit_flow(value);
self.push('\n');
} else if let Value::String(text) = value
&& self.use_block_scalar(text)
{
self.emit_block_scalar(text, self.options.indent, true);
} else if let Value::Tagged(tagged) = value
&& let Value::String(text) = &tagged.value
&& self.use_block_scalar(text)
{
if self.push_tag(tagged) {
self.push(' ');
self.emit_block_scalar(text, self.options.indent, true);
}
} else {
match value {
Value::Mapping(mapping) if !mapping.is_empty() => self.emit_mapping(mapping, 0),
Value::Sequence(sequence) if !sequence.is_empty() => {
self.emit_sequence(sequence, 0);
}
_ => {
self.emit_flow(value);
self.push('\n');
}
}
}
if self.options.explicit_end {
self.push_str("...\n");
}
}
fn emit_mapping(&mut self, mapping: &crate::mapping::Mapping, indent: usize) {
self.emit_mapping_items(mapping, indent, false);
}
fn needs_explicit_key(&self, key: &Value) -> bool {
match key {
Value::Sequence(_) | Value::Mapping(_) | Value::Tagged(_) => true,
Value::String(text) => self.key_width(text) > MAX_IMPLICIT_KEY_CHARS,
_ => false,
}
}
fn key_width(&self, text: &str) -> usize {
match self.string_form(text, self.options.scalar_style) {
StringForm::Plain => text.chars().count(),
StringForm::SingleQuoted => text.chars().count() + text.matches('\'').count() + 2,
StringForm::DoubleQuoted => double_quoted(text).chars().count(),
}
}
fn flow_key_is_long(&mut self, key: &Value) -> bool {
match key {
Value::String(_) => self.needs_explicit_key(key),
Value::Tagged(tagged) => {
let Ok(token) = self
.directives
.token(&tagged.tag, RedefinedHandles::default())
else {
return false;
};
let text = match &tagged.value {
Value::String(text) => self.key_width(text),
Value::Bool(value) => {
if *value {
4
} else {
5
}
}
Value::Number(number) => number.to_string().len(),
_ => 0,
};
token.chars().count() + 1 + text > MAX_IMPLICIT_KEY_CHARS
}
_ => false,
}
}
fn emit_key(&mut self, key: &Value) {
let in_key = std::mem::replace(&mut self.in_key, true);
self.emit_flow(key);
self.in_key = in_key;
}
fn emit_mapping_items(
&mut self,
mapping: &crate::mapping::Mapping,
indent: usize,
inline_first: bool,
) {
if !self.enter() {
return;
}
for (index, (key, value)) in mapping.iter().enumerate() {
if self.error.is_some() {
break;
}
if index > 0 || !inline_first {
self.indent(indent);
}
if self.needs_explicit_key(key) {
self.push_str("? ");
self.emit_key(key);
self.push('\n');
self.indent(indent);
self.push(':');
} else {
self.emit_key(key);
self.push(':');
}
self.push_key(key);
if self.force_flow()
&& matches!(
value,
Value::Mapping(_) | Value::Sequence(_) | Value::Tagged(_)
)
{
self.push(' ');
self.emit_flow(value);
self.push('\n');
} else if Self::needs_block_value(value) {
self.push('\n');
self.emit_node(value, self.block_value_indent(value, indent));
} else {
self.push(' ');
self.emit_inline_value(value, indent + self.options.indent);
}
self.pop_path();
}
self.leave();
}
fn block_value_indent(&self, value: &Value, indent: usize) -> usize {
let sequence_like = matches!(value, Value::Sequence(sequence) if !sequence.is_empty());
if !self.options.indent_sequences && sequence_like {
indent
} else {
indent + self.options.indent
}
}
fn emit_sequence(&mut self, sequence: &[Value], indent: usize) {
self.emit_sequence_items(sequence, indent, false);
}
fn emit_sequence_items(&mut self, sequence: &[Value], indent: usize, inline_first: bool) {
if !self.enter() {
return;
}
let step = self.options.indent;
for (index, item) in sequence.iter().enumerate() {
if self.error.is_some() {
break;
}
if index > 0 || !inline_first {
self.indent(indent);
}
self.push('-');
self.push_index(index);
if self.force_flow()
&& matches!(
item,
Value::Mapping(_) | Value::Sequence(_) | Value::Tagged(_)
)
{
self.push(' ');
self.emit_flow(item);
self.push('\n');
} else if let Value::Sequence(inner) = item
&& !inner.is_empty()
{
self.indent(step - 1);
self.emit_sequence_items(inner, indent + step, true);
} else if let Value::Mapping(mapping) = item
&& !mapping.is_empty()
{
self.indent(step - 1);
self.emit_mapping_items(mapping, indent + step, true);
} else if Self::needs_block_value(item) {
self.push('\n');
self.emit_node(item, indent + step);
} else {
self.push(' ');
self.emit_inline_value(item, indent + step);
}
self.pop_path();
}
self.leave();
}
fn emit_node(&mut self, value: &Value, indent: usize) {
match value {
Value::Mapping(mapping) if !mapping.is_empty() => self.emit_mapping(mapping, indent),
Value::Sequence(sequence) if !sequence.is_empty() => {
self.emit_sequence(sequence, indent);
}
Value::Tagged(tagged) => {
self.indent(indent);
if !self.push_tag(tagged) {
return;
}
self.push('\n');
if !tagged.value.is_null() {
self.emit_node(&tagged.value, indent);
}
}
_ => {
self.indent(indent);
self.emit_flow(value);
self.push('\n');
}
}
}
fn needs_block_value(value: &Value) -> bool {
match value {
Value::Mapping(mapping) => !mapping.is_empty(),
Value::Sequence(sequence) => !sequence.is_empty(),
Value::Tagged(tagged) => Self::needs_block_value(&tagged.value),
_ => false,
}
}
fn emit_inline_value(&mut self, value: &Value, indent: usize) {
match value {
Value::Mapping(mapping) if !mapping.is_empty() => {
self.push('\n');
self.emit_mapping(mapping, indent);
}
Value::Sequence(sequence) if !sequence.is_empty() => {
self.push('\n');
self.emit_sequence(sequence, indent);
}
Value::Tagged(tagged) => {
if !self.push_tag(tagged) {
return;
}
if tagged.value.is_null() {
self.push('\n');
} else if let Value::String(text) = &tagged.value
&& self.use_block_scalar(text)
{
self.push(' ');
self.emit_block_scalar(text, indent, false);
} else if Self::needs_block_value(&tagged.value) {
self.push('\n');
self.emit_node(&tagged.value, indent);
} else {
self.push(' ');
self.emit_flow(&tagged.value);
self.push('\n');
}
}
Value::String(text) if self.use_block_scalar(text) => {
self.emit_block_scalar(text, indent, false);
}
_ => {
self.emit_flow(value);
self.push('\n');
}
}
}
fn use_block_scalar(&self, text: &str) -> bool {
if self.in_flow || self.in_key {
return false;
}
let block_style = match self.scalar_style() {
Some(
crate::event::ScalarStyle::SingleQuoted | crate::event::ScalarStyle::DoubleQuoted,
) => return false,
Some(crate::event::ScalarStyle::Literal | crate::event::ScalarStyle::Folded) => true,
_ => text.contains('\n'),
};
block_style && block_scalar_ok(text)
}
#[allow(
clippy::cast_possible_truncation,
reason = "the indentation indicator is a single digit in 1..=9"
)]
fn emit_block_scalar(&mut self, text: &str, content_indent: usize, root: bool) {
let content_indent = if root {
content_indent.min(8)
} else {
content_indent
};
let trailing = text.chars().rev().take_while(|ch| *ch == '\n').count();
let body = &text[..text.len().saturating_sub(trailing)];
let folded = matches!(self.scalar_style(), Some(crate::event::ScalarStyle::Folded))
&& can_fold(body);
let folded_body;
let inferred = if trailing == 0 {
Chomping::Strip
} else if trailing == 1 && !body.is_empty() {
Chomping::Clip
} else {
Chomping::Keep
};
let requested = self.style().chomping;
let chomping = match requested {
Some(Chomping::Strip) if trailing == 0 => Chomping::Strip,
Some(Chomping::Clip)
if (trailing == 1 && !body.is_empty()) || (body.is_empty() && trailing == 0) =>
{
Chomping::Clip
}
Some(Chomping::Keep) if trailing > 0 || body.is_empty() => Chomping::Keep,
_ => inferred,
};
let indicator = if folded { '>' } else { '|' };
self.push(indicator);
if needs_explicit_indent(text) {
let indicator = if root {
content_indent + 1
} else {
self.options.indent
};
self.push(char::from_digit(indicator as u32, 10).unwrap_or('0'));
}
match chomping {
Chomping::Strip => self.push('-'),
Chomping::Clip => {}
Chomping::Keep => self.push('+'),
}
self.push('\n');
let body = if folded {
folded_body = expand_folded(body);
folded_body.as_str()
} else {
body
};
if body.is_empty() {
for _ in 0..trailing {
self.push('\n');
}
} else {
for line in body.split('\n') {
if !line.is_empty() {
self.indent(content_indent);
self.push_str(line);
}
self.push('\n');
}
for _ in 1..trailing {
self.push('\n');
}
}
}
fn emit_flow(&mut self, value: &Value) {
match value {
Value::Null => self.push_str("null"),
Value::Bool(value) => self.push_str(if *value { "true" } else { "false" }),
Value::Number(value) => self.push_str(&value.to_string()),
Value::String(value) => self.emit_string(value),
Value::Sequence(sequence) if sequence.is_empty() => self.push_str("[]"),
Value::Mapping(mapping) if mapping.is_empty() => self.push_str("{}"),
Value::Sequence(sequence) => {
if !self.enter() {
return;
}
let in_flow = std::mem::replace(&mut self.in_flow, true);
self.push('[');
for (index, item) in sequence.iter().enumerate() {
if index > 0 {
self.push_str(", ");
}
self.push_index(index);
self.emit_flow(item);
self.pop_path();
}
self.push(']');
self.in_flow = in_flow;
self.leave();
}
Value::Mapping(mapping) => {
if !self.enter() {
return;
}
let in_flow = std::mem::replace(&mut self.in_flow, true);
self.push('{');
for (index, (key, value)) in mapping.iter().enumerate() {
if index > 0 {
self.push_str(", ");
}
let explicit = Self::needs_block_value(key) || self.flow_key_is_long(key);
if explicit {
self.push_str("? ");
}
self.emit_key(key);
if explicit && !matches!(key, Value::Tagged(tagged) if tagged.value.is_null()) {
self.push(' ');
}
self.push_str(": ");
self.push_key(key);
self.emit_flow(value);
self.pop_path();
}
self.push('}');
self.in_flow = in_flow;
self.leave();
}
Value::Tagged(tagged) => {
if !self.push_tag(tagged) {
return;
}
if tagged.value.is_null() {
if self.in_flow {
self.push(' ');
}
} else {
self.push(' ');
self.emit_flow(&tagged.value);
}
}
}
}
fn string_form(&self, value: &str, style: Option<crate::event::ScalarStyle>) -> StringForm {
match style {
Some(crate::event::ScalarStyle::SingleQuoted) if single_quoted_ok(value) => {
StringForm::SingleQuoted
}
Some(
crate::event::ScalarStyle::SingleQuoted
| crate::event::ScalarStyle::DoubleQuoted
| crate::event::ScalarStyle::Literal
| crate::event::ScalarStyle::Folded,
) => StringForm::DoubleQuoted,
_ if self.in_flow && plain_is_safe(value) => StringForm::Plain,
_ if !self.in_flow && plain_is_block_safe(value) => StringForm::Plain,
_ => StringForm::DoubleQuoted,
}
}
fn emit_string(&mut self, value: &str) {
match self.string_form(value, self.scalar_style()) {
StringForm::SingleQuoted => {
self.push('\'');
for (index, part) in value.split('\'').enumerate() {
if index > 0 {
self.push_str("''");
}
self.push_str(part);
}
self.push('\'');
}
StringForm::DoubleQuoted => self.push_str(&double_quoted(value)),
StringForm::Plain => self.push_str(value),
}
}
}
#[derive(Clone, Copy)]
enum StringForm {
Plain,
SingleQuoted,
DoubleQuoted,
}
#[cfg(test)]
mod tests {
use crate::value::Value;
#[test]
fn emits_and_reparses_scalars_and_collections() {
let mut mapping = crate::Mapping::new();
mapping.insert(Value::from("plain"), Value::from("text"));
mapping.insert(Value::from("ambiguous"), Value::from("true"));
mapping.insert(
Value::from("items"),
Value::Sequence(vec![Value::from(1_u64), Value::from("x")]),
);
let value = Value::Mapping(mapping);
let text = crate::to_string(&value).expect("emit");
assert!(text.contains("ambiguous: \"true\""));
let reparsed = crate::parse_value(&text).expect("reparse");
assert_eq!(reparsed, value);
}
#[test]
fn emits_tagged_values_and_round_trips_enums() {
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
enum E {
Unit,
Tuple(u64, u64),
}
let text = crate::to_string(&E::Unit).expect("emit");
let value: E = crate::from_str(&text).expect("decode");
assert_eq!(value, E::Unit);
let text = crate::to_string(&E::Tuple(1, 2)).expect("emit");
let value: E = crate::from_str(&text).expect("decode");
assert_eq!(value, E::Tuple(1, 2));
}
#[test]
fn generic_emitters_accept_unsized_serializable_values() {
let scalar: &str = "sample";
assert_eq!(crate::to_string(scalar).expect("emit str"), "sample\n");
let sequence: &[u8] = &[1, 2, 3];
let mut output = Vec::new();
crate::to_writer(&mut output, sequence).expect("emit slice");
assert_eq!(
crate::parse_value(std::str::from_utf8(&output).expect("UTF-8 output"))
.expect("parse sequence"),
Value::Sequence(vec![1_u64.into(), 2_u64.into(), 3_u64.into()])
);
}
}
#[cfg(test)]
mod tag_form_tests {
use super::RedefinedHandles;
use super::tags::{TagForm, needs_directive};
use crate::tag::Tag;
#[test]
fn needs_directive_agrees_with_the_tag_form() {
let tags = [
Tag::local("x"),
Tag::local("a b"),
Tag::local(""),
Tag::new("!", "x"),
Tag::new("!e-", "x"),
Tag::new("tag:yaml.org,2002:", "str"),
Tag::new("tag:yaml.org,2002:", ""),
Tag::new("tag:yaml.org,2002:", "a b"),
Tag::new("tag:x:", "y"),
Tag::new("tag:x:", "50%25"),
Tag::new("tag:x:", "50%"),
Tag::new("tag:x:", "50%2"),
Tag::new("tag:x:", "50%zz"),
Tag::new("tag:x:", "a b"),
Tag::new("tag:x:", "é"),
Tag::new("tag:x:", "[a],b"),
Tag::new("", "foobar"),
Tag::new("", "tag:x:y"),
Tag::new("", "1abc:x"),
Tag::new("", "a+b-c.d:x"),
Tag::new("", "a_b:x"),
Tag::new("foo", "bar"),
Tag::new("x", "y"),
Tag::new("x", ""),
Tag::new("", "x"),
Tag::new("", ""),
];
for tag in tags {
let form = TagForm::of(&tag, RedefinedHandles::default());
let directive = !matches!(form, Ok(TagForm::Token(_)));
assert_eq!(needs_directive(&tag), directive, "{tag:?}: {form:?}");
}
}
}
#[cfg(test)]
mod value_tests {
use crate::value::Value;
#[test]
fn existing_tagged_values_round_trip_through_the_value_emitter() {
for input in ["!Custom text\n", "!Unit\n", "!Tag [a, b]\n"] {
let value = crate::parse_value(input).expect("parse");
let text = crate::to_string_value(&value).expect("emit");
let decoded = crate::parse_value(&text).expect("reparse");
assert_eq!(decoded, value, "input={input:?} output={text:?}");
assert!(matches!(decoded, Value::Tagged(_)));
}
}
}
#[cfg(test)]
mod collection_tests {
#[test]
fn mapping_sequences_are_indentless_and_sequence_mappings_are_compact() {
let value = crate::parse_value("traces:\n - a\n - b\nitems:\n - k: v\n").unwrap();
let text = crate::to_string_value(&value).expect("emit");
assert_eq!(text, "traces:\n- a\n- b\nitems:\n- k: v\n");
assert_eq!(crate::parse_value(&text).unwrap(), value);
}
#[test]
fn block_scalars_need_no_flow_quoting_and_control_escapes_are_named() {
assert_eq!(crate::to_string("a, b").unwrap(), "a, b\n");
assert_eq!(crate::to_string("a[b").unwrap(), "a[b\n");
assert_eq!(crate::to_string("\u{1b}[41m").unwrap(), "\"\\e[41m\"\n");
}
#[test]
fn nested_and_tagged_collections_round_trip() {
for input in [
"key:\n - a\n - b\n",
"key: !Tag\n - a\n - b\n",
"key: !Tag\n a: b\n",
"1: one\n2:\n nested: true\n",
"empty: {}\nitems: []\n",
"? [a, b]\n: value\n",
] {
let value = crate::parse_value(input).expect("parse");
let text = crate::to_string_value(&value).expect("emit");
let decoded = crate::parse_value(&text).expect("reparse");
assert_eq!(decoded, value, "input={input:?} output={text:?}");
}
}
}
#[cfg(test)]
mod options_tests {
use super::EmitterOptions;
use crate::value::Value;
#[test]
fn flow_and_document_options_round_trip() {
let value = crate::parse_value("a:\n - 1\n - 2\n").expect("parse");
let flow = crate::to_string_value_with_options(
&value,
&EmitterOptions {
flow: true,
explicit_start: true,
explicit_end: true,
..EmitterOptions::default()
},
)
.expect("flow emit");
assert!(flow.starts_with("---\n{"));
assert!(flow.ends_with("...\n"));
let decoded = crate::parse_value(&flow).expect("flow reparse");
assert_eq!(decoded, value);
let first = crate::parse_value("a: 1\n").expect("first");
let second = crate::parse_value("b: 2\n").expect("second");
let documents = crate::to_string_documents(&[first, second]).expect("documents");
let limits = crate::Limits {
max_documents: 2,
..crate::Limits::default()
};
let decoded =
crate::parse_documents_with_limits(&documents, &limits).expect("reparse documents");
assert_eq!(decoded.len(), 2);
assert_eq!(decoded[1]["b"], Value::from(2_u64));
}
}
#[cfg(test)]
mod ambiguity_tests {
use crate::value::Value;
#[test]
fn ambiguous_strings_round_trip() {
let strings = [
"",
"null",
"true",
"0123",
"0b11",
"1e3",
"a: b",
"a #b",
" leading",
"trailing ",
"-",
"?",
":",
"---",
"...",
"yes",
"line\nbreak",
"quote\"slash\\",
"é",
];
let value = Value::Sequence(strings.iter().map(|text| Value::from(*text)).collect());
let text = crate::to_string_value(&value).expect("emit");
let decoded = crate::parse_value(&text).expect("reparse");
assert_eq!(decoded, value, "output={text:?}");
}
}
#[cfg(test)]
mod scalar_style_tests {
use crate::event::ScalarStyle;
use crate::value::Value;
#[test]
fn scalar_style_options_are_applied() {
let value = Value::from("plain text");
let text = crate::to_string_value_with_options(
&value,
&super::EmitterOptions {
scalar_style: Some(ScalarStyle::SingleQuoted),
..super::EmitterOptions::default()
},
)
.expect("single quote");
assert_eq!(text, "'plain text'\n");
let text = crate::to_string_value_with_options(
&value,
&super::EmitterOptions {
scalar_style: Some(ScalarStyle::DoubleQuoted),
..super::EmitterOptions::default()
},
)
.expect("double quote");
assert_eq!(text, "\"plain text\"\n");
assert_eq!(crate::parse_value(&text).unwrap(), value);
}
}
#[cfg(test)]
mod output_limit_tests {
use crate::value::Value;
#[test]
fn output_limits_are_enforced_for_values_events_and_documents() {
let value = Value::from("long enough to exceed the limit");
let limits = crate::Limits {
max_output_bytes: 3,
..crate::Limits::default()
};
let error = crate::to_string_value_with_limits(&value, &limits).expect_err("value limit");
assert_eq!(error.kind(), crate::ErrorKind::Limit);
let documents = crate::parse_documents_with_limits(
"a: 1\n---\nb: 2\n",
&crate::Limits {
max_documents: 2,
..crate::Limits::default()
},
)
.expect("documents");
let error = crate::to_string_documents_with_limits(&documents, &limits)
.expect_err("document limit");
assert_eq!(error.kind(), crate::ErrorKind::Limit);
let events: Vec<crate::Event<'_>> = crate::parse_events("a: 1\n")
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
let error = crate::to_string_events_with_limits(&events, &limits).expect_err("event limit");
assert_eq!(error.kind(), crate::ErrorKind::Limit);
}
}
#[cfg(test)]
mod tag_token_tests {
use crate::tag::{Tag, TaggedValue};
use crate::value::Value;
#[test]
fn expanded_tags_use_verbatim_syntax() {
let value = Value::from(TaggedValue::new(
Tag::new("tag:example.com,2026:", "foo"),
Value::from("x"),
));
let text = crate::to_string_value(&value).expect("emit");
assert!(text.contains("!<tag:example.com,2026:foo>"), "{text:?}");
let decoded = crate::parse_value(&text).expect("reparse");
assert!(decoded.is_tagged());
}
}
#[cfg(test)]
mod writer_tests {
use crate::value::Value;
#[test]
fn document_writer_streams_parseable_output() {
let values = vec![
crate::parse_value("a: 1\n").expect("first"),
crate::parse_value("b: 2\n").expect("second"),
];
let mut output = Vec::new();
crate::to_writer_documents(&mut output, &values).expect("write");
let limits = crate::Limits {
max_documents: 2,
..crate::Limits::default()
};
let decoded = crate::parse_documents_with_limits(
std::str::from_utf8(&output).expect("utf8"),
&limits,
)
.expect("reparse");
assert_eq!(decoded.len(), 2);
assert_eq!(decoded[1]["b"], Value::from(2_u64));
}
}
#[cfg(test)]
mod writer_option_tests {
#[test]
fn writer_options_apply_and_round_trip() {
let value = crate::parse_value("a: 1\n").expect("parse");
let mut output = Vec::new();
crate::to_writer_value_with_options(
&mut output,
&value,
&super::EmitterOptions {
flow: true,
explicit_start: true,
..super::EmitterOptions::default()
},
)
.expect("write");
let text = std::str::from_utf8(&output).expect("utf8");
assert!(text.starts_with("---\n{"));
assert_eq!(crate::parse_value(text).expect("reparse"), value);
}
}
#[cfg(test)]
mod streaming_writer_tests {
#[test]
fn value_writer_is_incremental_and_limits_output() {
let value = crate::parse_value("a: 1\n").expect("parse");
let mut output = Vec::new();
crate::to_writer_value(&mut output, &value).expect("write");
assert_eq!(
std::str::from_utf8(&output).expect("utf8"),
crate::to_string_value(&value).expect("string")
);
let limits = crate::Limits {
max_output_bytes: 2,
..crate::Limits::default()
};
let mut limited = Vec::new();
let error =
crate::to_writer_value_with_limits(&mut limited, &value, &limits).expect_err("limit");
assert_eq!(error.kind(), crate::ErrorKind::Limit);
assert!(limited.len() <= 2);
}
}
#[cfg(test)]
mod builder_tests;
#[cfg(test)]
mod indent_tests;
#[cfg(test)]
mod tagged_block_scalar_tests;
#[cfg(test)]
mod value_block_scalar_tests;