Skip to content

Instantly share code, notes, and snippets.

@viperscape
Last active December 21, 2015 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viperscape/7462f9156ea63682e433 to your computer and use it in GitHub Desktop.
Save viperscape/7462f9156ea63682e433 to your computer and use it in GitHub Desktop.
toml parser for key bindings, example
/// toml parser and config for keybindings, etc.
use toml::{Parser,Value};
use std::fs::File;
use std::io::Read;
use glium::glutin::VirtualKeyCode;
use std::collections::{HashMap,BTreeMap};
#[derive(Debug)]
pub struct Bindings(HashMap<String,VirtualKeyCode>);
pub type Config = BTreeMap<String,Value>;
impl Bindings {
fn load (path: &str) -> Config {
let mut input = String::new();
if let Some(mut file) = File::open(path).ok() {
file.read_to_string(&mut input);
}
Parser::new(&input).parse().unwrap_or(BTreeMap::new())
}
pub fn default() -> Bindings {
let r = Bindings::load("assets/config.toml");
let mut bindings = HashMap::new();
{
if let Some(table) = r.get("keys") {
match table {
&Value::Table(ref keys) => {
for key in keys.iter() {
let vkey = {
match key.0 as &str {
"A" => VirtualKeyCode::A,
"S" => VirtualKeyCode::S,
"D" => VirtualKeyCode::D,
"W" => VirtualKeyCode::W,
_ => VirtualKeyCode::F12,
}
};
if let Some(action) = Actions::parse_string(key.1) {
bindings.insert(action,vkey);
}
}
}
_ => {},
}
}
}
Bindings(bindings)
}
pub fn get(&self, action: &str) -> Option<&VirtualKeyCode> {
self.0.get(action)
}
}
struct Actions;
impl Actions {
fn parse_string(action: &Value) -> Option<String> {
match action {
&Value::String(ref action) => Some(action.clone()),
_ => None,
}
}
}
[keys]
A = "move_left"
D = "move_right"
W = "move_up"
S = "move_down"
fn main() {
let bindings = Bindings::default();
println!("{:?}",bindings);
if let Some(key) = bindings.get("move_left") {
println!("{:?}",key);
}
}
// prints out ->
// Bindings({"move_up": W, "move_left": A, "move_right": D, "move_down": S})
// A
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment