Created
July 21, 2015 04:33
-
-
Save flagoworld/c432ac12df37dad5c6f3 to your computer and use it in GitHub Desktop.
gstore multi type hashmap
This file contains hidden or 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
use std::any::Any; | |
use std::collections::HashMap; | |
use std::fmt; | |
pub struct GStore | |
{ | |
map: HashMap<String, Box<Any>> | |
} | |
impl GStore | |
{ | |
pub fn new() -> GStore | |
{ | |
GStore { map: HashMap::new() } | |
} | |
pub fn insert_string(&mut self, key: &str, string: String) | |
{ | |
self.map.insert(key.to_string(), Box::new(string)); | |
} | |
pub fn insert_int(&mut self, key: &str, integer: usize) | |
{ | |
self.map.insert(key.to_string(), Box::new(integer)); | |
} | |
pub fn get_string(&self, key: &str) -> &str | |
{ | |
&self.map.get(key).unwrap().downcast_ref::<String>().unwrap() | |
} | |
pub fn get_int(&self, key: &str) -> usize | |
{ | |
*self.map.get(key).unwrap().downcast_ref::<usize>().unwrap() | |
} | |
pub fn contains_key<T: Any>(&self, key: &str) -> bool | |
{ | |
self.map.get(key).and_then({ |v| v.downcast_ref::<T>() }).map_or(false, { |_| true }) | |
} | |
} | |
impl fmt::Debug for GStore | |
{ | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result | |
{ | |
write!(f, "GStore ({})", self.map.len()) | |
} | |
} | |
fn main() | |
{ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment