Skip to main content

NodeRef

Struct NodeRef 

Source
pub struct NodeRef<'doc> { /* private fields */ }
Expand description

A borrowed reference to a YAML node.

NodeRef<'doc> provides zero-copy access to node data. The lifetime 'doc ties the reference to its parent Document, ensuring the node cannot outlive the document.

§Zero-Copy Scalar Access

Scalar data is accessed directly from libfyaml’s internal buffers:

use fyaml::Document;

let doc = Document::parse_str("key: value").unwrap();
let root = doc.root().unwrap();
let value = root.at_path("/key").unwrap();

// This returns &'doc str - zero allocation!
let s: &str = value.scalar_str().unwrap();
assert_eq!(s, "value");

Navigate the tree using paths or iteration:

use fyaml::Document;

let doc = Document::parse_str("users:\n  - name: Alice\n  - name: Bob").unwrap();
let root = doc.root().unwrap();

// Path navigation
let first_user = root.at_path("/users/0/name").unwrap();
assert_eq!(first_user.scalar_str().unwrap(), "Alice");

// Iteration
let users = root.at_path("/users").unwrap();
for user in users.seq_iter() {
    println!("{}", user.at_path("/name").unwrap().scalar_str().unwrap());
}

§Thread Safety

NodeRef is !Send and !Sync because the underlying document is not thread-safe.

Implementations§

Source§

impl<'doc> NodeRef<'doc>

Source

pub fn document(&self) -> &'doc Document

Returns a reference to the parent document.

Source

pub fn kind(&self) -> NodeType

Returns the type of this node.

Source

pub fn is_scalar(&self) -> bool

Returns true if this node is a scalar value.

Source

pub fn is_mapping(&self) -> bool

Returns true if this node is a mapping (dictionary).

Source

pub fn is_sequence(&self) -> bool

Returns true if this node is a sequence (list).

Source

pub fn style(&self) -> NodeStyle

Returns the style of this node.

For scalar nodes, this indicates quoting style (plain, single-quoted, etc.). For sequences/mappings, this indicates flow vs block style.

Source

pub fn is_quoted(&self) -> bool

Returns true if this scalar was quoted (single or double quotes).

Source

pub fn is_non_plain(&self) -> bool

Returns true if this scalar has a non-plain style.

Non-plain styles include single-quoted, double-quoted, literal (|), and folded (>). These styles should prevent type inference (the value should be treated as a string, not inferred as bool/int/null).

Source

pub fn scalar_bytes(&self) -> Result<&'doc [u8]>

Returns the scalar value as a byte slice (zero-copy).

The returned slice points directly into libfyaml’s internal buffer. It is valid for the lifetime 'doc of the document.

§Errors

Returns an error if this is not a scalar node.

§Example
use fyaml::Document;

let doc = Document::parse_str("data: hello").unwrap();
let node = doc.at_path("/data").unwrap();
assert_eq!(node.scalar_bytes().unwrap(), b"hello");
Source

pub fn scalar_str(&self) -> Result<&'doc str>

Returns the scalar value as a string slice (zero-copy).

The returned string points directly into libfyaml’s internal buffer. It is valid for the lifetime 'doc of the document.

§Errors

Returns an error if this is not a scalar node or if the content is not valid UTF-8.

§Example
use fyaml::Document;

let doc = Document::parse_str("name: Alice").unwrap();
let name = doc.at_path("/name").unwrap().scalar_str().unwrap();
assert_eq!(name, "Alice");
Source

pub fn tag_bytes(&self) -> Result<Option<&'doc [u8]>>

Returns the YAML tag as a byte slice (zero-copy).

Returns Ok(None) if the node has no explicit tag.

Source

pub fn tag_str(&self) -> Result<Option<&'doc str>>

Returns the YAML tag as a string slice (zero-copy).

Returns Ok(None) if the node has no explicit tag.

Source

pub fn at_path(&self, path: &str) -> Option<NodeRef<'doc>>

Navigates to a child node by path.

Path format uses / as separator:

  • /foo - access key “foo” in a mapping
  • /0 - access index 0 in a sequence
  • /foo/bar/0 - nested access
  • `` (empty) - returns self

Returns None if the path doesn’t exist.

§Example
use fyaml::Document;

let doc = Document::parse_str("a:\n  b:\n    c: deep").unwrap();
let deep = doc.root().unwrap().at_path("/a/b/c").unwrap();
assert_eq!(deep.scalar_str().unwrap(), "deep");
Source

pub fn seq_len(&self) -> Result<usize>

Returns the number of items in a sequence node.

§Errors

Returns an error if this is not a sequence.

Source

pub fn map_len(&self) -> Result<usize>

Returns the number of key-value pairs in a mapping node.

§Errors

Returns an error if this is not a mapping.

Source

pub fn seq_get(&self, index: i32) -> Option<NodeRef<'doc>>

Gets a sequence item by index.

Returns None if the index is out of bounds or this is not a sequence. Negative indices count from the end (-1 is the last element).

Source

pub fn seq_iter(&self) -> SeqIter<'doc>

Returns an iterator over items in a sequence node.

If this is not a sequence, the iterator will be empty.

§Example
use fyaml::Document;

let doc = Document::parse_str("- a\n- b\n- c").unwrap();
let root = doc.root().unwrap();

let items: Vec<&str> = root.seq_iter()
    .map(|n| n.scalar_str().unwrap())
    .collect();
assert_eq!(items, vec!["a", "b", "c"]);
Source

pub fn map_get(&self, key: &str) -> Option<NodeRef<'doc>>

Looks up a value in this mapping by string key.

Returns None if the key is not found or this is not a mapping.

Source

pub fn map_iter(&self) -> MapIter<'doc>

Returns an iterator over key-value pairs in a mapping node.

If this is not a mapping, the iterator will be empty.

§Example
use fyaml::Document;

let doc = Document::parse_str("a: 1\nb: 2").unwrap();
let root = doc.root().unwrap();

for (key, value) in root.map_iter() {
    println!("{}: {}", key.scalar_str().unwrap(), value.scalar_str().unwrap());
}
Source

pub fn emit(&self) -> Result<String>

Emits this node as a YAML string.

For scalar nodes, this includes any quoting. For complex nodes, this returns properly formatted YAML.

This always allocates a new string. If the emitted content contains invalid UTF-8 (rare), invalid bytes are replaced with U+FFFD.

Trait Implementations§

Source§

impl<'doc> Clone for NodeRef<'doc>

Source§

fn clone(&self) -> NodeRef<'doc>

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 NodeRef<'_>

Source§

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

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

impl Display for NodeRef<'_>

Source§

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

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

impl<'doc> Copy for NodeRef<'doc>

Auto Trait Implementations§

§

impl<'doc> Freeze for NodeRef<'doc>

§

impl<'doc> RefUnwindSafe for NodeRef<'doc>

§

impl<'doc> !Send for NodeRef<'doc>

§

impl<'doc> !Sync for NodeRef<'doc>

§

impl<'doc> Unpin for NodeRef<'doc>

§

impl<'doc> UnwindSafe for NodeRef<'doc>

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