Trait relay_protocol::Getter
source · pub trait Getter {
// Required method
fn get_value(&self, path: &str) -> Option<Val<'_>>;
// Provided method
fn get_iter(&self, _path: &str) -> Option<GetterIter<'_>> { ... }
}
Expand description
A type that supports field access by paths.
This is the runtime version of get_value!
and additionally supports
indexing into Value
. For typed access to static paths, use the macros instead.
§Syntax
The path identifies a value within the structure. A path consists of components separated by
.
, where each of the components is the name of a field to access. Every path starts with the
name of the root level component, which must match for this type.
Special characters are escaped with a \
. The two special characters are:
\.
matches a literal dot in a path component.\\
matches a literal backslash in a path component.
§Implementation
Implementation of the Getter
trait should follow a set of conventions to ensure the paths
align with expectations based on the layout of the implementing type:
- The name of the root component should be the lowercased version of the name of the
structure. For example, a structure called
Event
would useevent
as the root component. - All fields of the structure are referenced by the name of the field in the containing
structure. This also applies to mappings such as
HashMap
, where the key should be used as field name. For recursive access, this translates transitively through the hierarchy. - Newtypes and structured enumerations do not show up in paths. This especially applies to
Option
, which opaque in the path:None
is simply propagated up.
In the future, a derive for the Getter
trait will be added to simplify implementing the
Getter
trait.
§Example
use relay_protocol::{Getter, Val};
struct Root {
a: u64,
b: Nested,
}
struct Nested {
c: u64,
}
impl Getter for Root {
fn get_value(&self, path: &str) -> Option<Val<'_>> {
match path.strip_prefix("root.")? {
"a" => Some(self.a.into()),
"b.c" => Some(self.b.c.into()),
_ => None,
}
}
}
let root = Root {
a: 1,
b: Nested {
c: 2,
}
};
assert_eq!(root.get_value("root.a"), Some(Val::U64(1)));
assert_eq!(root.get_value("root.b.c"), Some(Val::U64(2)));
assert_eq!(root.get_value("root.d"), None);
Required Methods§
Provided Methods§
sourcefn get_iter(&self, _path: &str) -> Option<GetterIter<'_>>
fn get_iter(&self, _path: &str) -> Option<GetterIter<'_>>
Returns an iterator over the array pointed to by a path
.
If the path does not exist or is not an array, this returns None
. Note that get_value
may not return a value for paths that expose an iterator.