pub struct Mapping(/* private fields */);Expand description
A YAML mapping (key-value pairs)
Note: This type uses interior mutability through the rowan library.
Mutation methods work even when called through &self. See the crate-level
documentation for details on the mutability model.
Implementations§
Source§impl Mapping
impl Mapping
Sourcepub fn move_after(
&self,
after_key: impl AsYaml,
new_key: impl AsYaml,
new_value: impl AsYaml,
) -> bool
pub fn move_after( &self, after_key: impl AsYaml, new_key: impl AsYaml, new_value: impl AsYaml, ) -> bool
Move a key-value pair to immediately after an existing key.
If new_key already exists in the mapping, that entry is rebuilt with the
new value, the old one going as with remove, and moved
after after_key - so the key ends up at the requested position regardless
of where it was before. Passing the entry’s current value, as
get returns it, moves the entry as it is, comments and
anchor included. Either way the entry moves as with
reorder_fields, which says what happens to aliases.
If after_key is not found, returns false and leaves the mapping unchanged.
Returns true on success.
Use insert_after if you want existing entries to be
updated in-place rather than moved.
Sourcepub fn move_before(
&self,
before_key: impl AsYaml,
new_key: impl AsYaml,
new_value: impl AsYaml,
) -> bool
pub fn move_before( &self, before_key: impl AsYaml, new_key: impl AsYaml, new_value: impl AsYaml, ) -> bool
Move a key-value pair to immediately before an existing key.
If new_key already exists in the mapping, that entry is moved before
before_key, with the new value, as with move_after.
If before_key is not found, returns false and leaves the mapping unchanged.
Returns true on success.
Use insert_before if you want existing entries to be
updated in-place rather than moved.
Source§impl Mapping
impl Mapping
Sourcepub fn dump_cst(&self) -> String
pub fn dump_cst(&self) -> String
Dump the CST (Concrete Syntax Tree) structure to a human-readable string.
This is intended for debugging and testing. The output shows the full node hierarchy with indentation.
Sourcepub fn keys(&self) -> impl Iterator<Item = YamlNode> + '_
pub fn keys(&self) -> impl Iterator<Item = YamlNode> + '_
Iterate over all keys in this mapping as YamlNodes.
Each key is returned as a YamlNode wrapping
the underlying CST node, preserving quoting style and other formatting.
The nodes implement AsYaml, so they can be passed
back to get, contains_key, etc.,
and compared semantically with yaml_eq.
Prefer entries when you also need the values, or
iter for (key, value) pairs as (YamlNode, YamlNode).
For raw CST nodes, use pairs().
Sourcepub fn get(&self, key: impl AsYaml) -> Option<YamlNode>
pub fn get(&self, key: impl AsYaml) -> Option<YamlNode>
Get the value associated with key as a YamlNode.
Returns None if the key does not exist.
Matching is semantic but type-strict, so a key’s type has to match as
well as its text: 1 does not find the string key "1", and the
null key of : v is found with
ScalarValue::null rather than "",
which finds the distinct empty-string key of "": v.
let doc = Document::from_str(": a\n\"\": b\n").unwrap();
let mapping = doc.as_mapping().unwrap();
assert!(mapping.get(ScalarValue::null()).is_some());
assert!(mapping.get("").is_some());Sourcepub fn get_mapping(&self, key: impl AsYaml) -> Option<Mapping>
pub fn get_mapping(&self, key: impl AsYaml) -> Option<Mapping>
Get the value for key as a nested Mapping.
Returns None if the key does not exist or its value is not a mapping.
A tag on the value is looked through: key: !custom over a block
mapping still gives that mapping.
Sourcepub fn modify_mapping<F>(&self, key: impl AsYaml, f: F) -> bool
pub fn modify_mapping<F>(&self, key: impl AsYaml, f: F) -> bool
Modify a nested mapping in place by applying a closure to it.
Returns true if key exists and its value is a mapping (and f was
called); returns false if the key is missing or its value is not a
mapping.
Because Mapping uses interior mutability via rowan’s SyntaxNode,
the closure receives a shared reference - mutations are still possible
through the node’s set, remove, and other &self methods.
Sourcepub fn get_sequence(&self, key: impl AsYaml) -> Option<Sequence>
pub fn get_sequence(&self, key: impl AsYaml) -> Option<Sequence>
Get the value for key as a nested Sequence.
Returns None if the key does not exist or its value is not a sequence.
A tag on the value is looked through, as for
get_mapping.
Sourcepub fn contains_key(&self, key: impl AsYaml) -> bool
pub fn contains_key(&self, key: impl AsYaml) -> bool
Returns true if this mapping contains an entry with the given key.
Sourcepub fn new_flow() -> Self
pub fn new_flow() -> Self
An empty mapping that renders as {} and stays flow when filled.
Use this for a mapping that is meant to be flow-style in the output, including one that is left empty.
Sourcepub fn new_pending_block() -> Self
pub fn new_pending_block() -> Self
An empty mapping that becomes a block mapping once an entry is added.
YAML has no block syntax for an empty mapping: block collections are
written as their entries, so with none left there is nothing to write,
and a bare key: reads back as null. An empty mapping is therefore
{} whatever its eventual style, and block-vs-flow only becomes a
real choice once there is an entry.
This renders as exactly {}, plus a zero-width token that marks it as
destined for block style. Mapping::set rewrites it into block form
when the first entry arrives; a {} that came from the source has no
such marker and keeps its flow style.
A block mapping that loses its last entry to remove or clear is
written the same way, marker included.
The marker lives only in the tree. Serializing and re-parsing yields
an ordinary {}, which stays flow, since YAML has nowhere to record
the intent.
Sourcepub fn reorder_fields<I, K>(&self, order: I)where
I: IntoIterator<Item = K>,
K: AsYaml,
pub fn reorder_fields<I, K>(&self, order: I)where
I: IntoIterator<Item = K>,
K: AsYaml,
Reorder fields according to the specified order.
Fields not in the order list will appear after the ordered fields, in their original relative order.
An alias that ends up before the node it refers to becomes a copy of it, anchor included, and the node an alias where it can.
Source§impl Mapping
impl Mapping
Sourcepub fn is_flow_style(&self) -> bool
pub fn is_flow_style(&self) -> bool
Check if this mapping is in flow style (JSON/inline format with {}).
Returns true if the mapping uses flow style (e.g., {key: value},
or a single pair in a flow sequence such as [key: value]), false
if it uses block style (e.g., key: value).
Sourcepub fn find_entry_by_key(&self, key: impl AsYaml) -> Option<MappingEntry>
pub fn find_entry_by_key(&self, key: impl AsYaml) -> Option<MappingEntry>
Find the MappingEntry whose key matches key, or None if not found.
Matching is semantic (quoting style is ignored), so "foo", 'foo',
and foo all match the scalar "foo".
Sourcepub fn find_all_entries_by_key<'a>(
&'a self,
key: impl AsYaml + 'a,
) -> impl Iterator<Item = MappingEntry> + 'a
pub fn find_all_entries_by_key<'a>( &'a self, key: impl AsYaml + 'a, ) -> impl Iterator<Item = MappingEntry> + 'a
Find all entries with a given key.
Returns an iterator over all MappingEntry instances that match the
given key. This is useful for handling duplicate keys in YAML (which
are allowed by the spec but semantically ambiguous).
Matching is semantic (quoting style is ignored), so "foo", 'foo',
and foo all match the scalar "foo".
§Example
let yaml = r#"
Reference: First
Reference: Second
Reference: Third
"#;
let doc = Document::from_str(yaml).unwrap();
let mapping = doc.as_mapping().unwrap();
// Collect all Reference entries
let refs: Vec<_> = mapping.find_all_entries_by_key("Reference").collect();
assert_eq!(refs.len(), 3);
// Remove all but the first occurrence
let _: Vec<()> = refs.into_iter().skip(1).map(|entry| entry.remove()).collect();Sourcepub fn entries(&self) -> impl Iterator<Item = MappingEntry>
pub fn entries(&self) -> impl Iterator<Item = MappingEntry>
Iterate over all entries in this mapping as typed MappingEntry handles.
Each MappingEntry gives access to the key, value, and mutation
methods for that entry. For decoded (key, value) pairs, prefer
iter; for raw CST nodes, use pairs().
Sourcepub fn entry<K: AsYaml>(&self, key: K) -> Entry<'_, K>
pub fn entry<K: AsYaml>(&self, key: K) -> Entry<'_, K>
Return an Entry view into the entry for key.
Mirrors std::collections::BTreeMap::entry, enabling
insert-or-update patterns while preserving formatting.
use std::str::FromStr;
use yaml_edit::Document;
let doc = Document::from_str("name: Alice\n").unwrap();
let mapping = doc.as_mapping().unwrap();
mapping.entry("age").or_insert(30);
mapping.entry("name").or_insert("Bob");
assert_eq!(doc.to_string(), "name: Alice\nage: 30\n");Sourcepub fn find_entry_index_by_key(&self, key: impl AsYaml) -> Option<usize>
pub fn find_entry_index_by_key(&self, key: impl AsYaml) -> Option<usize>
Find the child index of a mapping entry by its key.
Returns the index within the mapping’s children (including non-entry
tokens like whitespace), or None if no entry with the given key exists.
This index is suitable for use with splice_children.
Sourcepub fn set(&self, key: impl AsYaml, value: impl AsYaml)
pub fn set(&self, key: impl AsYaml, value: impl AsYaml)
Set a key-value pair, replacing the existing value if the key exists or
appending a new entry if it does not. Accepts any value that implements
AsYaml - scalars, mappings, sequences, etc.
This method always succeeds; it never silently ignores input. See also
insert_after and insert_before
which return bool to indicate whether the anchor key was found.
Mutates in place despite &self (see crate docs on interior mutability).
set replaces the value with the node you pass. It does not infer
YAML 1.1 merge keys from a resolved map. To keep identity, pass an
alias node (*name) or a mapping that already contains <<: *name.
Merge reads (get_resolved(), merged()) stay separate from
this CST replace.
An anchor on the replaced value stays, on the new value, so aliases
to it still resolve: b: &x 2 set to 6 gives b: &x 6. A node
value that has an anchor of its own keeps it only if the old value
had none. The first alias to an anchor deeper in the old value
becomes a copy of the anchored node: b: {c: &y 1} and d: *y give
b: 6 and d: &y 1.
use std::str::FromStr;
use yaml_edit::Document;
let doc = Document::from_str(
"shared: &shared\n timeout: 30\n retries: 3\nservice_a: old\n",
)
.unwrap();
let mapping = doc.as_mapping().unwrap();
let merge = Document::from_str("<<: *shared\ntimeout: 60\n").unwrap();
mapping.set("service_a", merge.as_mapping().unwrap());
assert_eq!(
doc.to_string(),
"shared: &shared\n timeout: 30\n retries: 3\nservice_a:\n <<: *shared\n timeout: 60\n"
);Sourcepub fn set_with_field_order<I, K>(
&self,
key: impl AsYaml,
value: impl AsYaml,
field_order: I,
)where
I: IntoIterator<Item = K>,
K: AsYaml,
pub fn set_with_field_order<I, K>(
&self,
key: impl AsYaml,
value: impl AsYaml,
field_order: I,
)where
I: IntoIterator<Item = K>,
K: AsYaml,
Set a key-value pair with field ordering support If the key exists, updates its value. If the key doesn’t exist, inserts it at the correct position based on the provided field order. Fields not in the order list are placed at the end.
Sourcepub fn detect_indentation_level(&self) -> usize
pub fn detect_indentation_level(&self) -> usize
Detect the indentation level (in spaces) used by entries in this mapping.
Returns 0 for root-level mappings where entries have no leading indentation.
Sourcepub fn insert_at_index_preserving(
&self,
index: usize,
new_key: impl AsYaml,
new_value: impl AsYaml,
)
pub fn insert_at_index_preserving( &self, index: usize, new_key: impl AsYaml, new_value: impl AsYaml, )
Insert a key-value pair at a specific index (0-based), preserving formatting.
If new_key already exists in the mapping, the existing entry is replaced
with a newly built entry at the same position (the index argument is
ignored). Surrounding whitespace in the file is preserved, but the entry
node itself is rebuilt (comments attached to the old entry may be lost).
An anchor on the old value stays on the new one, as with
set.
If index is out of bounds, the entry is appended at the end.
Sourcepub fn remove(&self, key: impl AsYaml) -> Option<MappingEntry>
pub fn remove(&self, key: impl AsYaml) -> Option<MappingEntry>
Remove a key-value pair, returning the removed entry.
Returns Some(entry) if the key existed and was removed, or None if
the key was not found. The returned MappingEntry is detached from
the tree; callers can inspect its key and value or re-insert it
elsewhere.
The first alias to an anchor in the removed entry becomes a copy of the anchored node, so it and later aliases keep their value.
Mutates in place despite &self (see crate docs on interior mutability).
Sourcepub fn remove_nth_occurrence(
&self,
key: impl AsYaml,
n: usize,
) -> Option<MappingEntry>
pub fn remove_nth_occurrence( &self, key: impl AsYaml, n: usize, ) -> Option<MappingEntry>
Remove the nth occurrence of a key, returning the removed entry.
Returns Some(entry) if the nth occurrence exists and was removed,
or None if there are fewer than n+1 occurrences of the key.
The index n is 0-based (n=0 removes the first occurrence, n=1 removes
the second, etc.).
This is useful for handling duplicate keys in YAML. While duplicate keys are semantically ambiguous, they are allowed by the YAML spec, and this method provides fine-grained control over which occurrence to remove.
§Example
let yaml = r#"
Reference: First
Reference: Second
Reference: Third
"#;
let doc = Document::from_str(yaml).unwrap();
let mapping = doc.as_mapping().unwrap();
// Remove the second occurrence (index 1)
let removed = mapping.remove_nth_occurrence("Reference", 1);
assert!(removed.is_some());
// Now only two Reference entries remain
let count = mapping.find_all_entries_by_key("Reference").count();
assert_eq!(count, 2);Mutates in place despite &self (see crate docs on interior mutability).
Sourcepub fn clear(&self)
pub fn clear(&self)
Remove all key-value pairs from this mapping.
Mutates in place despite &self (see crate docs on interior mutability).
Sourcepub fn rename_key(&self, old_key: impl AsYaml, new_key: impl AsYaml) -> bool
pub fn rename_key(&self, old_key: impl AsYaml, new_key: impl AsYaml) -> bool
Rename a key while preserving its value and formatting.
The new key is built using the same AsYaml infrastructure as other
write methods, so quoting and escaping are handled automatically.
Returns true if the key was found and renamed, false if old_key
does not exist.
If new_key differs from old_key and is already present, the
existing new_key entry is removed, as with set and
move_after, so the rename does not create a
duplicate key. The renamed entry keeps its position, value and
comments.
The key keeps its anchor, so aliases to it still resolve; an anchor
on a new_key node is used only if the old key had none. The key’s
tag is kept if new_key has no tag of its own and still means the
same with it: !!str a renamed to "b" gives !!str b, but renamed
to 1 gives 1, as !!str 1 would be a string. The first alias to
an anchor deeper in the old key becomes a copy of the anchored node.
let doc = Document::from_str("a: 1\nb: 2\nc: 3\n").unwrap();
assert!(doc.as_mapping().unwrap().rename_key("a", "b"));
assert_eq!(doc.to_string(), "b: 1\nc: 3\n");Mutates in place despite &self (see crate docs on interior mutability).
Sourcepub fn insert_after(
&self,
after_key: impl AsYaml,
key: impl AsYaml,
value: impl AsYaml,
) -> bool
pub fn insert_after( &self, after_key: impl AsYaml, key: impl AsYaml, value: impl AsYaml, ) -> bool
Insert a key-value pair immediately after an existing key.
If key already exists in the mapping, its value is updated in-place and
it remains at its current position (it is not moved to after after_key).
Returns true in both the update and the insert cases.
Returns false only if after_key is not found.
Use move_after if you want
an existing entry to be moved to the new position.
Mutates in place despite &self (see crate docs on interior mutability).
Sourcepub fn insert_before(
&self,
before_key: impl AsYaml,
key: impl AsYaml,
value: impl AsYaml,
) -> bool
pub fn insert_before( &self, before_key: impl AsYaml, key: impl AsYaml, value: impl AsYaml, ) -> bool
Insert a key-value pair immediately before an existing key.
If key already exists in the mapping, its value is updated in-place and
it remains at its current position (it is not moved to before before_key).
Returns true in both the update and the insert cases.
Returns false only if before_key is not found.
Use move_before if you want
an existing entry to be moved to the new position.
Mutates in place despite &self (see crate docs on interior mutability).
Sourcepub fn insert_at_index(
&self,
index: usize,
key: impl AsYaml,
value: impl AsYaml,
)
pub fn insert_at_index( &self, index: usize, key: impl AsYaml, value: impl AsYaml, )
Insert a key-value pair at a specific index (0-based).
If key already exists in the mapping, its value is updated in-place and
it remains at its current position (the index argument is ignored).
If index is out of bounds, the entry is appended at the end.
This method always succeeds; it never returns an error.
Mutates in place despite &self (see crate docs on interior mutability).
Sourcepub fn byte_range(&self) -> TextPosition
pub fn byte_range(&self) -> TextPosition
Get the byte offset range of this mapping in the source text.
Returns the start and end byte offsets as a TextPosition.
Sourcepub fn start_position(&self, source_text: &str) -> LineColumn
pub fn start_position(&self, source_text: &str) -> LineColumn
Get the line and column where this mapping starts.
Requires the original source text to calculate line/column from byte offsets. Line and column numbers are 1-indexed.
§Arguments
source_text- The original YAML source text
Sourcepub fn end_position(&self, source_text: &str) -> LineColumn
pub fn end_position(&self, source_text: &str) -> LineColumn
Get the line and column where this mapping ends.
Requires the original source text to calculate line/column from byte offsets. Line and column numbers are 1-indexed.
§Arguments
source_text- The original YAML source text
Trait Implementations§
Source§impl AsYaml for Mapping
impl AsYaml for Mapping
Source§fn as_node(&self) -> Option<&SyntaxNode<Lang>>
fn as_node(&self) -> Option<&SyntaxNode<Lang>>
SyntaxNode if one exists. Read moreSource§fn build_content(
&self,
builder: &mut GreenNodeBuilder<'_>,
indent: usize,
_flow_context: bool,
) -> bool
fn build_content( &self, builder: &mut GreenNodeBuilder<'_>, indent: usize, _flow_context: bool, ) -> bool
GreenNodeBuilder. Read moreimpl Eq for Mapping
Source§impl<'a> IntoIterator for &'a Mapping
impl<'a> IntoIterator for &'a Mapping
Source§impl MappingMergedExt for Mapping
impl MappingMergedExt for Mapping
Source§fn merged<'a>(
&self,
registry: &'a AnchorRegistry,
) -> Result<MergedMapping<'a>, ResolveError>
fn merged<'a>( &self, registry: &'a AnchorRegistry, ) -> Result<MergedMapping<'a>, ResolveError>
MergedMapping view over this mapping that resolves
aliases and merge keys against registry. Read moreSource§impl MappingView for Mapping
impl MappingView for Mapping
impl StructuralPartialEq for Mapping
Source§impl YamlAccept for Mapping
impl YamlAccept for Mapping
Source§fn accept<V: YamlVisitor>(&self, visitor: &mut V)
fn accept<V: YamlVisitor>(&self, visitor: &mut V)
Source§impl YamlPath for Mapping
impl YamlPath for Mapping
Source§fn try_get_path_with(
&self,
path: &str,
policy: AliasPolicy,
) -> Result<YamlNode, PathError>
fn try_get_path_with( &self, path: &str, policy: AliasPolicy, ) -> Result<YamlNode, PathError>
Source§fn try_set_path_with(
&self,
path: &str,
value: impl AsYaml,
policy: AliasPolicy,
) -> Result<(), PathError>
fn try_set_path_with( &self, path: &str, value: impl AsYaml, policy: AliasPolicy, ) -> Result<(), PathError>
try_set_path, but with an explicit
AliasPolicy for intermediate segments that land on an alias. Read moreSource§fn try_remove_path_with(
&self,
path: &str,
policy: AliasPolicy,
) -> Result<YamlNode, PathError>
fn try_remove_path_with( &self, path: &str, policy: AliasPolicy, ) -> Result<YamlNode, PathError>
try_remove_path, but with an
explicit AliasPolicy for intermediate segments that land on
an alias. Read moreSource§fn get_path(&self, path: &str) -> Option<YamlNode>
fn get_path(&self, path: &str) -> Option<YamlNode>
use try_get_path; get_path swallows PathError as None