use std::borrow::Cow;
use rdf_syntax::{InvalidIri, Iri, IriBuf, IriRef, IriRefBuf};
#[derive(Debug, thiserror::Error)]
#[error("invalid compact IRI")]
pub struct InvalidJsonLdCompactIri<T>(pub T);
#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct JsonLdCompactIri(str);
impl JsonLdCompactIri {
pub fn new(s: &str) -> Result<&Self, InvalidJsonLdCompactIri<&str>> {
match s.split_once(':') {
Some((prefix, suffix)) if prefix != "_" && !suffix.starts_with("//") => {
match IriRef::new(s) {
Ok(_) => Ok(unsafe { Self::new_unchecked(s) }),
Err(_) => Err(InvalidJsonLdCompactIri(s)),
}
}
_ => Err(InvalidJsonLdCompactIri(s)),
}
}
pub unsafe fn new_unchecked(s: &str) -> &Self {
unsafe { std::mem::transmute(s) }
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn to_owned(&self) -> JsonLdCompactIriBuf {
JsonLdCompactIriBuf(self.0.to_owned())
}
pub fn prefix(&self) -> &str {
let i = self.find(':').unwrap();
&self[0..i]
}
pub fn suffix(&self) -> &str {
let i = self.find(':').unwrap();
&self[i + 1..]
}
pub fn as_iri(&self) -> Option<&Iri> {
Iri::new(self.as_str()).ok()
}
pub fn as_iri_ref(&self) -> Option<&IriRef> {
IriRef::new(self.as_str()).ok()
}
pub fn resolve<'a>(
&self,
resolver: impl FnOnce(&str) -> Option<Cow<'a, Iri>>,
) -> Result<IriBuf, InvalidIri<String>> {
match resolver(self.prefix()) {
Some(prefix) => IriBuf::from_string(format!("{}{}", prefix, self.suffix())),
None => IriBuf::from_string(self.as_str().to_owned()),
}
}
}
impl std::ops::Deref for JsonLdCompactIri {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl std::borrow::Borrow<str> for JsonLdCompactIri {
fn borrow(&self) -> &str {
&self.0
}
}
impl AsRef<str> for JsonLdCompactIri {
fn as_ref(&self) -> &str {
&self.0
}
}
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct JsonLdCompactIriBuf(String);
impl JsonLdCompactIriBuf {
pub fn from_string(s: String) -> Result<Self, InvalidJsonLdCompactIri<String>> {
match JsonLdCompactIri::new(&s) {
Ok(_) => Ok(unsafe { Self::new_unchecked(s) }),
Err(_) => Err(InvalidJsonLdCompactIri(s)),
}
}
pub unsafe fn new_unchecked(s: String) -> Self {
Self(s)
}
pub fn as_compact_iri(&self) -> &JsonLdCompactIri {
unsafe { JsonLdCompactIri::new_unchecked(&self.0) }
}
pub fn into_iri_ref(self) -> IriRefBuf {
IriRefBuf::new(self.0).unwrap()
}
pub fn into_string(self) -> String {
self.0
}
}
impl std::borrow::Borrow<JsonLdCompactIri> for JsonLdCompactIriBuf {
fn borrow(&self) -> &JsonLdCompactIri {
self.as_compact_iri()
}
}
impl std::ops::Deref for JsonLdCompactIriBuf {
type Target = JsonLdCompactIri;
fn deref(&self) -> &JsonLdCompactIri {
self.as_compact_iri()
}
}