Struct regorust::Node

source ·
pub struct Node {
    pub size: usize,
    pub kind: NodeKind,
    /* private fields */
}
Expand description

Interface for Rego Node objects.

Rego Nodes are the basic building blocks of a Rego result. They exist in a tree structure. Each node has a kind, which is one of the variants of NodeKind. Each node also has zero or more children, which are also nodes.

§Examples

use regorust::*;
let rego = Interpreter::new();
match rego.query(r#"x={"a": 10, "b": "20", "c": [30.0, 60], "d": true, "e": null}"#) {
  Ok(result) => {
    let x = result.binding("x").expect("cannot get x");
    println!("x = {}", x.json().unwrap());
    if let NodeValue::Int(a) = x
        .lookup("a")
        .unwrap()
        .value()
        .unwrap()
    {
      println!("x['a'] = {}", a);
    }

    if let NodeValue::String(b) = x
       .lookup("b")
       .unwrap()
       .value()
       .unwrap()
    {
      println!("x['b'] = {}", b);
    }

    let c = x.lookup("c").unwrap();
    if let NodeValue::Float(c0) = c.index(0)
      .unwrap()
      .value()
      .unwrap()
    {
      println!("x['c'][0] = {}", c0);
    }

    if let NodeValue::Int(c1) = c.index(1)
      .unwrap()
      .value()
      .unwrap()
    {
      println!("x['c'][1] = {}", c1);
    }

    if let NodeValue::Bool(d) = x
      .lookup("d")
      .unwrap()
      .value()
      .unwrap()
    {
      println!("x['d'] = {}", d);
    }

    if let NodeValue::Null = x
      .lookup("e")
      .unwrap()
      .value()
      .unwrap()
    {
      println!("x['e'] = null");
    }
  }
  Err(e) => {
    panic!("error: {}", e);
  }
}

Fields§

§size: usize

The number of children of this node.

§kind: NodeKind

The kind of this node.

Implementations§

source§

impl Node

source

pub fn kind_name(&self) -> &str

Returns a human-readable string representation of the node kind.

source

pub fn value(&self) -> Option<NodeValue>

Returns the value of the node.

If the node has a singular value (i.e is a Scalar or a Term containing a scalar) then this will return that value. Otherwise it will return [Option::None].

§Examples
let x = result.binding("x").expect("cannot get x");
if let NodeValue::Int(x) = result
  .binding("x")
  .unwrap()
  .value()
  .unwrap()
{
  println!("x = {}", x);
}

if let NodeValue::String(y) = result
  .binding("y")
  .unwrap()
  .value()
  .unwrap()
{
  println!("y = {}", y);
}

if let NodeValue::Bool(z) = result
  .binding("z")
  .unwrap()
  .value()
  .unwrap()
{
  println!("z = {}", z);
}
source

pub fn json(&self) -> Result<String, &str>

Returns the node as a JSON string.

The result of this function will a valid JSON representation of the node. If the node cannot be transformed into JSON this will return an error.

§Examples
let x = result.binding("x").expect("cannot get x");
println!("x = {}", x.json().unwrap());
let y = result.binding("y").expect("cannot get y");
println!("y = {}", y.json().unwrap());
let z = result.binding("z").expect("cannot get z");
println!("z = {}", z.json().unwrap());
source

pub fn size(&self) -> usize

Returns the number of child nodes.

source

pub fn lookup(&self, key: &str) -> Result<&Node, &str>

Looks up a key in an object or a set.

The key argument should be a JSON representation of the key, and can be both simple types (e.g. strings, ints, bools) or complex types (e.g. objects, arrays). The returned result will be value node of the object item with a matching key, or conversely the node with the matching value in the set. If no matching value is found, or if the node is not an object or a set, an error will be returned.

§Examples
let output = rego.query(r#"x={"a": 1}; y={["foo", false], 5}; z=[1, "bar"]"#).unwrap();
let x = output.binding("x").unwrap();
println!(r#"x["a"] = {}"#, x.lookup("a").unwrap().json().unwrap());
let y = output.binding("y").unwrap();
println!(r#"y[["foo", false]] = {}"#, y.lookup(r#"["foo", false]"#).unwrap().json().unwrap());
let z = output.binding("z").unwrap();
match z.lookup("bar") {
  Ok(_) => panic!("bar should not be found"),
  Err(err) => println!("{}", err)
}
source

pub fn index(&self, index: usize) -> Result<&Node, &str>

Looks up an index in an array.

If the index falls outside the range of the array, the result will be an error. Similarly, this method will only work if the Node is of NodeKind::Array.

§Examples
let output = rego.query(r#"x=[1, 2, 3]; y={"0": "a"}"#).unwrap();
let x = output.binding("x").unwrap();
println!(r#"x[0] = {}"#, x.index(0).unwrap().json().unwrap());
let y = output.binding("y").unwrap();
match y.index(0) {
  Ok(_) => panic!("0 should not be found"),
  Err(err) => println!("{}", err)
}
source

pub fn at(&self, index: usize) -> Result<&Node, &str>

Returns the raw child node at a particular index.

If the index falls outside the range of the array, the result will be an error.

source

pub fn iter(&self) -> Iter<'_, Node>

Returns an iterator over the child nodes.

Trait Implementations§

source§

impl Debug for Node

source§

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

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

impl Display for Node

source§

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

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

impl Index<usize> for Node

§

type Output = Node

The returned type after indexing.
source§

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

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

impl PartialEq for Node

source§

fn eq(&self, other: &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.

Auto Trait Implementations§

§

impl Freeze for Node

§

impl RefUnwindSafe for Node

§

impl !Send for Node

§

impl !Sync for Node

§

impl Unpin for Node

§

impl UnwindSafe for Node

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> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> ToString for T
where T: Display + ?Sized,

source§

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

§

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

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more