use crate::model::base::Id;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum HRef {
Local(String),
Remote(String),
}
impl HRef {
pub fn from_local(id: impl Into<String>) -> Self {
let s = id.into();
let bare = s.strip_prefix('#').unwrap_or(&s).to_owned();
HRef::Local(bare)
}
pub fn from_local_id(id: Id) -> Self {
HRef::Local(id.into())
}
pub fn from_remote(uri: impl Into<String>) -> Self {
HRef::Remote(uri.into())
}
pub fn local_id(&self) -> Option<&str> {
match self {
HRef::Local(id) => Some(id.as_str()),
HRef::Remote(_) => None,
}
}
pub fn is_local(&self) -> bool {
matches!(self, HRef::Local(_))
}
}
impl From<String> for HRef {
fn from(s: String) -> Self {
if let Some(id) = s.strip_prefix('#') {
HRef::Local(id.to_owned())
} else {
HRef::Remote(s)
}
}
}
impl From<&str> for HRef {
fn from(s: &str) -> Self {
HRef::from(s.to_owned())
}
}
impl std::fmt::Display for HRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
HRef::Local(id) => write!(f, "#{id}"),
HRef::Remote(uri) => f.write_str(uri),
}
}
}
impl std::str::FromStr for HRef {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(HRef::from(s))
}
}