Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created October 9, 2019 09:21
Show Gist options
  • Save rust-play/db681346b3aac6a79905931e6b6ef779 to your computer and use it in GitHub Desktop.
Save rust-play/db681346b3aac6a79905931e6b6ef779 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use crate::node::Node;
use serde_json::Value;
use serde::ser::{Serialize, SerializeMap, Serializer};
use json_patch::merge;
struct WrapDirectory<'a, T> {
name: &'a str,
value: &'a T
}
impl<'a, T> Serialize for WrapDirectory<'a, T> where T: Serialize {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer, T: Serialize
{
let mut ser = serializer.serialize_map(None)?;
ser.serialize_key(self.name)?;
ser.serialize_value(self.value)?;
ser.end()
}
}
fn merge_jsons(nodes: &Vec<Value>) -> Value {
let value = nodes.iter().fold(serde_json::Value::Null, |acc, n| {
let mut cacc = acc.clone();
merge(&mut cacc, n);
cacc
});
value
}
fn make_json(node: &Node) -> Result<Value, serde_json::error::Error> {
match node {
Node::KeyValue{key, value} => {
let wrap = WrapDirectory {name: key, value: value};
serde_json::to_value(wrap)
},
Node::Directory{key, nodes} => {
let jnodes: Result<Vec<_>, _>= nodes.iter()
.filter(|(k, _)| !k.key().is_empty()) //clean empty leafs!
.map(|(_, n)| make_json(n)).collect();
let parts = jnodes?;
let value = merge_jsons(&parts);
serde_json::to_value(WrapDirectory {name: &key, value: &value})
}
}
}
pub fn to_json(_node: &Node) -> String {
let strr = make_json(_node).and_then(|n| serde_json::to_string_pretty(&n));
match strr {
Ok(x) => {
println!("{}", x);
x
},
Err(_) => {
unimplemented!("fsd")
}
}
}
pub fn to_hocon(_nodes: &Node) -> String {
println!("{:?}", _nodes); "".to_string()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment