use std::sync::Arc;
use crate::error::{ClientError, NameRefusal};
use crate::transport::{MethodRef, RoutePath};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Route {
path: RoutePath,
refused: Option<Arc<(String, NameRefusal)>>,
}
impl Route {
pub const ROOT: Route = Route { path: RoutePath::EMPTY, refused: None };
pub fn at(path: impl Into<RoutePath>, namespace: &str) -> Route {
let path = path.into();
if path.as_str() == namespace {
Route::ROOT
} else {
Route { path, refused: None }
}
}
pub fn path<'a>(&'a self, namespace: &'a str) -> &'a str {
if self.path.is_empty() {
namespace
} else {
self.path.as_str()
}
}
pub fn child(&self, segment: &str, joined: &'static str) -> Route {
let path = if self.path.is_empty() {
RoutePath::from_static(joined)
} else {
self.path.join(segment)
};
Route { path, refused: self.refused.clone() }
}
pub fn instance(&self, namespace: &str, name: &str, statics: &[&str]) -> Route {
let path = if self.path.is_empty() {
RoutePath::from(format!("{namespace}.{name}"))
} else {
self.path.join(name)
};
let refusal = if name.is_empty() {
Some(NameRefusal::Empty)
} else if name.contains('.') {
Some(NameRefusal::Dotted)
} else if !is_route_segment(name) {
Some(NameRefusal::NotASegment)
} else if statics.contains(&name) {
Some(NameRefusal::StaticChild)
} else {
None
};
let refused = match (&self.refused, refusal) {
(Some(earlier), _) => Some(earlier.clone()),
(None, Some(why)) => Some(Arc::new((name.to_owned(), why))),
(None, None) => None,
};
Route { path, refused }
}
pub fn method(&self, method: MethodRef) -> Result<MethodRef, ClientError> {
match &self.refused {
None => Ok(if self.path.is_empty() { method } else { method.at(self.path.clone()) }),
Some(r) => Err(ClientError::InvalidName { name: r.0.clone(), reason: r.1 }),
}
}
}
pub fn is_route_segment(s: &str) -> bool {
let mut chars = s.chars();
match chars.next() {
Some(c) if c.is_ascii_lowercase() => chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn routes_join_and_refuse() {
let root = Route::ROOT;
assert_eq!(root.path("tree"), "tree");
let branch = root.child("branch", "tree.branch");
assert_eq!(branch.path("branch"), "tree.branch");
let a = root.instance("tree", "a", &["branch"]);
assert_eq!(a.path("item"), "tree.a");
assert_eq!(a.method(MethodRef::new("item", "watch")).unwrap().qualified(), "tree.a.watch");
assert!(root.instance("tree", "count", &["branch"]).method(MethodRef::new("item", "watch")).is_ok());
for (name, why) in [("", NameRefusal::Empty), ("a.b", NameRefusal::Dotted), ("A", NameRefusal::NotASegment), ("branch", NameRefusal::StaticChild)] {
let r = root.instance("tree", name, &["branch"]);
assert_eq!(r.method(MethodRef::new("item", "watch")), Err(ClientError::InvalidName { name: name.into(), reason: why }));
let below = r.child("leaf", "item.leaf").instance("item", "ok", &[]);
assert!(below.method(MethodRef::new("x", "y")).is_err());
}
}
}