use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Namespace {
Neo4j,
System,
SystemOntologies,
}
impl Namespace {
pub const ALL: [Namespace; 3] = [
Namespace::Neo4j,
Namespace::System,
Namespace::SystemOntologies,
];
pub fn as_str(&self) -> &'static str {
match self {
Namespace::Neo4j => "neo4j",
Namespace::System => "system",
Namespace::SystemOntologies => "system_ontologies",
}
}
pub fn parse(name: &str) -> Option<Namespace> {
Namespace::ALL
.iter()
.find(|ns| name.eq_ignore_ascii_case(ns.as_str()))
.copied()
}
pub fn is_writable(&self) -> bool {
matches!(self, Namespace::Neo4j)
}
pub fn is_read_only(&self) -> bool {
matches!(self, Namespace::SystemOntologies)
}
pub fn element_id_segment(&self) -> Option<&'static str> {
match self {
Namespace::Neo4j => Some("rl-id"),
Namespace::System => None,
Namespace::SystemOntologies => Some("rl-onto"),
}
}
pub fn from_element_id_segment(segment: &str) -> Option<Namespace> {
Namespace::ALL
.iter()
.find(|ns| ns.element_id_segment() == Some(segment))
.copied()
}
}
pub const GRAPH_SELECTOR_FUNCTIONS: [(&str, usize); 4] = [
("graph.names", 0),
("graph.byname", 1),
("graph.byelementid", 1),
("graph.propertiesbyname", 1),
];
pub const GRAPH_SELECTOR_FUNCTION_NAMES: [&str; GRAPH_SELECTOR_FUNCTIONS.len()] = {
let mut names = [""; GRAPH_SELECTOR_FUNCTIONS.len()];
let mut i = 0;
while i < GRAPH_SELECTOR_FUNCTIONS.len() {
names[i] = GRAPH_SELECTOR_FUNCTIONS[i].0;
i += 1;
}
names
};
pub fn is_graph_selector_function_name(name: &str) -> bool {
graph_selector_arity(name).is_some()
}
pub fn graph_selector_arity(name: &str) -> Option<usize> {
GRAPH_SELECTOR_FUNCTIONS
.iter()
.find(|(selector, _)| name.eq_ignore_ascii_case(selector))
.map(|(_, arity)| *arity)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ElementIdRef<'a> {
pub kind: &'a str,
pub segment: &'a str,
pub id: &'a str,
}
impl<'a> ElementIdRef<'a> {
pub fn parse(id: &'a str) -> Option<ElementIdRef<'a>> {
let mut parts = id.split(':');
let parsed = ElementIdRef {
kind: parts.next()?,
segment: parts.next()?,
id: parts.next()?,
};
if parts.next().is_some() {
return None;
}
Some(parsed)
}
pub fn namespace(&self) -> Option<Namespace> {
Namespace::from_element_id_segment(self.segment)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ElementKind {
Node,
Rel,
}
impl ElementKind {
fn kind_segment(self) -> &'static str {
match self {
ElementKind::Node => "4",
ElementKind::Rel => "5",
}
}
fn entity_prefix(self) -> char {
match self {
ElementKind::Node => 'n',
ElementKind::Rel => 'r',
}
}
}
pub fn node_element_id(id: i64, namespace: Namespace) -> Option<String> {
element_id(id, namespace, ElementKind::Node)
}
pub fn rel_element_id(id: i64, namespace: Namespace) -> Option<String> {
element_id(id, namespace, ElementKind::Rel)
}
pub fn parse_node_element_id(s: &str) -> Option<i64> {
parse_element_id(s, ElementKind::Node)
}
pub fn parse_rel_element_id(s: &str) -> Option<i64> {
parse_element_id(s, ElementKind::Rel)
}
fn element_id(id: i64, namespace: Namespace, kind: ElementKind) -> Option<String> {
let segment = namespace.element_id_segment()?;
Some(format!(
"{}:{}:{}{}",
kind.kind_segment(),
segment,
kind.entity_prefix(),
id
))
}
fn parse_element_id(s: &str, kind: ElementKind) -> Option<i64> {
let parsed = ElementIdRef::parse(s)?;
if parsed.kind != kind.kind_segment() {
return None;
}
parsed.namespace()?;
parsed.id.strip_prefix(kind.entity_prefix())?.parse().ok()
}
impl fmt::Display for Namespace {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Namespace {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Namespace::parse(s).ok_or(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_is_case_insensitive() {
assert_eq!(Namespace::parse("neo4j"), Some(Namespace::Neo4j));
assert_eq!(Namespace::parse("Neo4j"), Some(Namespace::Neo4j));
assert_eq!(Namespace::parse("NEO4J"), Some(Namespace::Neo4j));
assert_eq!(Namespace::parse("SYSTEM"), Some(Namespace::System));
assert_eq!(
Namespace::parse("System_Ontologies"),
Some(Namespace::SystemOntologies)
);
assert_eq!("neo4j".parse::<Namespace>(), Ok(Namespace::Neo4j));
assert_eq!(
"SYSTEM_ONTOLOGIES".parse::<Namespace>(),
Ok(Namespace::SystemOntologies)
);
}
#[test]
fn parse_rejects_unknown_names() {
assert_eq!(Namespace::parse(""), None);
assert_eq!(Namespace::parse("nosuch"), None);
assert_eq!(Namespace::parse("systemx"), None);
assert_eq!(Namespace::parse("system_ontology"), None);
assert!("movies".parse::<Namespace>().is_err());
}
#[test]
fn display_and_as_str_are_canonical() {
assert_eq!(Namespace::Neo4j.as_str(), "neo4j");
assert_eq!(Namespace::System.as_str(), "system");
assert_eq!(Namespace::SystemOntologies.as_str(), "system_ontologies");
assert_eq!(Namespace::Neo4j.to_string(), "neo4j");
assert_eq!(Namespace::System.to_string(), "system");
assert_eq!(Namespace::SystemOntologies.to_string(), "system_ontologies");
}
#[test]
fn only_neo4j_is_writable() {
assert!(Namespace::Neo4j.is_writable());
assert!(!Namespace::System.is_writable());
assert!(!Namespace::SystemOntologies.is_writable());
}
#[test]
fn only_system_ontologies_is_read_only() {
assert!(!Namespace::Neo4j.is_read_only());
assert!(!Namespace::System.is_read_only());
assert!(Namespace::SystemOntologies.is_read_only());
}
#[test]
fn element_id_segments_round_trip() {
assert_eq!(Namespace::Neo4j.element_id_segment(), Some("rl-id"));
assert_eq!(Namespace::System.element_id_segment(), None);
assert_eq!(
Namespace::SystemOntologies.element_id_segment(),
Some("rl-onto")
);
for ns in Namespace::ALL {
if let Some(segment) = ns.element_id_segment() {
assert_eq!(Namespace::from_element_id_segment(segment), Some(ns));
}
}
assert_eq!(Namespace::from_element_id_segment("system"), None);
assert_eq!(Namespace::from_element_id_segment("rl-id.system"), None);
assert_eq!(Namespace::from_element_id_segment("neo4j"), None);
assert_eq!(Namespace::from_element_id_segment(""), None);
}
#[test]
fn element_ids_carry_a_dash_so_shape_sniffing_clients_classify_them() {
for ns in Namespace::ALL {
if ns.element_id_segment().is_some() {
assert!(node_element_id(7, ns).unwrap().contains('-'));
assert!(rel_element_id(9, ns).unwrap().contains('-'));
}
}
}
#[test]
fn element_id_ref_parses_the_three_part_shape() {
let parsed = ElementIdRef::parse("4:rl-onto:r9").unwrap();
assert_eq!(parsed.kind, "4");
assert_eq!(parsed.segment, "rl-onto");
assert_eq!(parsed.id, "r9");
assert_eq!(parsed.namespace(), Some(Namespace::SystemOntologies));
assert_eq!(
ElementIdRef::parse("5:rl-id:n1").unwrap().namespace(),
Some(Namespace::Neo4j)
);
let parsed = ElementIdRef::parse("4:rl-id:999999").unwrap();
assert_eq!(parsed.id, "999999");
assert_eq!(ElementIdRef::parse("garbage"), None);
assert_eq!(ElementIdRef::parse("4:rl-id"), None);
assert_eq!(ElementIdRef::parse("4:rl-id:n1:extra"), None);
assert_eq!(ElementIdRef::parse("4::n1").unwrap().namespace(), None);
assert_eq!(
ElementIdRef::parse("4:00000000-0000-0000-0000-000000000000:n1")
.unwrap()
.namespace(),
None
);
}
#[test]
fn graph_selector_functions_are_the_four_composite_selectors() {
assert_eq!(
GRAPH_SELECTOR_FUNCTIONS,
[
("graph.names", 0),
("graph.byname", 1),
("graph.byelementid", 1),
("graph.propertiesbyname", 1)
]
);
assert_eq!(
GRAPH_SELECTOR_FUNCTION_NAMES,
[
"graph.names",
"graph.byname",
"graph.byelementid",
"graph.propertiesbyname"
]
);
for (name, _) in GRAPH_SELECTOR_FUNCTIONS {
assert_eq!(name, name.to_ascii_lowercase());
}
assert!(is_graph_selector_function_name("Graph.ByName"));
assert!(!is_graph_selector_function_name("graph.x"));
}
#[test]
fn all_lists_every_namespace_in_order() {
assert_eq!(
Namespace::ALL,
[
Namespace::Neo4j,
Namespace::System,
Namespace::SystemOntologies
]
);
}
}