Trait tau_engine::Object

source ·
pub trait Object {
    // Required methods
    fn get(&self, key: &str) -> Option<Value<'_>>;
    fn keys(&self) -> Vec<Cow<'_, str>>;
    fn len(&self) -> usize;

    // Provided method
    fn find(&self, key: &str) -> Option<Value<'_>> { ... }
}
Expand description

A data type that can be represented as an Object.

This allows more complex object-like data types to be represented in a generic way for use as a Value.

Implementations

As long as the data type is considered object-like then Object can be implemented on that type. Below is a contrived example: j

use std::borrow::Cow;

use tau_engine::{Object, Value};

struct Foo {
    pub bar: String,
    pub baz: String,
}

impl Object for Foo {
    fn get(&self, key: &str) -> Option<Value<'_>> {
        match key {
            "bar" => Some(Value::String(Cow::Borrowed(&self.bar))),
            "baz" => Some(Value::String(Cow::Borrowed(&self.baz))),
            _ => None,
        }
    }

    fn keys(&self) -> Vec<Cow<'_, str>> {
        ["bar", "baz"].iter().map(|s| Cow::Borrowed(*s)).collect()
    }

    fn len(&self) -> usize {
        2
    }
}

Find

The find function allows for nested access from an Object. A default implementation is provided by the trait which assumes the key will split on the . character. This can be overriden if required. Below is an example of how find works for a complex data structure.

use tau_engine::Object;

struct Foo {
    pub bar: String,
}
struct Baz {
    pub foo: Foo,
}
let complex = Baz {
    foo: Foo {
        bar: "foobar".to_owned(),
    }
};

let value = complex.find("foo.bar").unwrap();

assert_eq!(value.as_str(), Some("foobar"));

Required Methods§

source

fn get(&self, key: &str) -> Option<Value<'_>>

Get the Value corresponding to the key.

source

fn keys(&self) -> Vec<Cow<'_, str>>

Returns the keys for the object.

source

fn len(&self) -> usize

Returns the number of elements in the object.

Provided Methods§

source

fn find(&self, key: &str) -> Option<Value<'_>>

Looks for a Value by key and returns it if found. The provided implementation will split the key on . to handle nesting.

Trait Implementations§

source§

impl Document for &dyn Object

source§

fn find(&self, key: &str) -> Option<Value<'_>>

Looks for a Value by key and returns it if found.

Implementations on Foreign Types§

source§

impl Object for Mapping

source§

fn get(&self, key: &str) -> Option<Value<'_>>

source§

fn keys(&self) -> Vec<Cow<'_, str>>

source§

fn len(&self) -> usize

source§

impl Object for Map<String, Json>

source§

fn get(&self, key: &str) -> Option<Value<'_>>

source§

fn keys(&self) -> Vec<Cow<'_, str>>

source§

fn len(&self) -> usize

source§

impl<V, S> Object for HashMap<String, V, S>where V: AsValue, S: BuildHasher,

source§

fn get(&self, key: &str) -> Option<Value<'_>>

source§

fn keys(&self) -> Vec<Cow<'_, str>>

source§

fn len(&self) -> usize

Implementors§