-
-
Save badboy/c4b6ddd87384620f93d4aea6d155cc52 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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
#![allow(unused)] | |
use std::collections::HashMap; | |
#[derive(Debug)] | |
enum Scalar { | |
String(String), | |
Unsigned(u32), | |
Bool(bool), | |
} | |
impl Scalar { | |
pub fn set_string<S: AsRef<str>>(&mut self, val: S) { | |
if let Scalar::String(ref mut s) = self { | |
s.clear(); | |
s.push_str(val.as_ref()); | |
} else { | |
panic!("Trying to set a string on a non-string scalar"); | |
} | |
} | |
pub fn set_bool(&mut self, val: bool) { | |
if let Scalar::Bool(ref mut s) = self { | |
*s = val; | |
} else { | |
panic!("Trying to set a bool on a non-bool scalar"); | |
} | |
} | |
pub fn set_uint(&mut self, val: u32) { | |
if let Scalar::Unsigned(ref mut s) = self { | |
*s = val; | |
} else { | |
panic!("Trying to set a uint on a non-uint scalar"); | |
} | |
} | |
} | |
#[derive(Clone, Copy, Debug)] | |
enum ScalarType { | |
String, | |
Unsigned, | |
Bool, | |
} | |
fn make_scalar(typ: ScalarType) -> Scalar { | |
match typ { | |
ScalarType::String => Scalar::String(String::new()), | |
ScalarType::Bool => Scalar::Bool(false), | |
ScalarType::Unsigned => Scalar::Unsigned(0), | |
} | |
} | |
#[derive(Debug)] | |
struct Storage { | |
store: HashMap<String, Scalar>, | |
} | |
impl Storage { | |
pub fn new() -> Storage { | |
Storage { | |
store: HashMap::new(), | |
} | |
} | |
pub fn register(&mut self, name: &str, typ: ScalarType) { | |
self.store.insert(name.to_string(), make_scalar(typ)); | |
} | |
pub fn get_scalar(&mut self, name: &str) -> Option<&mut Scalar> { | |
self.store.get_mut(name) | |
} | |
} | |
fn main() { | |
let mut store = Storage::new(); | |
store.register("client_id", ScalarType::String); | |
store.register("a11_enabled", ScalarType::Bool); | |
store.register("pcd", ScalarType::Unsigned); | |
{ | |
let c = store.get_scalar("client_id").unwrap(); | |
c.set_string("c0ffee-c0ff-c0ffee"); | |
} | |
println!("Store: {:?}", store); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment