Skip to content

Instantly share code, notes, and snippets.

@badboy
Forked from rust-play/playground.rs
Created September 27, 2018 20: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 badboy/c4b6ddd87384620f93d4aea6d155cc52 to your computer and use it in GitHub Desktop.
Save badboy/c4b6ddd87384620f93d4aea6d155cc52 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![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