use std::collections::HashMap;
use std::fmt::Write as _;
use std::io::Write;
use crate::error::{Error, ErrorKind};
use crate::limits::Limits;
use crate::value::Value;
#[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)?;
let mut emitter = ValueWriter::new(&mut output, limits, options, styles);
emitter.emit_root(value);
emitter.finish()?;
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() {
if index > 0 {
output.push_str("---\n")?;
}
let mut emitter = ValueWriter::new(&mut output, limits, options, styles);
emitter.emit_root(value);
emitter.finish()?;
}
output.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,
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,
buffer: Vec::new(),
written: 0,
limits: limits.clone(),
}
}
pub(crate) fn direct(writer: &'a mut W, limits: &Limits) -> Self {
Self {
buffered: false,
..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() >= 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,
}
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,
) -> Self {
Self {
output,
options,
styles,
path: Vec::new(),
limits: limits.clone(),
depth: 0,
error: None,
in_flow: false,
in_key: false,
}
}
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;
}
self.push_str(&tag_token(&tagged.tag));
true
}
fn finish(self) -> Result<(), Error> {
self.error.map_or(Ok(()), Err)
}
fn emit_root(&mut self, value: &Value) {
if self.options.explicit_start {
self.push_str("---\n");
}
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);
} 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);
}
} 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) => {
text.chars().count() > MAX_IMPLICIT_KEY_CHARS
|| (!plain_is_block_safe(text)
&& double_quoted(text).chars().count() > 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);
} 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);
}
_ => {
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)
}
fn emit_block_scalar(&mut self, text: &str, content_indent: usize) {
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) {
self.push(char::from_digit(self.options.indent as u32, 10).expect("validated"));
}
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)
|| (matches!(key, Value::String(_)) && self.needs_explicit_key(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 emit_string(&mut self, value: &str) {
match self.scalar_style() {
Some(crate::event::ScalarStyle::SingleQuoted) if single_quoted_ok(value) => {
self.push('\'');
for (index, part) in value.split('\'').enumerate() {
if index > 0 {
self.push_str("''");
}
self.push_str(part);
}
self.push('\'');
}
Some(
crate::event::ScalarStyle::SingleQuoted
| crate::event::ScalarStyle::DoubleQuoted
| crate::event::ScalarStyle::Literal
| crate::event::ScalarStyle::Folded,
) => {
self.push_str(&double_quoted(value));
}
_ if self.in_flow && plain_is_safe(value) => self.push_str(value),
_ if !self.in_flow && plain_is_block_safe(value) => self.push_str(value),
_ => self.push_str(&double_quoted(value)),
}
}
}
const CORE_PREFIX: &str = "tag:yaml.org,2002:";
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct RedefinedHandles {
pub(crate) primary: bool,
pub(crate) secondary: bool,
}
pub(crate) fn tag_token(tag: &crate::tag::Tag) -> String {
tag_token_with(tag, RedefinedHandles::default())
}
pub(crate) fn tag_token_with(tag: &crate::tag::Tag, redefined: RedefinedHandles) -> String {
let suffix = tag.suffix();
let mut output = String::with_capacity(tag.handle().len() + suffix.len() + 3);
match tag.handle() {
"!" if suffix.is_empty() => output.push('!'),
"!" if !redefined.primary => {
output.push('!');
escape_tag(suffix, false, &mut output);
}
CORE_PREFIX if !redefined.secondary && !suffix.is_empty() => {
output.push_str("!!");
escape_tag(suffix, false, &mut output);
}
handle => {
output.push_str("!<");
escape_tag(handle, true, &mut output);
escape_tag(suffix, true, &mut output);
output.push('>');
}
}
output
}
fn escape_tag(text: &str, verbatim: bool, output: &mut String) {
for ch in text.chars() {
let raw = ch.is_ascii_alphanumeric()
|| matches!(
ch,
'-' | '#'
| ';'
| '/'
| '?'
| ':'
| '@'
| '&'
| '='
| '+'
| '$'
| '_'
| '.'
| '~'
| '*'
| '\''
| '('
| ')'
)
|| (verbatim && matches!(ch, '!' | ',' | '[' | ']' | '%'));
if raw {
output.push(ch);
} else {
let mut buffer = [0_u8; 4];
for byte in ch.encode_utf8(&mut buffer).bytes() {
let _ = write!(output, "%{byte:02X}");
}
}
}
}
pub(crate) fn is_printable(ch: char) -> bool {
matches!(
ch,
'\t' | '\n'
| '\r'
| ' '..='~'
| '\u{85}'
| '\u{a0}'..='\u{d7ff}'
| '\u{e000}'..='\u{fffd}'
| '\u{10000}'..='\u{10ffff}'
)
}
pub(crate) fn is_raw_char(ch: char) -> bool {
is_printable(ch)
&& !matches!(
ch,
'\n' | '\r' | '\u{85}' | '\u{2028}' | '\u{2029}' | '\u{feff}'
)
}
fn is_flow_indicator(ch: char) -> bool {
matches!(ch, ',' | '[' | ']' | '{' | '}')
}
pub(crate) fn plain_text_ok(value: &str, flow: bool) -> bool {
let mut chars = value.chars();
let Some(first) = chars.next() else {
return false;
};
let second = chars.next();
if first.is_whitespace()
|| value.ends_with(char::is_whitespace)
|| value.starts_with("---")
|| value.starts_with("...")
{
return false;
}
let leading_ok = match first {
'-' => second.is_some_and(|next| next != ' ' && !(flow && is_flow_indicator(next))),
'?' | ':' => !flow && second.is_some_and(|next| next != ' '),
',' | '[' | ']' | '{' | '}' | '#' | '&' | '*' | '!' | '|' | '>' | '\'' | '"' | '%'
| '@' | '`' => false,
_ => true,
};
if !leading_ok {
return false;
}
let mut previous = None;
let mut chars = value.chars().peekable();
while let Some(ch) = chars.next() {
if !is_raw_char(ch) || ch == '\t' {
return false;
}
if flow && (is_flow_indicator(ch) || ch == ':') {
return false;
}
if ch == ':' && chars.peek().is_none_or(|next| *next == ' ') {
return false;
}
if ch == '#' && previous == Some(' ') {
return false;
}
previous = Some(ch);
}
true
}
fn resolves_to_string(value: &str) -> bool {
crate::resolver::plain_resolves_to_string(value)
}
pub(crate) fn plain_is_safe(value: &str) -> bool {
plain_text_ok(value, true) && resolves_to_string(value)
}
fn plain_is_block_safe(value: &str) -> bool {
plain_text_ok(value, false) && resolves_to_string(value)
}
pub(crate) fn single_quoted_ok(value: &str) -> bool {
value.chars().all(is_raw_char)
}
pub(crate) fn block_scalar_ok(value: &str) -> bool {
value.chars().all(|ch| ch == '\n' || is_raw_char(ch)) && !has_whitespace_only_line(value)
}
pub(crate) fn can_fold(body: &str) -> bool {
if body.starts_with('\n') || body.contains(['\t', '\r']) {
return false;
}
body.split('\n')
.all(|line| !line.starts_with(' ') && !line.ends_with(' '))
}
pub(crate) fn expand_folded(body: &str) -> String {
let mut output = String::with_capacity(body.len().saturating_add(8));
let mut chars = body.chars().peekable();
while let Some(ch) = chars.next() {
output.push(ch);
if ch == '\n' {
output.push('\n');
while chars.peek() == Some(&'\n') {
output.push('\n');
chars.next();
}
}
}
output
}
pub(crate) fn needs_explicit_indent(text: &str) -> bool {
let body = text.trim_end_matches('\n');
body.split('\n')
.find(|line| !line.is_empty())
.is_some_and(|line| line.starts_with([' ', '\t']))
}
fn has_whitespace_only_line(text: &str) -> bool {
text.trim_end_matches('\n')
.split('\n')
.any(|line| !line.is_empty() && line.chars().all(|ch| matches!(ch, ' ' | '\t')))
}
pub(crate) fn double_quoted(value: &str) -> String {
let mut output = String::with_capacity(value.len() + 2);
emit_double_quoted(value, &mut output);
output
}
pub(crate) fn emit_double_quoted(value: &str, output: &mut String) {
output.push('"');
for ch in value.chars() {
match ch {
'\\' => output.push_str("\\\\"),
'"' => output.push_str("\\\""),
'\0' => output.push_str("\\0"),
'\u{0007}' => output.push_str("\\a"),
'\u{0008}' => output.push_str("\\b"),
'\t' => output.push_str("\\t"),
'\n' => output.push_str("\\n"),
'\u{000b}' => output.push_str("\\v"),
'\u{000c}' => output.push_str("\\f"),
'\r' => output.push_str("\\r"),
'\u{001b}' => output.push_str("\\e"),
'\u{0085}' => output.push_str("\\N"),
'\u{2028}' => output.push_str("\\L"),
'\u{2029}' => output.push_str("\\P"),
ch if !is_printable(ch) || ch == '\u{feff}' => {
let code = ch as u32;
if code <= 0xFF {
let _ = write!(output, "\\x{code:02X}");
} else if code <= 0xFFFF {
let _ = write!(output, "\\u{code:04X}");
} else {
let _ = write!(output, "\\U{code:08X}");
}
}
ch => output.push(ch),
}
}
output.push('"');
}
#[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"),
crate::Value::Sequence(vec![1_u64.into(), 2_u64.into(), 3_u64.into()])
);
}
}
#[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 value_block_scalar_tests {
use crate::event::ScalarStyle;
use crate::value::Value;
#[test]
fn multiline_value_strings_emit_as_block_scalars() {
for text in ["a\nb\n", "a\nb", "a\n\n", "line\n\nnext\n"] {
let value = Value::from(text);
let output = crate::to_string_value(&value).expect("emit");
assert!(output.starts_with('|'), "output={output:?}");
assert_eq!(
crate::parse_value(&output).expect("reparse"),
value,
"output={output:?}"
);
}
}
#[test]
fn forced_block_scalar_style_round_trips() {
let value = Value::from("plain text");
let output = crate::to_string_value_with_options(
&value,
&super::EmitterOptions {
scalar_style: Some(ScalarStyle::Literal),
..super::EmitterOptions::default()
},
)
.expect("literal");
assert!(output.starts_with("|-"));
assert_eq!(crate::parse_value(&output).unwrap(), value);
let output = crate::to_string_value_with_options(
&value,
&super::EmitterOptions {
scalar_style: Some(ScalarStyle::Folded),
..super::EmitterOptions::default()
},
)
.expect("folded");
assert!(output.starts_with(">-"));
assert_eq!(crate::parse_value(&output).unwrap(), value);
}
}
#[cfg(test)]
mod tagged_block_scalar_tests {
#[test]
fn tagged_multiline_strings_emit_as_tagged_block_scalars() {
let value = crate::parse_value("!Custom |\n a\n b\n").expect("parse");
let output = crate::to_string_value(&value).expect("emit");
assert!(output.starts_with("!Custom |"), "{output:?}");
let decoded = crate::parse_value(&output).expect("reparse");
assert_eq!(decoded, value);
let value = crate::parse_value("key: !Custom |\n a\n b\n").expect("parse");
let output = crate::to_string_value(&value).expect("emit");
assert!(output.contains("!Custom |"), "{output:?}");
assert_eq!(crate::parse_value(&output).expect("reparse"), value);
}
}
#[cfg(test)]
mod indent_tests {
#[test]
fn custom_indent_is_used_for_nested_blocks() {
let value = crate::parse_value("a:\n b: 1\n").expect("parse");
let output = crate::to_string_value_with_options(
&value,
&super::EmitterOptions {
indent: 4,
..super::EmitterOptions::default()
},
)
.expect("emit");
assert!(output.contains("a:\n b: 1"), "{output:?}");
assert_eq!(crate::parse_value(&output).expect("reparse"), value);
}
}
#[cfg(test)]
mod builder_tests {
use super::{Emitter, EmitterOptions, EmitterStyles, NodeStyle};
use crate::value::Value;
#[test]
fn builder_emits_values_writers_and_documents() {
let limits = crate::Limits::default();
let options = EmitterOptions::default().with_flow(true);
let emitter = Emitter::new(&limits, &options);
let value = crate::parse_value("a: 1\n").expect("parse");
let text = emitter.value_to_string(&value).expect("string");
assert_eq!(text, "{a: 1}\n");
assert_eq!(crate::parse_value(&text).expect("reparse"), value);
let mut output = Vec::new();
emitter.value_to_writer(&mut output, &value).expect("write");
assert_eq!(String::from_utf8(output).expect("utf8"), text);
let documents = [value, Value::from("next")];
let stream = emitter.documents_to_string(&documents).expect("documents");
assert_eq!(stream, "{a: 1}\n---\nnext\n");
}
#[test]
fn builder_applies_per_node_styles() {
let limits = crate::Limits::default();
let options = EmitterOptions::default();
let mut styles = EmitterStyles::new();
styles.set(
vec![crate::PathSegment::key("a")],
NodeStyle::default().with_scalar_style(Some(crate::ScalarStyle::SingleQuoted)),
);
let emitter = Emitter::new(&limits, &options).with_styles(&styles);
let value = crate::parse_value("a: plain\n").expect("parse");
assert_eq!(
emitter.value_to_string(&value).expect("emit"),
"a: 'plain'\n"
);
}
}