Skip to main content

json_ld/core/
term.rs

1use rdf_syntax::{Id, Iri, IriBuf};
2use std::fmt;
3
4use crate::{JsonLdLenient, syntax::JsonLdKeyword};
5
6/// Identifier, keyword or `@null`.
7#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub enum JsonLdTerm {
9	/// `@null` value.
10	Null,
11
12	/// Node identifier.
13	Id(JsonLdLenient<Id>),
14
15	/// [`JsonLdKeyword`].
16	Keyword(JsonLdKeyword),
17}
18
19impl JsonLdTerm {
20	/// Checks if this term is `@null`.
21	pub fn is_null(&self) -> bool {
22		matches!(self, JsonLdTerm::Null)
23	}
24
25	/// Turns this term into an IRI if possible.
26	///
27	/// If it is not an IRI, returns the term itself.
28	pub fn into_iri(self) -> Result<IriBuf, Self> {
29		match self {
30			JsonLdTerm::Id(JsonLdLenient::Valid(Id::Iri(id))) => Ok(id),
31			term => Err(term),
32		}
33	}
34
35	/// Checks if this term is a keyword.
36	pub fn is_keyword(&self) -> bool {
37		matches!(self, JsonLdTerm::Keyword(_))
38	}
39
40	/// Returns a reference to the IRI representation of the term, if any.
41	pub fn as_iri(&self) -> Option<&Iri> {
42		match self {
43			JsonLdTerm::Id(p) => p.as_iri(),
44			_ => None,
45		}
46	}
47
48	pub fn as_str(&self) -> &str {
49		match self {
50			JsonLdTerm::Id(p) => p.as_str(),
51			JsonLdTerm::Keyword(k) => k.into_str(),
52			JsonLdTerm::Null => "",
53		}
54	}
55}
56
57impl From<IriBuf> for JsonLdTerm {
58	fn from(id: IriBuf) -> JsonLdTerm {
59		JsonLdTerm::Id(JsonLdLenient::Valid(Id::Iri(id)))
60	}
61}
62
63impl From<JsonLdLenient<Id>> for JsonLdTerm {
64	fn from(prop: JsonLdLenient<Id>) -> JsonLdTerm {
65		JsonLdTerm::Id(prop)
66	}
67}
68
69impl fmt::Display for JsonLdTerm {
70	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71		self.as_str().fmt(f)
72	}
73}