Skip to main content

ValueRef

Struct ValueRef 

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

A zero-copy typed view of a YAML node.

ValueRef wraps a NodeRef and provides typed accessor methods that interpret YAML scalars as specific types without allocation.

§Type Interpretation

YAML scalars are stored as strings, but can represent various types. ValueRef provides methods to interpret these on demand:

  • as_str() - Returns the raw string content (zero-copy)
  • as_bool() - Interprets as boolean (true, false, yes, no, etc.)
  • as_i64() / as_u64() - Interprets as integer (supports hex, octal, binary)
  • as_f64() - Interprets as floating point (supports .inf, .nan)
  • is_null() - Checks for null (null, ~, empty)

§Non-Plain Scalar Awareness

Scalars with non-plain styles (single-quoted '...', double-quoted "...", literal block |, folded block >) are treated as strings and will not be type-interpreted. This matches YAML semantics where 'true' is a string, not a boolean.

use fyaml::Document;

let doc = Document::parse_str("quoted: 'true'\nunquoted: true").unwrap();
let root = doc.root_value().unwrap();

// Quoted: treated as string, not interpreted
assert_eq!(root.get("quoted").unwrap().as_bool(), None);
assert_eq!(root.get("quoted").unwrap().as_str(), Some("true"));

// Unquoted (plain): interpreted as boolean
assert_eq!(root.get("unquoted").unwrap().as_bool(), Some(true));

§YAML 1.1 Boolean Compatibility

Boolean interpretation accepts YAML 1.1-style values (yes/no, on/off) in addition to YAML 1.2 core schema values (true/false). This matches the behavior of many YAML parsers and configuration files.

Implementations§

Source§

impl<'doc> ValueRef<'doc>

Source

pub fn new(node: NodeRef<'doc>) -> Self

Creates a new ValueRef from a NodeRef.

Source

pub fn as_node(&self) -> NodeRef<'doc>

Returns the underlying NodeRef.

Source

pub fn is_scalar(&self) -> bool

Returns true if this is a scalar node.

Source

pub fn is_sequence(&self) -> bool

Returns true if this is a sequence (array/list).

Source

pub fn is_mapping(&self) -> bool

Returns true if this is a mapping (object/dictionary).

Source

pub fn is_null(&self) -> bool

Returns true if this scalar represents a null value.

Recognizes: null (case-insensitive), ~, and empty scalars. Non-plain scalars (quoted, literal, folded) are never considered null.

Source

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

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

Returns None if this is not a scalar or if the content is not valid UTF-8.

§Example
use fyaml::Document;

let doc = Document::parse_str("name: Alice").unwrap();
let root = doc.root_value().unwrap();
assert_eq!(root.get("name").unwrap().as_str(), Some("Alice"));
Source

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

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

Returns None if this is not a scalar.

Source

pub fn as_bool(&self) -> Option<bool>

Interprets the scalar as a boolean.

Recognizes YAML 1.1 boolean values (for compatibility with common configs):

  • True: true, True, TRUE, yes, Yes, YES, on, On, ON
  • False: false, False, FALSE, no, No, NO, off, Off, OFF

Returns None if not a scalar, non-plain (quoted/literal/folded), or not a recognized boolean string.

§Note

YAML 1.2 core schema only recognizes true/false. This method also accepts yes/no/on/off for compatibility with YAML 1.1 and common configuration files.

§Example
use fyaml::Document;

let doc = Document::parse_str("active: yes\nenabled: false").unwrap();
let root = doc.root_value().unwrap();
assert_eq!(root.get("active").unwrap().as_bool(), Some(true));
assert_eq!(root.get("enabled").unwrap().as_bool(), Some(false));
Source

pub fn as_i64(&self) -> Option<i64>

Interprets the scalar as a signed 64-bit integer.

Supports:

  • Decimal: 42, -10, +5
  • Hexadecimal: 0xFF, -0xFF
  • Octal: 0o77, -0o77
  • Binary: 0b1010, -0b1010

Returns None if not a scalar, non-plain (quoted/literal/folded), not a valid integer, or overflows i64.

§Example
use fyaml::Document;

let doc = Document::parse_str("count: 42\nnegative: -10").unwrap();
let root = doc.root_value().unwrap();
assert_eq!(root.get("count").unwrap().as_i64(), Some(42));
assert_eq!(root.get("negative").unwrap().as_i64(), Some(-10));
Source

pub fn as_u64(&self) -> Option<u64>

Interprets the scalar as an unsigned 64-bit integer.

Supports:

  • Decimal: 42, +5
  • Hexadecimal: 0xFF
  • Octal: 0o77
  • Binary: 0b1010

Returns None if not a scalar, non-plain, negative, not a valid integer, or overflows u64.

Source

pub fn as_f64(&self) -> Option<f64>

Interprets the scalar as a 64-bit floating point number.

Recognizes:

  • Standard floats: 3.14, 1.0e10, -2.5
  • Positive infinity: .inf, +.inf (case-insensitive)
  • Negative infinity: -.inf (case-insensitive)
  • Not a number: .nan (case-insensitive)

Note: Unlike as_i64(), plain integers like 42 will also parse as floats (42.0). Use as_i64() first if you need to distinguish.

Returns None if not a scalar, non-plain, or not a valid float.

§Example
use fyaml::Document;

let doc = Document::parse_str("pi: 3.14159\ninf: .inf").unwrap();
let root = doc.root_value().unwrap();
assert!((root.get("pi").unwrap().as_f64().unwrap() - 3.14159).abs() < 0.0001);
assert!(root.get("inf").unwrap().as_f64().unwrap().is_infinite());
Source

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

Navigates to a child node by path.

See NodeRef::at_path for path format details.

Source

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

Gets a value from a mapping by string key.

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

§Example
use fyaml::Document;

let doc = Document::parse_str("name: Alice\nage: 30").unwrap();
let root = doc.root_value().unwrap();
assert_eq!(root.get("name").unwrap().as_str(), Some("Alice"));
assert!(root.get("missing").is_none());
Source

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

Gets a sequence item by index.

Negative indices count from the end (-1 is the last element).

Returns None if this is not a sequence or index is out of bounds.

Source

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

Returns the number of items in a sequence.

Returns None if this is not a sequence.

Source

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

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

Returns None if this is not a mapping.

Source

pub fn seq_iter(&self) -> impl Iterator<Item = ValueRef<'doc>>

Returns an iterator over sequence items as ValueRef.

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

§Example
use fyaml::Document;

let doc = Document::parse_str("- 1\n- 2\n- 3").unwrap();
let root = doc.root_value().unwrap();

let sum: i64 = root.seq_iter()
    .filter_map(|v| v.as_i64())
    .sum();
assert_eq!(sum, 6);
Source

pub fn map_iter(&self) -> impl Iterator<Item = (ValueRef<'doc>, ValueRef<'doc>)>

Returns an iterator over mapping key-value pairs as (ValueRef, ValueRef).

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_value().unwrap();

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

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

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

Returns None if the node has no explicit tag.

Trait Implementations§

Source§

impl<'doc> Clone for ValueRef<'doc>

Source§

fn clone(&self) -> ValueRef<'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 ValueRef<'_>

Source§

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

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

impl Display for ValueRef<'_>

Source§

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

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

impl<'doc> Copy for ValueRef<'doc>

Auto Trait Implementations§

§

impl<'doc> Freeze for ValueRef<'doc>

§

impl<'doc> RefUnwindSafe for ValueRef<'doc>

§

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

§

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

§

impl<'doc> Unpin for ValueRef<'doc>

§

impl<'doc> UnwindSafe for ValueRef<'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.