A rust library that provides pseudo-reflection for structs and enums

Overview

Treeflection Build Status Crates.io Docs

treeflection_derive Crates.io Docs

Treeflection runs a command stored as a string on a tree of structs, collections and primitive types.

Commands

A command to set an int in a Vec in a struct in another struct in a Hashmap to the value 50 looks like: someHashMap["key"].someChild.anotherChild[0]:set 50

For the full syntax take a look at the Command Manual

Usage

The Node trait must be implemented for every type in the tree. Then a new NodeRunner is created using the command string and passed to the node_step method of the root node. The NodeRunner is then passed to the children specified in the command and then runs the command on the final specified child. Use the treeflection_derive crate to #[Derive(Node)] your own structs or write your own handlers.

Vec example

extern crate treeflection;
use treeflection::{NodeRunner, Node};

pub fn main() {
    let mut test_vec = vec!(0, 413, 358, 42);

    let command = "[1]:get";
    let result = test_vec.node_step(NodeRunner::new(command).unwrap());
    assert_eq!(result, "413");

    let command = "[1]:set 1111";
    let result = test_vec.node_step(NodeRunner::new(command).unwrap());
    assert_eq!(result, "");

    let command = "[1]:get";
    let result = test_vec.node_step(NodeRunner::new(command).unwrap());
    assert_eq!(result, "1111");
}

Custom struct example

Use the treeflection_derive crate to #[Derive(Node)] your own structs or write your own handlers. Your structs also need to impl the traits Serialize, Deserialize, Default and Clone as well as extern crate serde_json. This is because serde_json is used to get/set entire structs.

Currently use treeflection::{NodeRunner, Node, NodeToken}; must be included so the macro can access these types.

extern crate treeflection;
#[macro_use] extern crate treeflection_derive;
#[macro_use] extern crate serde_derive;
extern crate serde_json;

use treeflection::{NodeRunner, Node, NodeToken};

#[derive(Node, Serialize, Deserialize, Default, Clone)]
struct SolarSystem {
    pub mercury:  Planet,
    pub earth:    Planet,
    pub mars:     Planet,
        planet_x: Planet,
}

impl SolarSystem {
    pub fn new() -> SolarSystem {
        SolarSystem {
            mercury:  Planet { radius: 2440.0 },
            earth:    Planet { radius: 6371.0 },
            mars:     Planet { radius: 3390.0 },
            planet_x: Planet { radius: 1337.0 },
        }
    }
}

#[NodeActions(
    // we want the function circumference to be accessible via treeflection by the same name
    NodeAction(function="circumference", return_string),

    // we want the function explode_internal_naming_scheme to be accessible via treeflection
    // by the name explode and we want to ignore its return value so that it will compile despite not returning a String
    NodeAction(action="explode", function="explode_internal_naming_scheme"),
)]
#[derive(Node, Serialize, Deserialize, Default, Clone)]
struct Planet {
    pub radius: f32
}

impl Planet {
    pub fn circumference(&self) -> String {
        (self.radius * 2.0 * std::f32::consts::PI).to_string()
    }

    pub fn explode_internal_naming_scheme(&mut self) {
        self.radius = 0.0;
    }
}


pub fn main() {
    let mut ss = SolarSystem::new();

    // serialize the whole struct into json
    let command = ":get";
    let result = ss.node_step(NodeRunner::new(command).unwrap());
    assert_eq!(result,
r#"{
  "mercury": {
    "radius": 2440.0
  },
  "earth": {
    "radius": 6371.0
  },
  "mars": {
    "radius": 3390.0
  },
  "planet_x": {
    "radius": 1337.0
  }
}"#);

    // access properties
    let command = "earth.radius:get";
    let result = ss.node_step(NodeRunner::new(command).unwrap());
    assert_eq!(result, "6371");

    // call methods on the struct
    let command = "earth:circumference";
    let result = ss.node_step(NodeRunner::new(command).unwrap());
    assert_eq!(result, "40030.176");

    let command = "earth:explode";
    let result = ss.node_step(NodeRunner::new(command).unwrap());
    assert_eq!(result, "");
    assert_eq!(ss.earth.radius, 0.0);

    // private properties are not accessible via treeflection
    let command = "planet_x:get";
    let result = ss.node_step(NodeRunner::new(command).unwrap());
    assert_eq!(result, "SolarSystem does not have a property 'planet_x'");
}

Contributing

This library is designed around the specific needs of Canon Collision. Pull requests are welcome but if the changes go against the needs of Canon Collision you will be stuck with your own fork. :)

You might also like...
A tool and library to losslessly join multiple .mp4 files shot with same camera and settings

mp4-merge A tool and library to losslessly join multiple .mp4 files shot with same camera and settings. This is useful to merge multiple files that ar

Rust library for hardware accelerated drawing of 2D shapes, images, and text, with an easy to use API.
Rust library for hardware accelerated drawing of 2D shapes, images, and text, with an easy to use API.

Speedy2D Hardware-accelerated drawing of shapes, images, and text, with an easy to use API. Speedy2D aims to be: The simplest Rust API for creating a

Comprehensive DSP graph and synthesis library for developing a modular synthesizer in Rust, such as HexoSynth.

HexoDSP - Comprehensive DSP graph and synthesis library for developing a modular synthesizer in Rust, such as HexoSynth. This project contains the com

A library for transcoding between bytes in Astro Notation Format and Native Rust data types.

Rust Astro Notation A library for transcoding between hexadecimal strings in Astro Notation Format and Native Rust data types. Usage In your Cargo.tom

A simple thread schedule and priority library for rust

thread-priority A simple library to control thread schedule policies and thread priority. If your operating system isn't yet supported, please, create

Library and proc macro to analyze memory usage of data structures in rust.
Library and proc macro to analyze memory usage of data structures in rust.

Allocative: memory profiler for Rust This crate implements a lightweight memory profiler which allows object traversal and memory size introspection.

An actors library for Rust and Tokio designed to work with async / await message handlers out of the box.

Akt An actors framework for Rust and Tokio. It is heavily inspired by Actix and right now it has very similar look and feel. The main difference is th

Rust library for scheduling, managing resources, and running DAGs 🌙

🌙 moongraph 📈 moongraph is a Rust library for scheduling, managing resources, and running directed acyclic graphs. In moongraph, graph nodes are nor

Rust library for compiling and running other programs.

Exers 💻 Exers is a rust library for compiling and running code in different languages and runtimes. Usage example fn main() { // Imports...

Comments
  • TODO

    TODO

    • [x] Use serde for setting/getting containers
    • [x] Index notation/IndexProperty for tuples
    • [x] impl more vec like functions onto ContextVec
    • [x] Add [?] syntax to command parser
    • [x] Index notation/IndexProperty for enum tuples
    • [x] Dot notation/ChainProperty for enum structs
    • [x] dont explode everytime something goes slightly wrong
    opened by rukai 1
  • improve or replace get_field_type()

    improve or replace get_field_type()

    I feel like there should be a better way to do get_field_type() in treeflection_derive. However if there isnt then we need to manually complete get_field_type() ourselves.

    opened by rukai 0
  • Automatically include `use treeflection::{Node, NodeRunner, NodeToken};` on a #[derive(Node)]

    Automatically include `use treeflection::{Node, NodeRunner, NodeToken};` on a #[derive(Node)]

    Automatically include use treeflection::{Node, NodeRunner, NodeToken}; on a #[derive(Node)]

    I remember looking into this and not finding a solution, but I dont remember what the issue was.

    opened by rukai 0
Owner
Lucas Kent
Building experimental platform fighter tools and games with rust
Lucas Kent
Static-checked parsing of regexes into structs

Statically-checked regex parsing into structs. This avoids common regex pitfalls like Off by one capture indexes Trying to get nonexistent captures De

Andrew Baxter 4 Dec 18, 2022
Rust library provides a standalone implementation of the ROS (Robot Operating System) core

ROS-core implementation in Rust This Rust library provides a standalone implementation of the ROS (Robot Operating System) core. It allows you to run

Patrick Wieschollek 3 Apr 26, 2023
An API for getting questions from http://either.io implemented fully in Rust, using reqwest and some regex magic. Provides asynchronous and blocking clients respectively.

eithers_rust An API for getting questions from http://either.io implemented fully in Rust, using reqwest and some regex magic. Provides asynchronous a

null 2 Oct 24, 2021
This blog provides detailed status updates and useful information about Theseus OS and its development

The Theseus OS Blog This blog provides detailed status updates and useful information about Theseus OS and its development. Attribution This blog was

Theseus OS 1 Apr 14, 2022
alto provides idiomatic Rust bindings for OpenAL 1.1 and extensions (including EFX).

alto alto provides idiomatic Rust bindings for OpenAL 1.1 and extensions (including EFX). WARNING Because Alto interacts with global C state via dynam

null 80 Aug 7, 2022
A radix tree implementation for router, and provides CRUD operations.

radixtree A radix tree implementation for router, and provides CRUD operations. Radixtree is part of treemux, on top of which updates and removes are

Zhenwei Guo 2 Dec 19, 2022
This is the Rust course used by the Android team at Google. It provides you the material to quickly teach Rust to everyone.

Comprehensive Rust ?? This repository has the source code for Comprehensive Rust ?? , a four day Rust course developed by the Android team. The course

Google 5.2k Jan 3, 2023
Crabzilla provides a simple interface for running JavaScript modules alongside Rust code.

Crabzilla Crabzilla provides a simple interface for running JavaScript modules alongside Rust code. Example use crabzilla::*; use std::io::stdin; #[i

Andy 14 Feb 19, 2022
Rust 核心库和标准库的源码级中文翻译,可作为 IDE 工具的智能提示 (Rust core library and standard library translation. can be used as IntelliSense for IDE tools)

Rust 标准库中文版 这是翻译 Rust 库 的地方, 相关源代码来自于 https://github.com/rust-lang/rust。 如果您不会说英语,那么拥有使用中文的文档至关重要,即使您会说英语,使用母语也仍然能让您感到愉快。Rust 标准库是高质量的,不管是新手还是老手,都可以从中

wtklbm 493 Jan 4, 2023
Omeglib, a portmanteau of "omegle" and "library", is a crate for interacting with omegle, simply and asynchronously

Omeglib, a portmanteau of "omegle" and "library", is a crate for interacting with omegle, simply and asynchronously. It is intended to suit one's every requirement regarding chat on omegle.

null 1 May 25, 2022