1use crate::{Id, ValidId};
2use contextual::{AsRefWithContext, DisplayWithContext, WithContext};
3use iri_rs::IriBuf;
4use jsonld_syntax::Keyword;
5use rdfx::{BlankIdBuf, vocabulary::Vocabulary};
6use std::fmt;
7
8#[derive(Clone, PartialEq, Eq, Hash)]
10pub enum Term<T = IriBuf, B = BlankIdBuf> {
11 Null,
13
14 Id(Id<T, B>),
16
17 Keyword(Keyword),
19}
20
21impl<I, B> Term<I, B> {
22 pub fn is_null(&self) -> bool {
24 matches!(self, Term::Null)
25 }
26
27 pub fn into_iri(self) -> Result<I, Self> {
35 match self {
36 Term::Id(Id::Valid(ValidId::Iri(id))) => Ok(id),
37 term => Err(term),
38 }
39 }
40
41 pub fn is_keyword(&self) -> bool {
43 matches!(self, Term::Keyword(_))
44 }
45
46 pub fn as_iri(&self) -> Option<&I> {
48 match self {
49 Term::Id(p) => p.as_iri(),
50 _ => None,
51 }
52 }
53
54 pub fn map_id<U, C>(self, f: impl FnOnce(ValidId<I, B>) -> ValidId<U, C>) -> Term<U, C> {
56 match self {
57 Self::Null => Term::Null,
58 Self::Keyword(k) => Term::Keyword(k),
59 Self::Id(id) => Term::Id(id.map(f)),
60 }
61 }
62}
63
64impl<T, B, N: Vocabulary<Iri = T, BlankId = B>> DisplayWithContext<N> for Term<T, B> {
65 fn fmt_with(&self, vocabulary: &N, f: &mut fmt::Formatter) -> fmt::Result {
66 use std::fmt::Display;
67 match self {
68 Self::Null => write!(f, "null"),
69 Self::Id(id) => id.with(vocabulary).fmt(f),
70 Self::Keyword(k) => k.fmt(f),
71 }
72 }
73}
74
75impl<T: AsRef<str>, B: AsRef<str>> Term<T, B> {
76 pub fn as_str(&self) -> &str {
78 match self {
79 Term::Id(p) => p.as_str(),
80 Term::Keyword(k) => k.into_str(),
81 Term::Null => "",
82 }
83 }
84}
85
86impl<T, B, N: Vocabulary<Iri = T, BlankId = B>> AsRefWithContext<str, N> for Term<T, B> {
87 fn as_ref_with<'a>(&'a self, vocabulary: &'a N) -> &'a str {
88 match self {
89 Term::Id(p) => p.with(vocabulary).as_str(),
90 Term::Keyword(k) => k.into_str(),
91 Term::Null => "",
92 }
93 }
94}
95
96impl<'a, T, B> From<&'a Term<T, B>> for Term<&'a T, &'a B> {
97 fn from(t: &'a Term<T, B>) -> Term<&'a T, &'a B> {
98 match t {
99 Term::Null => Term::Null,
100 Term::Id(r) => Term::Id(r.into()),
101 Term::Keyword(k) => Term::Keyword(*k),
102 }
103 }
104}
105
106impl<T, B> From<T> for Term<T, B> {
107 fn from(id: T) -> Term<T, B> {
108 Term::Id(Id::Valid(ValidId::Iri(id)))
109 }
110}
111
112impl<T, B> From<Id<T, B>> for Term<T, B> {
113 fn from(prop: Id<T, B>) -> Term<T, B> {
114 Term::Id(prop)
115 }
116}
117
118impl<T: fmt::Display, B: fmt::Display> fmt::Display for Term<T, B> {
119 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120 match self {
121 Term::Id(p) => p.fmt(f),
122 Term::Keyword(kw) => kw.fmt(f),
123 Term::Null => write!(f, "null"),
124 }
125 }
126}
127
128impl<T: fmt::Debug, B: fmt::Debug> fmt::Debug for Term<T, B> {
129 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
130 match self {
131 Term::Id(p) => write!(f, "Term::Id({p:?})"),
132 Term::Keyword(kw) => write!(f, "Term::Keyword({kw})"),
133 Term::Null => write!(f, "Term::Null"),
134 }
135 }
136}