Skip to main content

Mapping

Struct Mapping 

Source
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

Source

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.

Source

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().

Source

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.

Source

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.

Source

pub fn modify_mapping<F>(&self, key: impl AsYaml, f: F) -> bool
where F: FnOnce(&Mapping),

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.

Source

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.

Source

pub fn contains_key(&self, key: impl AsYaml) -> bool

Returns true if this mapping contains an entry with the given key.

Source

pub fn is_empty(&self) -> bool

Check if the mapping is empty

Source

pub fn len(&self) -> usize

Get the number of key-value pairs in this mapping

Source

pub fn values(&self) -> impl Iterator<Item = YamlNode> + '_

Iterate over the values in this mapping as YamlNodes.

Only entries whose value can be successfully wrapped in a YamlNode are yielded; malformed or unrecognised value nodes are silently skipped. Use iter to get both the key and value simultaneously, or pairs() for the raw SyntaxNode pairs.

Source

pub fn iter(&self) -> impl Iterator<Item = (YamlNode, YamlNode)> + '_

Iterate over (key, value) pairs, both as YamlNodes.

Entries that cannot be fully wrapped (malformed key or value nodes) are silently skipped. For raw CST nodes, use pairs(); for typed entry handles, prefer entries.

Source

pub fn new() -> Self

Create a new empty mapping

Source

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

Source

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).

Source

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".

Source

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();
Source

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().

Source

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.

Source

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).

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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).

Source

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).

Source

pub fn clear(&self)

Remove all key-value pairs from this mapping.

Mutates in place despite &self (see crate docs on interior mutability).

Source

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).

Source

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).

Source

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).

Source

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).

Source

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.

Source

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
Source

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

Source§

fn as_node(&self) -> Option<&SyntaxNode<Lang>>

Returns a reference to the underlying SyntaxNode if one exists. Read more
Source§

fn kind(&self) -> YamlKind

Returns the kind of YAML value this represents.
Source§

fn build_content( &self, builder: &mut GreenNodeBuilder<'_>, indent: usize, _flow_context: bool, ) -> bool

Serialize this value into a GreenNodeBuilder. Read more
Source§

fn is_inline(&self) -> bool

Returns whether this value should be rendered on the same line as its key. Read more
Source§

impl AstNode for Mapping

Source§

type Language = Lang

Source§

fn can_cast(kind: SyntaxKind) -> bool

Source§

fn cast(syntax: SyntaxNode<Lang>) -> Option<Self>

Source§

fn syntax(&self) -> &SyntaxNode<Lang>

Source§

fn clone_for_update(&self) -> Self
where Self: Sized,

Source§

fn clone_subtree(&self) -> Self
where Self: Sized,

Source§

impl Clone for Mapping

Source§

fn clone(&self) -> Mapping

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Mapping

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Mapping

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Mapping

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Hash for Mapping

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<'a> IntoIterator for &'a Mapping

Source§

type Item = (YamlNode, YamlNode)

The type of the elements being iterated over.
Source§

type IntoIter = Box<dyn Iterator<Item = (YamlNode, YamlNode)> + 'a>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for Mapping

Source§

fn eq(&self, other: &Mapping) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl YamlAccept for Mapping

Source§

fn accept<V: YamlVisitor>(&self, visitor: &mut V)

Accept a visitor for traversal
Source§

impl YamlPath for Mapping

Source§

fn get_path(&self, path: &str) -> Option<YamlNode>

Get a value at a nested path. Read more
Source§

fn set_path(&self, path: &str, value: impl AsYaml)

Set a value at a nested path, creating intermediate mappings if needed. Read more
Source§

fn remove_path(&self, path: &str) -> bool

Remove a value at a nested path. Read more
Source§

impl Eq for Mapping

Source§

impl StructuralPartialEq for Mapping

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.