Skip to content

Instantly share code, notes, and snippets.

@XanClic
Last active July 13, 2020 19:11
Show Gist options
  • Save XanClic/45d2e88d5b86dde8f35476d15433ee1a to your computer and use it in GitHub Desktop.
Save XanClic/45d2e88d5b86dde8f35476d15433ee1a to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
trait Descend {
fn descend(&self, key: &str, rem_path: Option<&str>) -> String;
}
impl Descend for HashMap<String, String> {
fn descend(&self, key: &str, rem_path: Option<&str>) -> String {
let obj = &self[key];
if rem_path.is_some() {
panic!("oh no")
} else {
obj.clone()
}
}
}
impl<T: Descend> Descend for HashMap<String, T> {
fn descend(&self, key: &str, rem_path: Option<&str>) -> String {
let obj = &self[key];
if let Some(rp) = rem_path {
dpath(obj, rp)
} else {
panic!("oh no")
}
}
}
impl Descend for Vec<String> {
fn descend(&self, key: &str, rem_path: Option<&str>) -> String {
let obj = &self[key.parse::<usize>().unwrap()];
if rem_path.is_some() {
panic!("oh no")
} else {
obj.clone()
}
}
}
impl<T: Descend> Descend for Vec<T> {
fn descend(&self, key: &str, rem_path: Option<&str>) -> String {
let obj = &self[key.parse::<usize>().unwrap()];
if let Some(rp) = rem_path {
dpath(obj, rp)
} else {
panic!("oh no")
}
}
}
fn dpath<T: Descend>(map: &T, path: &str) -> String {
let mut pi = path.splitn(2, "/");
map.descend(pi.next().unwrap(), pi.next())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment