Embedded_Commands_rs
Embedded_commands_rs is a simple library for adding commands to rust applications.
This library contains two distinct types, the Interpreter and Token types.
The interpreter type represents an instance of a command interpreter and has the following methods:
- new() // generates a new interpreter.
- register(fn( &mut T, &[Token] )) // registers a new command function which takes a mutable reference to T.
- interpret(&mut T, &str) // runs the commands sequentially based on the code written.
The token Type represents an enum which contains any of 4 types:
- an i64
- a f64
- a bool
- a string
Command format example
command1(1,2,3) // this command takes three integers.
command2(1,1.15,true,"abc") // this command takes 4 arguments and expects them to be of the types Token::Int, Token::Float, Token::Str and Token::Bool.
Code example for using this in a console app
use std::io::{self, Read};
use embedded_commands_rs::{Interpreter, Token};
#[derive(Debug)]
struct State {
counter: i64,
}
fn main() {
let mut state = State { counter: 0 };
let mut interp = Interpreter::new();
interp.register("print", print);
interp.register("increment", counter_inc);
interp.register("decrement", counter_dec);
interp.register("reveal_counter", counter_show);
let mut script = String::new();
io::stdin().read_to_string(&mut script).expect("Failed to read input");
interp.interpret(&mut state, &script);
}
fn print(_state: &mut State, args: &[Token]) {
if let Some(Token::Str(content)) = args.get(0) {
println!("{}", content);
} else {
eprintln!("print expects a string argument in parentheses, e.g., print(\"Hello\")");
}
}
fn counter_inc(state: &mut State, _args: &[Token]) {
state.counter += 1;
}
fn counter_dec(state: &mut State, _args: &[Token]) {
state.counter -= 1;
}
fn counter_show(state: &mut State, _args: &[Token]) {
println!("counter.value = {}", state.counter);
}