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 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.
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.
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.
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 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.
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}),
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 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).
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 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, it is first removed from its
current position and then re-inserted after after_key with the new value —
so the key ends up at the requested position regardless of where it was before.
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, it is first removed from its
current position and then re-inserted before before_key with the new value.
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.
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).
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.
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.
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 more