Last active
December 21, 2015 19:05
-
-
Save viperscape/7462f9156ea63682e433 to your computer and use it in GitHub Desktop.
toml parser for key bindings, example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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, | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[keys] | |
A = "move_left" | |
D = "move_right" | |
W = "move_up" | |
S = "move_down" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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