Struct yaml_peg::Node

source ·
pub struct Node<R: Repr> { /* private fields */ }
Expand description

Readonly node, including line number, column number, type assertion and anchor. You can access Yaml type through Node::yaml method.

This type will ignore additional information when comparison and hashing.

use std::collections::HashSet;
use yaml_peg::{NodeRc, Yaml};

let mut s = HashSet::new();
s.insert(NodeRc::new(Yaml::from("a"), 0, ""));
s.insert(NodeRc::new("a", 1, "my-tag"));
s.insert(NodeRc::new("a", 2, ""));
assert_eq!(s.len(), 1);

There is also a convenient macro node! to create nodes literally. Please see the macro description for more information.

Nodes can be indexing by convertable values, or sequence indicator Ind, but it will be panic if the index is not contained.

use yaml_peg::{node, Ind};

let n = node!(["a", "b", "c"]);
assert_eq!(node!("b"), n[Ind(1)]);
use yaml_peg::{node, Ind};

let n = node!(());
let n = &n["a"][Ind(0)]["b"];

Same as containers, to prevent panic, the Node::get method is the best choice. The Node::get_default can provide missing key value when indexing.

There are as_* methods provide Result<T, u64> returns with node position, default options can be created by Result::unwrap_or, additional error message can be attach by Result::map_err, and the optional Option can be return by Result::ok, which shown as following example:

use yaml_peg::node;

fn main() -> Result<(), (&'static str, u64)> {
    let n = node!({
        "title" => 12.
    });
    let n = n.get("title").map_err(|p| ("missing \"title\"", p))?;
    assert_eq!(
        Err(("title", 0)),
        n.as_str().map_err(|p| ("title", p))
    );
    assert_eq!(
        Option::<&str>::None,
        n.as_str().ok()
    );
    Ok(())
}

§Clone

Since the YAML data is wrapped by reference counter alloc::rc::Rc/alloc::sync::Arc, cloned nodes are still shared together, just like Python or JavaScript. Please see the Node::rc_ref/Node::yaml/Node::clone_yaml methods for details.

If you still want to copy data, use From/Into or serialize them to your custom type.

Implementations§

source§

impl<R: Repr> Node<R>

source

pub fn new(yaml: impl Into<Yaml<R>>, pos: u64, tag: impl ToString) -> Self

Create node from YAML data.

source

pub fn new_repr(yaml: R::Rc, pos: u64, tag: impl ToString) -> Self

Create from a representation.

source

pub fn set_yaml(&mut self, yaml: impl Into<Yaml<R>>)

Set from existing YAML data.

source

pub fn set_repr(&mut self, yaml: R::Rc)

Set from existing YAML representation.

source

pub fn pos(&self) -> u64

Document position.

source

pub fn tag(&self) -> &str

Tag. If the tag is not specified, returns a default tag from core schema.

Anchor has no tag.

source

pub fn yaml(&self) -> &Yaml<R>

YAML data.

source

pub fn clone_yaml(&self) -> R::Rc

Clone YAML repr.

source

pub fn rc_ref(&self) -> &R::Rc

As reference for the underlying reference counter.

use std::{rc::Rc, sync::Arc};
use yaml_peg::node;

let a_rc = node!("a");
let a_arc = node!(arc "a");
{
    let b_rc = a_rc.clone();
    let b_arc = a_arc.clone();
    assert_eq!(2, Rc::strong_count(b_rc.rc_ref()));
    assert_eq!(2, Arc::strong_count(b_arc.rc_ref()));
}
assert_eq!(1, Rc::strong_count(a_rc.rc_ref()));
assert_eq!(1, Arc::strong_count(a_arc.rc_ref()));
source

pub fn is_null(&self) -> bool

Check the value is null.

source

pub fn as_int(&self) -> Result<i64, u64>

Convert to integer.

use yaml_peg::node;

assert_eq!(60, node!(60).as_int().unwrap());
source

pub fn as_float(&self) -> Result<f64, u64>

Convert to float.

use yaml_peg::node;

assert_eq!(20.06, node!(20.06).as_float().unwrap());
source

pub fn as_number(&self) -> Result<f64, u64>

Convert to float for any number.

use yaml_peg::node;

assert_eq!(60., node!(60).as_number().unwrap());
assert_eq!(20.06, node!(20.06).as_number().unwrap());
source

pub fn as_bool(&self) -> Result<bool, u64>

Convert to boolean.

use yaml_peg::node;

assert!(node!(true).as_bool().unwrap());
source

pub fn as_str(&self) -> Result<&str, u64>

Convert to string pointer.

This method allows null, it represented as empty string. You can check them by str::is_empty.

use yaml_peg::node;

assert_eq!("abc", node!("abc").as_str().unwrap());
assert!(node!(()).as_str().unwrap().is_empty());
source

pub fn as_seq(&self) -> Result<Seq<R>, u64>

Convert to sequence.

use yaml_peg::node;

let n = node!(["55"]);
assert_eq!(node!("55"), n.as_seq().unwrap()[0]);
for n in n.as_seq().unwrap() {
    assert_eq!(node!("55"), n);
}
source

pub fn as_map(&self) -> Result<Map<R>, u64>

Convert to map.

use yaml_peg::node;

let n = node!({1 => 2});
assert_eq!(node!(2), n.as_map().unwrap()[&node!(1)]);
for (k, v) in n.as_map().unwrap() {
    assert_eq!(node!(1), k);
    assert_eq!(node!(2), v);
}
source

pub fn as_value(&self) -> Result<&str, u64>

Convert to string pointer for string, null, bool, int, and float type.

This method is useful when the option mixed with digit values.

use yaml_peg::node;

assert_eq!("abc", node!("abc").as_value().unwrap());
assert_eq!("123", node!(123).as_value().unwrap());
assert_eq!("12.04", node!(12.04).as_value().unwrap());
assert_eq!("true", node!(true).as_value().unwrap());
assert_eq!("false", node!(false).as_value().unwrap());
assert!(node!(()).as_value().unwrap().is_empty());
source

pub fn as_anchor<'a>(&'a self, anchors: &'a Anchors<R>) -> Result<&'a Self, u64>

Return the reference from anchors or self.

use yaml_peg::{node, parser::Anchors};

let mut anchors = Anchors::new();
anchors.insert("a".to_string(), node!(20));
assert_eq!(
    20,
    node!(*"a").as_anchor(&anchors).unwrap().as_int().unwrap()
);
source

pub fn get<Y: Into<Self>>(&self, key: Y) -> Result<&Self, u64>

Convert to map and try to get the value by key.

If any key is missing, return Err with node position.

use yaml_peg::node;

let n = node!({node!("a") => node!({node!("b") => node!(30.)})});
assert_eq!(&node!(30.), n.get("a")?.get("b")?);
source

pub fn get_default<'a, Y, Ret, F>( &'a self, key: Y, default: Ret, factory: F ) -> Result<Ret, u64>
where Y: Into<Self>, F: FnOnce(&'a Self) -> Result<Ret, u64>,

Same as Node::get but provide default value if the key is missing. For this method, a transform method as_* is required.

  • If the value exist, return the value.
  • If value is a wrong type, return Err with node position.
  • If the value is not exist, return the default value.
use yaml_peg::{node, Node};

let a = node!({node!("a") => node!({node!("b") => node!("c")})});
assert_eq!(
    "c",
    a.get("a")?.get_default("b", "d", Node::as_str)?
);
let b = node!({node!("a") => node!({})});
assert_eq!(
    "d",
    b.get("a")?.get_default("b", "d", Node::as_str)?
);
let c = node!({node!("a") => node!({node!("b") => node!(20.)})});
assert_eq!(
    Err(0),
    c.get("a")?.get_default("b", "d", Node::as_str)
);
use yaml_peg::{node, Node};

let n = node!({node!("a") => node!([node!(1), node!(2), node!(3)])});
let a = n.get_default("c", vec![], Node::as_seq)?;
assert_eq!(a, vec![]);
source

pub fn get_ind(&self, ind: Ind) -> Result<&Self, u64>

Get node through index indicator. Only suitable for sequence.

use yaml_peg::{node, Ind};

let n = node!([node!("a"), node!("b"), node!("c")]);
assert_eq!(&node!("b"), n.get_ind(Ind(1))?);

Trait Implementations§

source§

impl<R: Repr> Clone for Node<R>

source§

fn clone(&self) -> Self

Returns a copy 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<R: Repr> Debug for Node<R>

source§

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

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

impl<'a, R: Repr> Deserialize<'a> for Node<R>

Available on crate feature serde only.
source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'a>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl<'a, R: Repr> Deserializer<'a> for Node<R>

Available on crate feature serde only.
§

type Error = SerdeError

The error type that can be returned if some error occurs during deserialization.
source§

fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Require the Deserializer to figure out how to drive the visitor based on what data type is in the input. Read more
source§

fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a bool value.
source§

fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting an i8 value.
source§

fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting an i16 value.
source§

fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting an i32 value.
source§

fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting an i64 value.
source§

fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a u8 value.
source§

fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a u16 value.
source§

fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a u32 value.
source§

fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a u64 value.
source§

fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a f32 value.
source§

fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a f64 value.
source§

fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a string value and does not benefit from taking ownership of buffered data owned by the Deserializer. Read more
source§

fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a string value and would benefit from taking ownership of buffered data owned by the Deserializer. Read more
source§

fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a char value.
source§

fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a sequence of values.
source§

fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a map of key-value pairs.
source§

fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting the name of a struct field or the discriminant of an enum variant.
source§

fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting an i128 value. Read more
source§

fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting an u128 value. Read more
source§

fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a byte array and does not benefit from taking ownership of buffered data owned by the Deserializer. Read more
source§

fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a byte array and would benefit from taking ownership of buffered data owned by the Deserializer. Read more
source§

fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting an optional value. Read more
source§

fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a unit value.
source§

fn deserialize_unit_struct<V>( self, _name: &'static str, visitor: V ) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a unit struct with a particular name.
source§

fn deserialize_newtype_struct<V>( self, _name: &'static str, visitor: V ) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a newtype struct with a particular name.
source§

fn deserialize_tuple<V>( self, _len: usize, visitor: V ) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a sequence of values and knows how many values there are without looking at the serialized data.
source§

fn deserialize_tuple_struct<V>( self, _name: &'static str, _len: usize, visitor: V ) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a tuple struct with a particular name and number of fields.
source§

fn deserialize_struct<V>( self, _name: &'static str, _fields: &'static [&'static str], visitor: V ) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting a struct with a particular name and fields.
source§

fn deserialize_enum<V>( self, _name: &'static str, _variants: &'static [&'static str], visitor: V ) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type is expecting an enum value with a particular name and possible variants.
source§

fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>,

Hint that the Deserialize type needs to deserialize a value whose type doesn’t matter because it is ignored. Read more
source§

fn is_human_readable(&self) -> bool

Determine whether Deserialize implementations should expect to deserialize their human-readable form. Read more
source§

impl<R, Y> From<Y> for Node<R>
where R: Repr, Y: Into<Yaml<R>>,

source§

fn from(yaml: Y) -> Self

Converts to this type from the input type.
source§

impl<R: Repr> FromIterator<(Node<R>, Node<R>)> for Node<R>

source§

fn from_iter<T: IntoIterator<Item = (Self, Self)>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<R: Repr> FromIterator<Node<R>> for Node<R>

source§

fn from_iter<T: IntoIterator<Item = Self>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<R: Repr> FromIterator<Node<R>> for Yaml<R>

source§

fn from_iter<T: IntoIterator<Item = Node<R>>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<R: Repr> Hash for Node<R>

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<R, I> Index<I> for Node<R>
where R: Repr, I: Into<Self>,

§

type Output = Node<R>

The returned type after indexing.
source§

fn index(&self, index: I) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
source§

impl<R: Repr> Index<Ind> for Node<R>

§

type Output = Node<R>

The returned type after indexing.
source§

fn index(&self, index: Ind) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
source§

impl<R: Repr> PartialEq for Node<R>

source§

fn eq(&self, rhs: &Self) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<R: Repr> Serialize for Node<R>

Available on crate feature serde only.
source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl<R: Repr> Eq for Node<R>

Auto Trait Implementations§

§

impl<R> Freeze for Node<R>
where <R as Repr>::Rc: Freeze,

§

impl<R> RefUnwindSafe for Node<R>
where <R as Repr>::Rc: RefUnwindSafe, R: RefUnwindSafe,

§

impl<R> Send for Node<R>
where <R as Repr>::Rc: Send, R: Send,

§

impl<R> Sync for Node<R>
where <R as Repr>::Rc: Sync, R: Sync,

§

impl<R> Unpin for Node<R>
where <R as Repr>::Rc: Unpin, R: Unpin,

§

impl<R> UnwindSafe for Node<R>
where <R as Repr>::Rc: UnwindSafe, R: UnwindSafe,

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> CallHasher for T
where T: Hash + ?Sized,

source§

default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64
where H: Hash + ?Sized, B: BuildHasher,

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,

§

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, U> TryFrom<U> for T
where U: Into<T>,

§

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

§

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

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,