Struct Schema

Source
pub struct Schema {
    pub meta: Option<Meta>,
    pub internal: Option<Internal>,
}
Expand description

Type of a node: leaf or internal

Fields§

§meta: Option<Meta>

Inner metadata

§internal: Option<Internal>

Internal schemata

Implementations§

Source§

impl Schema

Source

pub const LEAF: Self

A leaf without metadata

Source

pub const fn numbered(numbered: &'static [Numbered]) -> Self

Create a new internal node schema with named children and without innner metadata

Source

pub const fn named(named: &'static [Named]) -> Self

Create a new internal node schema with numbered children and without innner metadata

Source

pub const fn homogeneous(homogeneous: Homogeneous) -> Self

Create a new internal node schema with homogenous children and without innner metadata

Source

pub const fn is_leaf(&self) -> bool

Whether this node is a leaf

Source

pub const fn len(&self) -> usize

Number of child nodes

Source

pub const fn is_empty(&self) -> bool

Source

pub fn next(&self, keys: impl Keys) -> Result<usize, KeyError>

Look up the next item from keys and return a child index

§Panics

On a leaf Schema.

Source

pub fn descend<'a, T, E>( &'a self, keys: impl Keys, func: impl FnMut(&'a Self, Option<(usize, &'a Internal)>) -> Result<T, E>, ) -> Result<T, DescendError<E>>

Traverse from the root to a leaf and call a function for each node.

If a leaf is found early (keys being longer than required) Err(KeyError::TooLong) is returned. If keys is exhausted before reaching a leaf node, Err(KeyError::TooShort) is returned.

use miniconf::{IntoKeys, TreeSchema};
#[derive(TreeSchema)]
struct S {
    foo: u32,
    bar: [u16; 2],
};
let mut ret = [
    (S::SCHEMA, Some(1usize)),
    (<[u16; 2]>::SCHEMA, Some(0)),
    (u16::SCHEMA, None),
].into_iter();
let func = |schema, idx_internal: Option<_>| {
    assert_eq!(ret.next().unwrap(), (schema, idx_internal.map(|(idx, _)| idx)));
    Ok::<_, Infallible>(())
};
assert_eq!(S::SCHEMA.descend(["bar", "0"].into_keys(), func), Ok(()));
§Args
  • keys: A Keys identifying the node.
  • func: A FnMut to be called for each (internal and leaf) node on the path. Its arguments are outer schema and optionally the inner index and internal schema. Returning Err(E) aborts the traversal. Returning Ok(T) continues the downward traversal.
§Returns

The leaf func call return value.

Source

pub fn get_meta( &self, keys: impl IntoKeys, ) -> Result<(Option<&Option<Meta>>, &Option<Meta>), KeyError>

Look up outer and inner metadata given keys.

Source

pub fn get(&self, keys: impl IntoKeys) -> Result<&Self, KeyError>

Get the schema of the node identified by keys.

Source

pub fn transcode<N: Transcode + Default>( &self, keys: impl IntoKeys, ) -> Result<N, DescendError<N::Error>>

Transcode keys to a new keys type representation

The keys can be

  • too short: the internal node is returned
  • matched length: the leaf node is returned
  • too long: Err(TooLong(depth)) is returned

In order to not require N: Default, use Transcode::transcode on an existing &mut N.

use miniconf::{Indices, JsonPath, Packed, Track, Short, Path, TreeSchema};
#[derive(TreeSchema)]
struct S {
    foo: u32,
    bar: [u16; 5],
};

let idx = [1, 1];
let sch = S::SCHEMA;

let path = sch.transcode::<Path<String, '/'>>(idx).unwrap();
assert_eq!(path.0.as_str(), "/bar/1");
let path = sch.transcode::<JsonPath<String>>(idx).unwrap();
assert_eq!(path.0.as_str(), ".bar[1]");
let indices = sch.transcode::<Indices<[usize; 2]>>(&path).unwrap();
assert_eq!(indices.as_ref(), idx);
let indices = sch.transcode::<Indices<[usize; 2]>>(["bar", "1"]).unwrap();
assert_eq!(indices.as_ref(), [1, 1]);
let packed = sch.transcode::<Packed>(["bar", "4"]).unwrap();
assert_eq!(packed.into_lsb().get(), 0b1_1_100);
let path = sch.transcode::<Path<String, '/'>>(packed).unwrap();
assert_eq!(path.0.as_str(), "/bar/4");
let node = sch.transcode::<Short<Track<()>>>(&path).unwrap();
assert_eq!((node.leaf(), node.inner().depth()), (true, 2));
§Args
  • keys: IntoKeys to identify the node.
§Returns

Transcoded target and node information on success

Source

pub const fn shape(&self) -> Shape

The Shape of the schema

Source

pub const fn nodes<N: Transcode + Default, const D: usize>( &'static self, ) -> ExactSize<NodeIter<N, D>>

Return an iterator over nodes of a given type

This is a walk of all leaf nodes. The iterator will walk all paths, including those that may be absent at runtime (see crate::TreeSchema). The iterator has an exact and trusted size_hint(). The D const generic of NodeIter is the maximum key depth.

use miniconf::{Indices, JsonPath, Short, Track, Packed, Path, TreeSchema};
#[derive(TreeSchema)]
struct S {
    foo: u32,
    bar: [u16; 2],
};
const MAX_DEPTH: usize = S::SCHEMA.shape().max_depth;
assert_eq!(MAX_DEPTH, 2);

let paths: Vec<_> = S::SCHEMA.nodes::<Path<String, '/'>, MAX_DEPTH>()
    .map(|p| p.unwrap().into_inner())
    .collect();
assert_eq!(paths, ["/foo", "/bar/0", "/bar/1"]);

let paths: Vec<_> = S::SCHEMA.nodes::<JsonPath<String>, MAX_DEPTH>()
    .map(|p| p.unwrap().into_inner())
    .collect();
assert_eq!(paths, [".foo", ".bar[0]", ".bar[1]"]);

let indices: Vec<_> = S::SCHEMA.nodes::<Indices<[_; 2]>, MAX_DEPTH>()
    .map(|p| p.unwrap().into_inner())
    .collect();
assert_eq!(indices, [([0, 0], 1), ([1, 0], 2), ([1, 1], 2)]);

let packed: Vec<_> = S::SCHEMA.nodes::<Packed, MAX_DEPTH>()
    .map(|p| p.unwrap().into_lsb().get())
    .collect();
assert_eq!(packed, [0b1_0, 0b1_1_0, 0b1_1_1]);

let nodes: Vec<_> = S::SCHEMA.nodes::<Short<Track<()>>, MAX_DEPTH>()
    .map(|p| {
        let p = p.unwrap();
        (p.leaf(), p.inner().depth())
    })
    .collect();
assert_eq!(nodes, [(true, 1), (true, 2), (true, 2)]);

Trait Implementations§

Source§

impl Clone for Schema

Source§

fn clone(&self) -> Schema

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 Schema

Source§

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

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

impl Default for Schema

Source§

fn default() -> Schema

Returns the “default value” for a type. Read more
Source§

impl Hash for Schema

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 Ord for Schema

Source§

fn cmp(&self, other: &Schema) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Schema

Source§

fn eq(&self, other: &Schema) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Schema

Source§

fn partial_cmp(&self, other: &Schema) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for Schema

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 Eq for Schema

Source§

impl StructuralPartialEq for Schema

Auto Trait Implementations§

§

impl Freeze for Schema

§

impl RefUnwindSafe for Schema

§

impl Send for Schema

§

impl Sync for Schema

§

impl Unpin for Schema

§

impl UnwindSafe for Schema

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