use serde::{Deserialize, Serialize};
use std::fmt::{self, Display, Formatter};
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct Path {
leaf: String,
seq: Vec<String>,
}
impl Path {
pub fn leaf(&self) -> &str {
self.leaf.as_str()
}
}
impl Display for Path {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", String::from(self))
}
}
impl From<&Path> for String {
fn from(p: &Path) -> String {
format!("/{}:{}", p.seq.join("/"), p.leaf)
}
}
impl From<String> for Path {
fn from(s: String) -> Self {
s.as_str().into()
}
}
impl<'path> From<&'path str> for Path {
fn from(s: &'path str) -> Self {
let mut vec: Vec<_> = s.split(":").collect();
let leaf = vec.remove(1).to_string();
let seq = vec
.remove(0)
.split("/")
.filter(|seg| seg != &"")
.map(|s| s.to_string())
.collect();
Self { leaf, seq }
}
}
#[test]
fn parse_path_simple() {
let path = "/msg:bob";
let Path { leaf, seq } = path.into();
assert_eq!(leaf, "bob".to_string());
assert_eq!(seq, vec!["msg".to_string()]);
}