Skip to content

Instantly share code, notes, and snippets.

@brosenan
Created December 15, 2018 11:55
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 brosenan/0f38b1fa36c41cb1bfb34c01981b29ea to your computer and use it in GitHub Desktop.
Save brosenan/0f38b1fa36c41cb1bfb34c01981b29ea to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Clone)]
pub enum Value {
Num(f64),
Str(String),
Struct(HashMap<String, Arc<Value>>),
}
impl Value {
pub fn from_num(v: f64) -> Value {
Value::Num(v)
}
pub fn from_str(v: String) -> Value {
Value::Str(v)
}
pub fn new_struct() -> Value {
Value::Struct(HashMap::new())
}
pub fn as_struct_mut<'a>(&'a mut self) -> &'a mut HashMap<String, Arc<Value>> {
if let Value::Struct(m) = self {
m
} else {
panic!("Expected Struct, got: {}", self);
}
}
pub fn as_struct<'a>(&'a self) -> &'a HashMap<String, Arc<Value>> {
if let Value::Struct(m) = self {
m
} else {
panic!("Expected Struct, got: {}", self);
}
}
pub fn set(&mut self, k: String, v: Value) {
self.as_struct_mut().insert(k, Arc::new(v));
}
pub fn set_at_path(&mut self, path: &[String], v: Value) {
let mut curr = self;
for k in path[..path.len()-1].iter() {
curr = Arc::make_mut(curr.as_struct_mut().get_mut(k).unwrap());
}
curr.as_struct_mut().insert(path[path.len()-1].clone(), Arc::new(v));
}
pub fn get_at_path<'a>(&'a self, path: &[String]) -> &'a Value {
let mut curr = self;
for k in path.iter() {
curr = curr.as_struct().get(k).unwrap();
}
curr
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Value::Num(v) => write!(f, "{}", v),
Value::Str(s) => write!(f, "{}", s),
Value::Struct(_m) => write!(f, "[...]"),
}
}
}
fn main() {
let v = Value::from_num(2.0);
let mut s = Value::new_struct();
s.set(String::from("foo"), v);
s.set(String::from("bar"), Value::new_struct());
s.set_at_path(&[String::from("bar"), String::from("baz")], Value::from_num(3.0));
println!("{}", s.get_at_path(&[String::from("bar"), String::from("baz")]));
let mut s1 = s.clone();
s1.set_at_path(&[String::from("bar"), String::from("baz")], Value::from_num(4.0));
println!("{}", s.get_at_path(&[String::from("bar"), String::from("baz")]));
println!("{}", s1.get_at_path(&[String::from("bar"), String::from("baz")]));
}
@brosenan
Copy link
Author

This is an example of defining dynamic data structures in Rust. The Value structure is recursive, containing numbers, strings and structs, which are maps from strings to values (defined recursively). Values can be cloned, and cloning is implemented lazily. Mutation follows "clone on write" -- If there is only one reference to this object, mutation is done directly. But if an object is referenced more than once, the Arc::make_mut() function clones the object (lazily) and the mutation is performed on the new clone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment