use std::borrow::Cow;
use std::collections::HashMap;
use crate::error::{Error, ErrorCode, ErrorKind};
use crate::event::{Anchor, Event, ScalarStyle};
use crate::limits::{AliasBudget, Limits};
use crate::mapping::{GlobalHasher, Mapping, SMALL_LIMIT};
use crate::resolver::{resolve_plain, resolve_scalar_cow};
use crate::span::Span;
use crate::tag::{Tag, TaggedValue};
use crate::value::Value;
pub(crate) fn compose_documents(
events: &[Event<'_>],
input_len: usize,
limits: &Limits,
) -> Result<Vec<Value>, Error> {
compose_documents_with_budget(
events.iter().cloned(),
input_len,
limits,
&mut AliasBudget::default(),
)
}
pub(crate) fn compose_documents_with_budget<'a>(
events: impl IntoIterator<Item = Event<'a>>,
input_len: usize,
limits: &Limits,
budget: &mut AliasBudget,
) -> Result<Vec<Value>, Error> {
let mut composer = StreamingComposer::with_budget(limits.clone(), input_len, *budget);
for event in events {
composer.event(event).map_err(|error| *error)?;
}
let (documents, spent) = composer.finish_with_budget()?;
*budget = spent;
Ok(documents)
}
fn apply_tag(tag: Option<&Tag>, value: Value) -> Value {
match tag {
Some(tag) if !tag.is_core_collection() && !tag.is_core_scalar() => {
Value::from(TaggedValue::new(tag.clone(), value))
}
_ => value,
}
}
fn estimate_size(value: &Value, node_cost: usize) -> usize {
match value {
Value::Null | Value::Bool(_) | Value::Number(_) => node_cost,
Value::String(text) => node_cost.saturating_add(text.len()),
Value::Sequence(sequence) => sequence.iter().fold(node_cost, |size, item| {
size.saturating_add(estimate_size(item, node_cost))
}),
Value::Mapping(mapping) => mapping.iter().fold(node_cost, |size, (key, value)| {
size.saturating_add(estimate_size(key, node_cost))
.saturating_add(estimate_size(value, node_cost))
}),
Value::Tagged(tagged) => node_cost
.saturating_add(tagged.tag.text_len())
.saturating_add(estimate_size(&tagged.value, node_cost)),
}
}
#[derive(Debug)]
pub(crate) struct Anchors<T> {
nodes: HashMap<String, AnchorNode<T>, GlobalHasher>,
}
#[derive(Debug)]
enum AnchorNode<T> {
Open,
Finished(T),
}
impl<T> Anchors<T> {
pub(crate) fn new() -> Self {
Self {
nodes: HashMap::with_hasher(GlobalHasher),
}
}
#[inline]
pub(crate) fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
pub(crate) fn clear(&mut self) {
self.nodes.clear();
}
#[inline]
pub(crate) fn capacity(&self) -> usize {
self.nodes.capacity()
}
fn set(&mut self, anchor: &str, node: AnchorNode<T>) {
match self.nodes.get_mut(anchor) {
Some(entry) => *entry = node,
None => {
self.nodes.insert(anchor.to_owned(), node);
}
}
}
pub(crate) fn open(&mut self, anchor: &str) {
self.set(anchor, AnchorNode::Open);
}
pub(crate) fn define(&mut self, anchor: &str, value: T) {
self.set(anchor, AnchorNode::Finished(value));
}
pub(crate) fn close(&mut self, anchor: &str, value: T) {
if let Some(entry) = self.nodes.get_mut(anchor)
&& matches!(entry, AnchorNode::Open)
{
*entry = AnchorNode::Finished(value);
}
}
pub(crate) fn resolve(&self, anchor: &str) -> Result<&T, (ErrorCode, &'static str)> {
match self.nodes.get(anchor) {
Some(AnchorNode::Finished(value)) => Ok(value),
Some(AnchorNode::Open) => Err((
ErrorCode::CyclicAlias,
"an alias cannot refer to a collection that contains it",
)),
None => Err((ErrorCode::UnknownAnchor, "unknown anchor")),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Step {
Item(usize),
Key(usize),
Value(usize),
}
#[derive(Clone, Debug)]
pub(crate) struct AnchorDef {
path: Vec<Step>,
size: usize,
height: usize,
}
#[derive(Default)]
pub(crate) struct ComposerScratch {
stack: Vec<Frame>,
scratch_items: Vec<Value>,
scratch_entries: Vec<(Value, Value)>,
anchors: Option<Anchors<AnchorDef>>,
}
impl ComposerScratch {
pub(crate) fn clear_and_clamp(&mut self) {
self.stack.clear();
if self.stack.capacity() > 128 {
self.stack = Vec::new();
}
self.scratch_items.clear();
if self.scratch_items.capacity() > 256 {
self.scratch_items = Vec::new();
}
self.scratch_entries.clear();
if self.scratch_entries.capacity() > 128 {
self.scratch_entries = Vec::new();
}
if let Some(ref mut anchors) = self.anchors {
anchors.clear();
if anchors.capacity() > 224 {
self.anchors = None;
}
}
}
pub(crate) fn release_all(&mut self) {
self.stack = Vec::new();
self.scratch_items = Vec::new();
self.scratch_entries = Vec::new();
self.anchors = None;
}
}
const SEQ_SCRATCH_LIMIT: usize = 64;
enum SeqBuf {
Scratch { start: usize, len: usize },
Owned(Vec<Value>),
}
impl SeqBuf {
#[inline]
fn len(&self) -> usize {
match self {
Self::Scratch { len, .. } => *len,
Self::Owned(items) => items.len(),
}
}
}
enum MapBuf {
Scratch { start: usize, len: u8 },
Large(Mapping),
}
impl MapBuf {
#[inline]
fn len(&self) -> usize {
match self {
Self::Scratch { len, .. } => usize::from(*len),
Self::Large(mapping) => mapping.len(),
}
}
}
enum Frame {
Sequence {
tag: Option<Tag>,
anchor: Option<String>,
items: SeqBuf,
span: Span,
size: usize,
height: usize,
},
Mapping {
tag: Option<Tag>,
anchor: Option<String>,
mapping: MapBuf,
pending_key: Option<(Value, Span)>,
span: Span,
size: usize,
height: usize,
},
}
impl Frame {
fn position(&self) -> Step {
match self {
Self::Sequence { items, .. } => Step::Item(items.len()),
Self::Mapping {
mapping,
pending_key: None,
..
} => Step::Key(mapping.len()),
Self::Mapping { mapping, .. } => Step::Value(mapping.len()),
}
}
fn child<'b>(
&'b self,
step: Step,
scratch_items: &'b [Value],
scratch_entries: &'b [(Value, Value)],
) -> Option<&'b Value> {
match (self, step) {
(Self::Sequence { items, .. }, Step::Item(index)) => match items {
SeqBuf::Scratch { start, len } if index < *len => scratch_items.get(*start + index),
SeqBuf::Scratch { .. } => None,
SeqBuf::Owned(items) => items.get(index),
},
(
Self::Mapping {
mapping,
pending_key,
..
},
Step::Key(index),
) => match mapping {
MapBuf::Scratch { start, len } => {
let count = usize::from(*len);
match index.cmp(&count) {
std::cmp::Ordering::Less => {
scratch_entries.get(*start + index).map(|(key, _)| key)
}
std::cmp::Ordering::Equal => pending_key.as_ref().map(|(key, _)| key),
std::cmp::Ordering::Greater => None,
}
}
MapBuf::Large(mapping) => match mapping.get_index(index) {
Some((key, _)) => Some(key),
None if index == mapping.len() => pending_key.as_ref().map(|(key, _)| key),
None => None,
},
},
(Self::Mapping { mapping, .. }, Step::Value(index)) => match mapping {
MapBuf::Scratch { start, len } if index < usize::from(*len) => {
scratch_entries.get(*start + index).map(|(_, value)| value)
}
MapBuf::Scratch { .. } => None,
MapBuf::Large(mapping) => mapping.get_index(index).map(|(_, value)| value),
},
_ => None,
}
}
}
fn child_of(mut value: &Value, step: Step) -> Option<&Value> {
while let Value::Tagged(tagged) = value {
value = &tagged.value;
}
match (value, step) {
(Value::Sequence(items), Step::Item(index)) => items.get(index),
(Value::Mapping(mapping), Step::Key(index)) => mapping.get_index(index).map(|(key, _)| key),
(Value::Mapping(mapping), Step::Value(index)) => {
mapping.get_index(index).map(|(_, value)| value)
}
_ => None,
}
}
fn anchored_value<'b>(
stack: &'b [Frame],
scratch_items: &'b [Value],
scratch_entries: &'b [(Value, Value)],
path: &[Step],
) -> Option<&'b Value> {
for (depth, step) in path.iter().enumerate() {
let frame = stack.get(depth)?;
if frame.position() == *step {
continue;
}
let mut value = frame.child(*step, scratch_items, scratch_entries)?;
for step in &path[depth + 1..] {
value = child_of(value, *step)?;
}
return Some(value);
}
None
}
fn shrink_root_value(mut value: &mut Value) {
while let Value::Tagged(tagged) = value {
value = &mut tagged.value;
}
match value {
Value::Sequence(items) => items.shrink_to_fit(),
Value::Mapping(mapping) => mapping.shrink_to_fit(),
_ => {}
}
}
pub(crate) struct StreamingComposer {
limits: Limits,
input_len: usize,
anchors: Anchors<AnchorDef>,
documents: Vec<Value>,
document: Option<Value>,
single_document: bool,
single_completed: bool,
next_capacity: usize,
stack: Vec<Frame>,
scratch_items: Vec<Value>,
scratch_entries: Vec<(Value, Value)>,
budget: AliasBudget,
}
impl StreamingComposer {
pub(crate) fn new(limits: Limits, input_len: usize) -> Self {
Self::with_budget(limits, input_len, AliasBudget::default())
}
pub(crate) fn new_single(limits: Limits, input_len: usize) -> Self {
let mut composer = Self::with_budget(limits, input_len, AliasBudget::default());
composer.single_document = true;
composer
}
pub(crate) fn with_scratch(
limits: Limits,
input_len: usize,
single_document: bool,
mut scratch: ComposerScratch,
) -> Self {
scratch.stack.clear();
scratch.scratch_items.clear();
scratch.scratch_entries.clear();
let mut anchors = scratch.anchors.unwrap_or_else(Anchors::new);
anchors.clear();
Self {
limits,
input_len,
anchors,
documents: Vec::new(),
document: None,
single_document,
single_completed: false,
next_capacity: 0,
stack: scratch.stack,
scratch_items: scratch.scratch_items,
scratch_entries: scratch.scratch_entries,
budget: AliasBudget::default(),
}
}
pub(crate) fn take_scratch(&mut self) -> ComposerScratch {
let mut scratch = ComposerScratch {
stack: std::mem::take(&mut self.stack),
scratch_items: std::mem::take(&mut self.scratch_items),
scratch_entries: std::mem::take(&mut self.scratch_entries),
anchors: Some(std::mem::replace(&mut self.anchors, Anchors::new())),
};
scratch.clear_and_clamp();
scratch
}
pub(crate) fn with_budget(limits: Limits, input_len: usize, budget: AliasBudget) -> Self {
Self {
limits,
input_len,
anchors: Anchors::new(),
documents: Vec::new(),
document: None,
single_document: false,
single_completed: false,
next_capacity: 0,
stack: Vec::new(),
scratch_items: Vec::new(),
scratch_entries: Vec::new(),
budget,
}
}
pub(crate) fn reserve_collection(&mut self, entries: usize) {
self.next_capacity = entries.min(self.limits.max_collection_entries);
}
#[inline]
pub(crate) fn plain_scalar(&mut self, value: &str, span: Span) -> Result<(), Box<Error>> {
self.next_capacity = 0;
let resolved = resolve_plain(value).unwrap_or_else(|| Value::String(value.to_owned()));
let size = if self.anchors.is_empty() {
0
} else {
estimate_size(&resolved, self.limits.node_cost_bytes)
};
self.feed(resolved, span, size, 0)
}
#[inline]
pub(crate) fn scalar(
&mut self,
value: Cow<'_, str>,
style: ScalarStyle,
tag: Option<&Tag>,
anchor: Option<&Anchor<'_>>,
span: Span,
) -> Result<(), Box<Error>> {
self.next_capacity = 0;
let resolved = resolve_scalar_cow(value, style, tag)
.map_err(|error| Box::new(error.with_span(span)))?;
let size = if anchor.is_some() || !self.anchors.is_empty() {
estimate_size(&resolved, self.limits.node_cost_bytes)
} else {
0
};
self.record_anchor(anchor.map(Anchor::as_str), size, 0, Anchors::define);
self.feed(resolved, span, size, 0)
}
pub(crate) fn event(&mut self, event: Event<'_>) -> Result<(), Box<Error>> {
let reserved = std::mem::take(&mut self.next_capacity);
match event {
Event::StreamStart { .. } | Event::StreamEnd { .. } | Event::Directive { .. } => {}
Event::DocumentStart { span, .. } => {
if !self.stack.is_empty() {
return Err(Box::new(Error::new(
ErrorKind::Composition,
"document started inside a collection",
)));
}
if self.single_document && self.single_completed {
return Err(Box::new(
Error::coded(
ErrorKind::Parser,
ErrorCode::TrailingDocuments,
"expected a single YAML document, but found trailing documents",
)
.with_span(span),
));
}
self.anchors.clear();
self.document = None;
}
Event::DocumentEnd { span, .. } => {
if !self.stack.is_empty() {
return Err(self.error_at(span, "document ended inside a collection"));
}
if self.single_document {
if self.document.is_none() {
self.document = Some(Value::Null);
}
self.single_completed = true;
} else {
let value = self.document.take().unwrap_or(Value::Null);
self.documents.push(value);
}
}
Event::Scalar {
value,
style,
tag,
anchor,
span,
..
} => {
return self.scalar(value, style, tag.as_ref(), anchor.as_ref(), span);
}
Event::Alias { anchor, span } => {
let (size, height, value) = {
let definition =
self.anchors
.resolve(anchor.as_str())
.map_err(|(code, message)| {
Box::new((*self.error_at(span, message)).with_code(code))
})?;
let size = definition.size;
let height = definition.height;
self.budget
.charge(&self.limits, self.input_len, size)
.map_err(|error| Box::new(error.with_span(span)))?;
self.limits
.check_depth(self.stack.len() + height)
.map_err(|error| Box::new(Error::from(error).with_span(span)))?;
let value = anchored_value(
&self.stack,
&self.scratch_items,
&self.scratch_entries,
&definition.path,
)
.cloned()
.ok_or_else(|| {
Box::new(
(*self.error_at(span, "unknown anchor"))
.with_code(ErrorCode::UnknownAnchor),
)
})?;
(size, height, value)
};
self.feed(value, span, size, height)?;
}
Event::SequenceStart {
tag, anchor, span, ..
} => {
self.limits
.check_depth(self.stack.len() + 1)
.map_err(|error| Box::new(Error::from(error).with_span(span)))?;
let anchor_name = if let Some(anchor) = anchor {
let owned = anchor.as_str().to_owned();
self.anchors.open(&owned);
Some(owned)
} else {
None
};
let items = if reserved > SEQ_SCRATCH_LIMIT {
SeqBuf::Owned(Vec::with_capacity(reserved))
} else {
SeqBuf::Scratch {
start: self.scratch_items.len(),
len: 0,
}
};
self.stack.push(Frame::Sequence {
tag,
anchor: anchor_name,
items,
span,
size: self.limits.node_cost_bytes,
height: 0,
});
}
Event::SequenceEnd { span } => self.finish_sequence(span)?,
Event::MappingStart {
tag, anchor, span, ..
} => {
self.limits
.check_depth(self.stack.len() + 1)
.map_err(|error| Box::new(Error::from(error).with_span(span)))?;
let anchor_name = if let Some(anchor) = anchor {
let owned = anchor.as_str().to_owned();
self.anchors.open(&owned);
Some(owned)
} else {
None
};
let mapping = if reserved > SMALL_LIMIT {
MapBuf::Large(Mapping::with_capacity(reserved))
} else {
MapBuf::Scratch {
start: self.scratch_entries.len(),
len: 0,
}
};
self.stack.push(Frame::Mapping {
tag,
anchor: anchor_name,
mapping,
pending_key: None,
span,
size: self.limits.node_cost_bytes,
height: 0,
});
}
Event::MappingEnd { span } => self.finish_mapping(span)?,
}
Ok(())
}
#[inline]
fn finish_sequence(&mut self, span: Span) -> Result<(), Box<Error>> {
let Some(Frame::Sequence {
tag,
anchor,
items,
span: start_span,
size,
height,
}) = self.stack.pop()
else {
return Err(self.error_at(span, "unexpected sequence end"));
};
let items = match items {
SeqBuf::Scratch { len: 0, .. } => Vec::new(),
SeqBuf::Scratch { start, len } => {
let mut exact = Vec::with_capacity(len);
exact.extend(self.scratch_items.drain(start..));
exact
}
SeqBuf::Owned(mut items) => {
if !self.stack.is_empty() && items.len() <= 256 {
items.shrink_to_fit();
}
items
}
};
let (value, size) = self.finish_collection(tag.as_ref(), Value::Sequence(items), size);
self.record_anchor(anchor.as_deref(), size, height + 1, Anchors::close);
self.feed(value, start_span, size, height + 1)
}
#[inline]
fn finish_mapping(&mut self, span: Span) -> Result<(), Box<Error>> {
let Some(Frame::Mapping {
tag,
anchor,
mapping,
pending_key,
span: start_span,
size,
height,
}) = self.stack.pop()
else {
return Err(self.error_at(span, "unexpected mapping end"));
};
if let Some((key, key_span)) = pending_key {
return Err(Box::new(
Error::new(
ErrorKind::Composition,
format!("mapping key without value: {key:?}"),
)
.with_span(key_span),
));
}
let mapping = match mapping {
MapBuf::Scratch { len: 0, .. } => Mapping::new(),
MapBuf::Scratch { start, .. } => {
Mapping::from_small_drain(self.scratch_entries.drain(start..))
}
MapBuf::Large(mut mapping) => {
if !self.stack.is_empty() && mapping.len() <= 256 {
mapping.shrink_to_fit();
}
mapping
}
};
let (value, size) = self.finish_collection(tag.as_ref(), Value::Mapping(mapping), size);
self.record_anchor(anchor.as_deref(), size, height + 1, Anchors::close);
self.feed(value, start_span, size, height + 1)
}
pub(crate) fn finish(self) -> Result<Vec<Value>, Error> {
self.finish_with_budget().map(|(documents, _)| documents)
}
pub(crate) fn finish_single_with_scratch(mut self) -> (Result<Value, Error>, ComposerScratch) {
let unterminated = !self.stack.is_empty();
let scratch = self.take_scratch();
if unterminated {
return (
Err(Error::new(
ErrorKind::Composition,
"unterminated collection at end of stream",
)),
scratch,
);
}
let mut value = self.document.take().unwrap_or(Value::Null);
shrink_root_value(&mut value);
(Ok(value), scratch)
}
pub(crate) fn finish_with_scratch(mut self) -> (Result<Vec<Value>, Error>, ComposerScratch) {
let unterminated = !self.stack.is_empty();
let scratch = self.take_scratch();
if unterminated {
return (
Err(Error::new(
ErrorKind::Composition,
"unterminated collection at end of stream",
)),
scratch,
);
}
let mut documents = std::mem::take(&mut self.documents);
for doc in &mut documents {
shrink_root_value(doc);
}
(Ok(documents), scratch)
}
pub(crate) fn finish_single(self) -> Result<Value, Error> {
let Self {
stack,
document,
scratch_items,
scratch_entries,
anchors,
documents,
..
} = self;
if !stack.is_empty() {
return Err(Error::new(
ErrorKind::Composition,
"unterminated collection at end of stream",
));
}
drop(stack);
drop(scratch_items);
drop(scratch_entries);
drop(anchors);
drop(documents);
let mut value = document.unwrap_or(Value::Null);
shrink_root_value(&mut value);
Ok(value)
}
pub(crate) fn finish_with_budget(self) -> Result<(Vec<Value>, AliasBudget), Error> {
let Self {
stack,
mut documents,
scratch_items,
scratch_entries,
anchors,
document,
budget,
..
} = self;
if !stack.is_empty() {
return Err(Error::new(
ErrorKind::Composition,
"unterminated collection at end of stream",
));
}
drop(stack);
drop(scratch_items);
drop(scratch_entries);
drop(anchors);
drop(document);
for doc in &mut documents {
shrink_root_value(doc);
}
Ok((documents, budget))
}
fn finish_collection(&self, tag: Option<&Tag>, value: Value, size: usize) -> (Value, usize) {
let value = apply_tag(tag, value);
let size = match &value {
Value::Tagged(tagged) => size
.saturating_add(self.limits.node_cost_bytes)
.saturating_add(tagged.tag.text_len()),
_ => size,
};
(value, size)
}
fn feed(
&mut self,
value: Value,
span: Span,
size: usize,
height: usize,
) -> Result<(), Box<Error>> {
match self.stack.last_mut() {
Some(Frame::Sequence {
items,
size: total,
height: deepest,
..
}) => {
*total = total.saturating_add(size);
*deepest = (*deepest).max(height);
match items {
SeqBuf::Scratch { start, len } => {
if *len < SEQ_SCRATCH_LIMIT {
if self.scratch_items.capacity() == 0 {
self.scratch_items.reserve_exact(16);
}
self.scratch_items.push(value);
*len += 1;
} else {
let mut owned = Vec::with_capacity(SEQ_SCRATCH_LIMIT * 2);
owned.extend(self.scratch_items.drain(*start..));
owned.push(value);
*items = SeqBuf::Owned(owned);
}
}
SeqBuf::Owned(owned) => {
owned.push(value);
}
}
}
Some(Frame::Mapping {
mapping,
pending_key,
size: total,
height: deepest,
..
}) => {
*total = total.saturating_add(size);
*deepest = (*deepest).max(height);
if let Some((key, key_span)) = pending_key.take() {
match mapping {
MapBuf::Scratch { start, len } => {
let existing = &self.scratch_entries[*start..];
if let Some((existing_key, _)) =
existing.iter().find(|(k, _)| k == &key)
{
return Err(Box::new(
Error::new(
ErrorKind::DuplicateKey,
format!(
"duplicate mapping key: {}",
crate::value::key_text(existing_key)
),
)
.with_span(key_span),
));
}
if usize::from(*len) < SMALL_LIMIT {
if self.scratch_entries.capacity() == 0 {
self.scratch_entries.reserve_exact(SMALL_LIMIT);
}
self.scratch_entries.push((key, value));
*len += 1;
} else {
let mut large = Mapping::with_capacity(SMALL_LIMIT * 2);
for (k, v) in self.scratch_entries.drain(*start..) {
drop(large.insert(k, v));
}
drop(large.insert(key, value));
*mapping = MapBuf::Large(large);
}
}
MapBuf::Large(large) => {
if let Err(duplicate) = large.insert_new(key, value) {
return Err(Box::new(
Error::new(
ErrorKind::DuplicateKey,
format!("duplicate mapping key: {duplicate}"),
)
.with_span(key_span),
));
}
}
}
} else {
*pending_key = Some((value, span));
}
}
None => {
if self.document.is_some() {
return Err(self.error_at(span, "multiple root nodes in one document"));
}
self.document = Some(value);
}
}
Ok(())
}
fn record_anchor(
&mut self,
anchor: Option<&str>,
size: usize,
height: usize,
record: fn(&mut Anchors<AnchorDef>, &str, AnchorDef),
) {
if let Some(anchor) = anchor {
let path = self.stack.iter().map(Frame::position).collect();
let definition = AnchorDef { path, size, height };
record(&mut self.anchors, anchor, definition);
}
}
#[cold]
#[inline(never)]
#[allow(
clippy::unused_self,
clippy::unnecessary_box_returns,
reason = "hot-path callers propagate Box<Error> to keep Result<_, Box<Error>> pointer-sized"
)]
fn error_at(&self, span: Span, message: impl Into<String>) -> Box<Error> {
Box::new(Error::new(ErrorKind::Composition, message).with_span(span))
}
}
#[cfg(test)]
mod tests {
use super::compose_documents;
use crate::error::ErrorKind;
use crate::limits::Limits;
use crate::parser::parse_events;
use crate::value::Value;
fn compose(input: &str) -> Value {
let events = parse_events(input, &Limits::default()).expect("parse");
compose_documents(&events, input.len(), &Limits::default())
.expect("compose")
.into_iter()
.next()
.expect("document")
}
#[test]
fn composes_scalars_sequences_and_mappings() {
let value = compose("name: ayaml\nitems:\n - one\n - two\n");
assert_eq!(value["name"], Value::from("ayaml"));
assert_eq!(value["items"][0], Value::from("one"));
assert_eq!(value["items"][1], Value::from("two"));
}
fn fixture(name: &str) -> Option<String> {
let root =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/compat");
std::fs::read_to_string(root.join(name)).ok()
}
#[test]
fn compatibility_scalars_and_tags() {
let Some(input) = fixture("scalar-tags-merges-aliases.yml") else {
return;
};
let value = compose(&input);
assert_eq!(value["plain_bool_word"], Value::from("yes"));
assert_eq!(value["legacy_octal"], Value::from("0123"));
assert_eq!(value["binary"].as_u64(), Some(3));
assert_eq!(value["hex"].as_u64(), Some(31));
assert_eq!(value["exponent"].as_f64(), Some(1000.0));
assert!(value["null_value"].is_null());
assert_eq!(value["core_string"], Value::from("123"));
assert!(value["tagged"].is_tagged());
assert_eq!(value["alias"], value["base"]);
assert_eq!(value["merged"]["<<"], value["base"]);
}
#[test]
fn duplicate_keys_are_rejected() {
let input = "a: 1\na: 2\n";
let events = parse_events(input, &Limits::default()).expect("parse");
let error =
compose_documents(&events, input.len(), &Limits::default()).expect_err("duplicate");
assert_eq!(error.kind(), ErrorKind::DuplicateKey);
}
#[test]
fn aliases_are_materialized_and_budgeted() {
let input = "base: &b {x: 1}\nuse: *b\n";
let value = compose(input);
assert_eq!(value["use"], value["base"]);
let events = parse_events(input, &Limits::default()).expect("parse");
let limits = Limits {
max_alias_expansion_bytes: 0,
..Limits::default()
};
let error = compose_documents(&events, input.len(), &limits).expect_err("budget");
assert_eq!(error.kind(), ErrorKind::Limit);
}
#[test]
fn anchors_are_scoped_to_their_document() {
let input = "---\na: &x 1\n---\nb: *x\n";
let limits = Limits {
max_documents: 2,
..Limits::default()
};
let events = parse_events(input, &limits).expect("parse");
let error = compose_documents(&events, input.len(), &limits).expect_err("cross-document");
assert_eq!(error.kind(), ErrorKind::Composition);
assert!(error.message().contains("unknown anchor"));
}
#[test]
fn aliases_before_their_anchor_are_rejected() {
let input = "a: *missing\n";
let events = parse_events(input, &Limits::default()).expect("parse");
let error = compose_documents(&events, input.len(), &Limits::default()).expect_err("alias");
assert_eq!(error.kind(), ErrorKind::Composition);
assert!(error.message().contains("unknown anchor"));
}
#[test]
fn multiple_documents_compose_in_order() {
let input = "a: 1\n---\nb: 2\n";
let limits = Limits {
max_documents: 2,
..Limits::default()
};
let events = parse_events(input, &limits).expect("parse");
let documents = compose_documents(&events, input.len(), &limits).expect("compose");
assert_eq!(documents.len(), 2);
assert_eq!(documents[0]["a"].as_u64(), Some(1));
assert_eq!(documents[1]["b"].as_u64(), Some(2));
}
#[test]
fn toolchain_fixture_composes() {
let Some(input) = fixture("toolchain-pins.yml") else {
return;
};
let value = compose(&input);
assert_eq!(value["version"].as_u64(), Some(1));
assert!(value["facts"].is_sequence());
assert!(value["rules"].is_sequence());
}
#[test]
fn duplicate_key_diagnostic_matches_across_small_and_large_mappings() {
let small_float = "0.0: 1\n-0.0: 2\n";
let mut large_float = String::new();
for idx in 0..8 {
use std::fmt::Write as _;
let _ = writeln!(large_float, "k{idx}: {idx}");
}
large_float.push_str(small_float);
let small_err = crate::parse_value(small_float).expect_err("small duplicate");
let large_err = crate::parse_value(&large_float).expect_err("large duplicate");
assert_eq!(small_err.kind(), ErrorKind::DuplicateKey);
assert_eq!(large_err.kind(), ErrorKind::DuplicateKey);
assert_eq!(small_err.message(), large_err.message());
let small_map = "? {a: 1, b: 2}\n: 1\n? {b: 2, a: 1}\n: 2\n";
let mut large_map = String::new();
for idx in 0..8 {
use std::fmt::Write as _;
let _ = writeln!(large_map, "k{idx}: {idx}");
}
large_map.push_str(small_map);
let small_err = crate::parse_value(small_map).expect_err("small complex duplicate");
let large_err = crate::parse_value(&large_map).expect_err("large complex duplicate");
assert_eq!(small_err.message(), large_err.message());
}
#[test]
fn aliases_resolve_across_scratch_and_spilled_collections_and_pending_keys() {
let mut seq_yaml = String::from("- &first {a: 1, b: 2}\n- *first\n");
for idx in 0..70 {
use std::fmt::Write as _;
let _ = writeln!(seq_yaml, "- {idx}");
}
seq_yaml.push_str("- *first\n");
let seq = crate::parse_value(&seq_yaml).expect("spilled seq with aliases");
let items = seq.as_sequence().expect("sequence");
assert_eq!(items.len(), 73);
assert_eq!(items[0], items[1]);
assert_eq!(items[0], items[72]);
let mut map_yaml = String::from("a0: &m0 [1, 2]\na1: *m0\n");
for idx in 2..12 {
use std::fmt::Write as _;
let _ = writeln!(map_yaml, "a{idx}: {idx}");
}
map_yaml.push_str("tail: *m0\n");
let map = crate::parse_value(&map_yaml).expect("spilled map with aliases");
assert_eq!(map["a0"], map["a1"]);
assert_eq!(map["a0"], map["tail"]);
let mut complex_yaml = String::from("? &pk {k: [1, 2]}\n:\n");
for idx in 0..10 {
use std::fmt::Write as _;
let _ = writeln!(complex_yaml, " n{idx}: {idx}");
}
complex_yaml.push_str(" ref_key: *pk\n");
let complex = crate::parse_value(&complex_yaml).expect("alias to pending complex key");
let root_map = complex.as_mapping().expect("root mapping");
let (key_val, val_map) = root_map.get_index(0).expect("first entry");
assert_eq!(&val_map["ref_key"], key_val);
}
#[test]
fn mapping_height_and_scratch_spill_boundaries_are_exact() {
use super::{Frame, MapBuf, SEQ_SCRATCH_LIMIT, SeqBuf, StreamingComposer};
use crate::limits::LimitKind;
use crate::{Event, Span};
let input = "base: &b {x: 1}\nwrap: {inner: *b}\n";
let ok_opts = crate::ParseOptions::new().with_limits(Limits::default().with_max_depth(3));
assert!(crate::parse_value_with(input, &ok_opts).is_ok());
let tight_opts =
crate::ParseOptions::new().with_limits(Limits::default().with_max_depth(2));
let err = crate::parse_value_with(input, &tight_opts).expect_err("depth 2 + height 1 > 2");
assert_eq!(
err.limit().map(crate::LimitExceeded::kind),
Some(LimitKind::Depth)
);
let deep = "base: &b {a: {c: 1}}\nwrap: *b\n";
let ok3 = crate::ParseOptions::new().with_limits(Limits::default().with_max_depth(3));
assert!(crate::parse_value_with(deep, &ok3).is_ok());
let deep_nested = "base: &b {a: {c: 1}}\nwrap: {k: *b}\n";
let err3 =
crate::parse_value_with(deep_nested, &ok3).expect_err("depth 2 + height 2 = 4 > 3");
assert_eq!(
err3.limit().map(crate::LimitExceeded::kind),
Some(LimitKind::Depth)
);
let mut c = StreamingComposer::new(Limits::default(), 64);
c.event(Event::SequenceStart {
style: crate::event::CollectionStyle::Block,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("seq start");
for i in 0..SEQ_SCRATCH_LIMIT {
c.plain_scalar("1", Span::empty(i)).expect("item");
}
assert!(matches!(
c.stack.last(),
Some(Frame::Sequence {
items: SeqBuf::Scratch { len, .. },
..
}) if *len == SEQ_SCRATCH_LIMIT
));
assert!(c.scratch_items.capacity() >= 16);
c.plain_scalar("1", Span::empty(SEQ_SCRATCH_LIMIT))
.expect("spill item");
assert!(matches!(
c.stack.last(),
Some(Frame::Sequence {
items: SeqBuf::Owned(v),
..
}) if v.len() == SEQ_SCRATCH_LIMIT + 1
));
let mut cm = StreamingComposer::new(Limits::default(), 64);
cm.event(Event::MappingStart {
style: crate::event::CollectionStyle::Block,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("map start");
let keys: Vec<String> = (0..=crate::mapping::SMALL_LIMIT)
.map(|i| format!("k{i}"))
.collect();
for key in &keys[..crate::mapping::SMALL_LIMIT] {
cm.plain_scalar(key, Span::empty(0)).expect("k");
cm.plain_scalar("1", Span::empty(0)).expect("v");
}
assert!(matches!(
cm.stack.last(),
Some(Frame::Mapping {
mapping: MapBuf::Scratch { len, .. },
..
}) if usize::from(*len) == crate::mapping::SMALL_LIMIT
));
assert_eq!(cm.scratch_entries.capacity(), crate::mapping::SMALL_LIMIT);
cm.plain_scalar(&keys[crate::mapping::SMALL_LIMIT], Span::empty(0))
.expect("spill k");
cm.plain_scalar("1", Span::empty(0)).expect("spill v");
assert!(matches!(
cm.stack.last(),
Some(Frame::Mapping {
mapping: MapBuf::Large(m),
..
}) if m.len() == crate::mapping::SMALL_LIMIT + 1
));
}
#[test]
fn composer_scratch_clamping_and_anchor_helpers() {
use super::{
AnchorDef, Anchors, ComposerScratch, StreamingComposer, apply_tag,
compose_documents_with_budget,
};
use crate::limits::AliasBudget;
use crate::tag::Tag;
use crate::{Event, Span};
let events = parse_events("a: 1\n", &Limits::default()).expect("parse");
let mut budget = AliasBudget::default();
let docs =
compose_documents_with_budget(events, 5, &Limits::default(), &mut budget).expect("doc");
assert_eq!(docs.len(), 1);
assert!(apply_tag(Some(&Tag::local("custom")), Value::Sequence(Vec::new())).is_tagged());
assert!(!apply_tag(Some(&Tag::core("seq")), Value::Sequence(Vec::new())).is_tagged());
assert!(!apply_tag(Some(&Tag::core("str")), Value::Sequence(Vec::new())).is_tagged());
let mut anchors: Anchors<usize> = Anchors::new();
assert!(anchors.is_empty());
assert_eq!(anchors.capacity(), 0);
for i in 0..16 {
anchors.define(&format!("a{i}"), i);
}
assert!(!anchors.is_empty());
assert!(anchors.capacity() >= 16);
anchors.clear();
assert!(anchors.is_empty());
assert!(anchors.resolve("a0").is_err());
let mut scratch = ComposerScratch {
stack: Vec::with_capacity(128),
scratch_items: Vec::with_capacity(256),
scratch_entries: Vec::with_capacity(128),
anchors: Some({
let mut a = Anchors::new();
for i in 0..200 {
a.define(
&format!("x{i}"),
AnchorDef {
path: Vec::new(),
size: 1,
height: 0,
},
);
}
assert_eq!(a.capacity(), 224);
a
}),
};
scratch.clear_and_clamp();
assert_eq!(scratch.stack.capacity(), 128);
assert_eq!(scratch.scratch_items.capacity(), 256);
assert_eq!(scratch.scratch_entries.capacity(), 128);
assert!(scratch.anchors.is_some());
assert!(scratch.anchors.as_ref().unwrap().is_empty());
assert_eq!(scratch.anchors.as_ref().unwrap().capacity(), 224);
scratch.stack = Vec::with_capacity(129);
scratch.scratch_items = Vec::with_capacity(257);
scratch.scratch_entries = Vec::with_capacity(129);
let big_anchors = scratch.anchors.as_mut().unwrap();
for i in 0..225 {
big_anchors.define(
&format!("k{i}"),
AnchorDef {
path: Vec::new(),
size: 1,
height: 0,
},
);
}
assert!(big_anchors.capacity() > 224);
scratch.clear_and_clamp();
assert_eq!(scratch.stack.capacity(), 0);
assert_eq!(scratch.scratch_items.capacity(), 0);
assert_eq!(scratch.scratch_entries.capacity(), 0);
assert!(scratch.anchors.is_none());
scratch.stack = Vec::with_capacity(8);
scratch.scratch_items = Vec::with_capacity(8);
scratch.scratch_entries = Vec::with_capacity(8);
scratch.anchors = Some(Anchors::new());
scratch.release_all();
assert_eq!(scratch.stack.capacity(), 0);
assert_eq!(scratch.scratch_items.capacity(), 0);
assert_eq!(scratch.scratch_entries.capacity(), 0);
assert!(scratch.anchors.is_none());
let mut sc = StreamingComposer::new_single(Limits::default(), 64);
sc.event(Event::SequenceStart {
style: crate::event::CollectionStyle::Block,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("seq");
sc.plain_scalar("1", Span::empty(0)).expect("item");
assert_eq!(sc.scratch_items.capacity(), 16);
sc.event(Event::SequenceEnd {
span: Span::empty(0),
})
.expect("end");
let taken = sc.take_scratch();
assert!(taken.stack.capacity() > 0 && taken.scratch_items.capacity() == 16);
}
#[test]
fn composer_frame_child_and_root_shrink_boundaries() {
use super::{Frame, MapBuf, SeqBuf, Step, anchored_value, shrink_root_value};
use crate::mapping::Mapping;
use crate::span::Span;
use crate::tag::Tag;
let items_buf = vec![
Value::from(10_u64),
Value::from(20_u64),
Value::from(30_u64),
];
let entries_buf = vec![
(Value::from("pad"), Value::from(0_u64)),
(Value::from("k0"), Value::from(100_u64)),
(Value::from("k1"), Value::from(200_u64)),
];
let seq_frame = Frame::Sequence {
tag: None,
anchor: None,
items: SeqBuf::Scratch { start: 1, len: 1 },
span: Span::empty(0),
size: 0,
height: 0,
};
assert_eq!(
seq_frame.child(Step::Item(0), &items_buf, &entries_buf),
Some(&Value::from(20_u64))
);
assert_eq!(
seq_frame.child(Step::Item(1), &items_buf, &entries_buf),
None
);
let map_scratch = Frame::Mapping {
tag: None,
anchor: None,
mapping: MapBuf::Scratch { start: 1, len: 1 },
pending_key: Some((Value::from("pk"), Span::empty(0))),
span: Span::empty(0),
size: 0,
height: 0,
};
assert_eq!(
map_scratch.child(Step::Key(0), &items_buf, &entries_buf),
Some(&Value::from("k0"))
);
assert_eq!(
map_scratch.child(Step::Key(1), &items_buf, &entries_buf),
Some(&Value::from("pk"))
);
assert_eq!(
map_scratch.child(Step::Key(2), &items_buf, &entries_buf),
None
);
assert_eq!(
map_scratch.child(Step::Value(0), &items_buf, &entries_buf),
Some(&Value::from(100_u64))
);
assert_eq!(
map_scratch.child(Step::Value(1), &items_buf, &entries_buf),
None
);
let map_scratch2 = Frame::Mapping {
tag: None,
anchor: None,
mapping: MapBuf::Scratch { start: 1, len: 2 },
pending_key: None,
span: Span::empty(0),
size: 0,
height: 0,
};
assert_eq!(
map_scratch2.child(Step::Key(1), &items_buf, &entries_buf),
Some(&Value::from("k1"))
);
assert_eq!(
map_scratch2.child(Step::Value(1), &items_buf, &entries_buf),
Some(&Value::from(200_u64))
);
let mut large_m = Mapping::with_capacity(2);
large_m.insert(Value::from("a"), Value::from(1_u64));
let map_large = Frame::Mapping {
tag: None,
anchor: None,
mapping: MapBuf::Large(large_m),
pending_key: Some((Value::from("pk_large"), Span::empty(0))),
span: Span::empty(0),
size: 0,
height: 0,
};
assert_eq!(
map_large.child(Step::Key(0), &items_buf, &entries_buf),
Some(&Value::from("a"))
);
assert_eq!(
map_large.child(Step::Key(1), &items_buf, &entries_buf),
Some(&Value::from("pk_large"))
);
assert_eq!(
map_large.child(Step::Key(2), &items_buf, &entries_buf),
None
);
assert_eq!(MapBuf::Scratch { start: 0, len: 0 }.len(), 0);
assert_eq!(MapBuf::Scratch { start: 0, len: 2 }.len(), 2);
let stack = vec![seq_frame, map_scratch2];
assert_eq!(
anchored_value(&stack, &items_buf, &entries_buf, &[Step::Item(0)]),
Some(&Value::from(20_u64))
);
assert_eq!(
anchored_value(
&stack,
&items_buf,
&entries_buf,
&[Step::Item(1), Step::Value(1)]
),
Some(&Value::from(200_u64))
);
let mut spare_seq = Vec::with_capacity(64);
spare_seq.push(Value::from(1_u64));
let mut root_seq = Value::from(crate::TaggedValue::new(
Tag::local("wrap"),
Value::Sequence(spare_seq),
));
shrink_root_value(&mut root_seq);
if let Value::Tagged(t) = root_seq
&& let Value::Sequence(v) = t.value
{
assert_eq!(v.capacity(), 1);
} else {
panic!("expected tagged sequence");
}
let mut spare_map = Mapping::with_capacity(64);
for i in 0_u64..10 {
spare_map.insert(Value::from(format!("k{i}")), Value::from(i));
}
assert!(spare_map.capacity() >= 64);
let mut root_map = Value::Mapping(spare_map);
shrink_root_value(&mut root_map);
assert_eq!(root_map.as_mapping().unwrap().len(), 10);
assert!(root_map.as_mapping().unwrap().capacity() < 64);
}
#[test]
fn composer_reserve_depth_and_nested_shrink_boundaries() {
use super::{Frame, MapBuf, SEQ_SCRATCH_LIMIT, SeqBuf, StreamingComposer};
use crate::event::Event;
use crate::limits::LimitKind;
use crate::mapping::SMALL_LIMIT;
use crate::span::Span;
let mut rc = StreamingComposer::new(Limits::default(), 64);
rc.reserve_collection(SEQ_SCRATCH_LIMIT);
rc.event(Event::SequenceStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("seq at limit");
assert!(matches!(
rc.stack.last(),
Some(Frame::Sequence {
items: SeqBuf::Scratch { .. },
..
})
));
rc.reserve_collection(SEQ_SCRATCH_LIMIT + 1);
rc.event(Event::SequenceStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("seq over limit");
assert!(matches!(
rc.stack.last(),
Some(Frame::Sequence {
items: SeqBuf::Owned(_),
..
})
));
rc.reserve_collection(SMALL_LIMIT);
rc.event(Event::MappingStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("map at limit");
assert!(matches!(
rc.stack.last(),
Some(Frame::Mapping {
mapping: MapBuf::Scratch { .. },
..
})
));
rc.reserve_collection(SMALL_LIMIT + 1);
rc.event(Event::MappingStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("map over limit");
assert!(matches!(
rc.stack.last(),
Some(Frame::Mapping {
mapping: MapBuf::Large(_),
..
})
));
let lim1 = crate::ParseOptions::new().with_limits(Limits::default().with_max_depth(1));
assert!(crate::parse_value_with("[1]\n", &lim1).is_ok());
assert_eq!(
crate::parse_value_with("[[1]]\n", &lim1)
.expect_err("depth 2 seq > 1")
.limit()
.map(crate::LimitExceeded::kind),
Some(LimitKind::Depth)
);
assert_eq!(
crate::parse_value_with("a:\n b: 1\n", &lim1)
.expect_err("depth 2 map > 1")
.limit()
.map(crate::LimitExceeded::kind),
Some(LimitKind::Depth)
);
let lim2 = crate::ParseOptions::new().with_limits(Limits::default().with_max_depth(2));
let seq_alias = "a: &s [[1]]\nb: *s\n";
assert_eq!(
crate::parse_value_with(seq_alias, &lim2)
.expect_err("stack 1 + height 2 = 3 > 2")
.limit()
.map(crate::LimitExceeded::kind),
Some(LimitKind::Depth)
);
let seq_h1 = "a: &s [1]\nb: [*s]\n";
assert_eq!(
crate::parse_value_with(seq_h1, &lim2)
.expect_err("stack 2 + height 1 = 3 > 2")
.limit()
.map(crate::LimitExceeded::kind),
Some(LimitKind::Depth)
);
let lim3 = crate::ParseOptions::new().with_limits(Limits::default().with_max_depth(3));
assert_eq!(
crate::parse_value_with("a: &s [[1]]\nb: [*s]\n", &lim3)
.expect_err("stack 2 + height 2 = 4 > 3")
.limit()
.map(crate::LimitExceeded::kind),
Some(LimitKind::Depth)
);
let d1 = Limits::default().with_max_depth(1);
let mut seq_c = StreamingComposer::new_single(d1.clone(), 8);
let seq_ev = Event::SequenceStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
};
seq_c.event(seq_ev.clone()).expect("depth 1 seq ok");
assert_eq!(
seq_c
.event(seq_ev)
.expect_err("depth 2 seq exceeds max_depth=1")
.limit()
.map(crate::LimitExceeded::kind),
Some(LimitKind::Depth)
);
let mut map_c = StreamingComposer::new_single(d1, 8);
let map_ev = Event::MappingStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
};
map_c.event(map_ev.clone()).expect("depth 1 map ok");
assert_eq!(
map_c
.event(map_ev)
.expect_err("depth 2 map exceeds max_depth=1")
.limit()
.map(crate::LimitExceeded::kind),
Some(LimitKind::Depth)
);
}
#[test]
fn composer_nested_and_root_shrink_boundaries() {
use super::StreamingComposer;
use crate::event::Event;
use crate::span::Span;
let mut nested_seq = StreamingComposer::new_single(Limits::default(), 1024);
nested_seq
.event(Event::SequenceStart {
style: crate::event::CollectionStyle::Block,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("outer");
nested_seq.reserve_collection(300);
nested_seq
.event(Event::SequenceStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("inner 256");
for _ in 0..256 {
nested_seq.plain_scalar("1", Span::empty(0)).expect("item");
}
nested_seq
.event(Event::SequenceEnd {
span: Span::empty(0),
})
.expect("end 256");
nested_seq.reserve_collection(300);
nested_seq
.event(Event::SequenceStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("inner 257");
for _ in 0..257 {
nested_seq.plain_scalar("1", Span::empty(0)).expect("item");
}
nested_seq
.event(Event::SequenceEnd {
span: Span::empty(0),
})
.expect("end 257");
nested_seq
.event(Event::SequenceEnd {
span: Span::empty(0),
})
.expect("end outer");
nested_seq
.event(Event::DocumentEnd {
explicit: false,
span: Span::empty(0),
})
.expect("doc end");
let root_val = nested_seq.finish_single().expect("finish");
let outer_items = root_val.as_sequence().expect("outer seq");
assert_eq!(outer_items[0].as_sequence().unwrap().capacity(), 256);
assert!(outer_items[1].as_sequence().unwrap().capacity() >= 300);
let mut root_seq_c = StreamingComposer::new_single(Limits::default(), 1024);
root_seq_c.reserve_collection(300);
root_seq_c
.event(Event::SequenceStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("root seq");
for _ in 0..70 {
root_seq_c.plain_scalar("1", Span::empty(0)).expect("item");
}
root_seq_c
.event(Event::SequenceEnd {
span: Span::empty(0),
})
.expect("end root seq");
assert!(
root_seq_c
.document
.as_ref()
.unwrap()
.as_sequence()
.unwrap()
.capacity()
>= 300
);
let shrunk_root_seq = root_seq_c.finish_single().expect("finish root seq");
assert_eq!(shrunk_root_seq.as_sequence().unwrap().capacity(), 70);
let mut nested_map = StreamingComposer::new_single(Limits::default(), 4096);
nested_map
.event(Event::SequenceStart {
style: crate::event::CollectionStyle::Block,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("outer seq");
nested_map.reserve_collection(600);
nested_map
.event(Event::MappingStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("inner map 256");
for i in 0..256 {
nested_map
.plain_scalar(&format!("a{i}"), Span::empty(0))
.expect("k");
nested_map.plain_scalar("1", Span::empty(0)).expect("v");
}
nested_map
.event(Event::MappingEnd {
span: Span::empty(0),
})
.expect("end map 256");
nested_map.reserve_collection(600);
nested_map
.event(Event::MappingStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("inner map 257");
for i in 0..257 {
nested_map
.plain_scalar(&format!("b{i}"), Span::empty(0))
.expect("k");
nested_map.plain_scalar("1", Span::empty(0)).expect("v");
}
nested_map
.event(Event::MappingEnd {
span: Span::empty(0),
})
.expect("end map 257");
nested_map
.event(Event::SequenceEnd {
span: Span::empty(0),
})
.expect("end outer");
let map_root_val = nested_map.finish_single().expect("finish nested maps");
let map_items = map_root_val.as_sequence().expect("outer seq");
assert!(map_items[0].as_mapping().unwrap().capacity() < 600);
assert!(map_items[1].as_mapping().unwrap().capacity() >= 600);
let mut root_map_c = StreamingComposer::new_single(Limits::default(), 4096);
root_map_c.reserve_collection(600);
root_map_c
.event(Event::MappingStart {
style: crate::event::CollectionStyle::Flow,
tag: None,
anchor: None,
span: Span::empty(0),
})
.expect("root map");
for i in 0..10 {
root_map_c
.plain_scalar(&format!("r{i}"), Span::empty(0))
.expect("k");
root_map_c.plain_scalar("1", Span::empty(0)).expect("v");
}
root_map_c
.event(Event::MappingEnd {
span: Span::empty(0),
})
.expect("end root map");
assert!(
root_map_c
.document
.as_ref()
.unwrap()
.as_mapping()
.unwrap()
.capacity()
>= 600
);
let shrunk_root_map = root_map_c.finish_single().expect("finish root map");
assert!(shrunk_root_map.as_mapping().unwrap().capacity() < 600);
}
}