Skip to main content

json_ld/core/
ty.rs

1use std::convert::TryFrom;
2use std::fmt;
3
4use rdf_syntax::{Id, Iri, IriBuf};
5
6use super::JsonLdTerm;
7use crate::{JsonLdLenient, syntax::JsonLdKeyword};
8
9/// Object type.
10///
11/// This is the value of a `@type` entry.
12#[derive(Clone, PartialEq, Eq, Hash, Debug)]
13pub enum JsonLdType {
14	/// `@id`.
15	///
16	/// The value must be interpreted as an IRI.
17	Id,
18
19	/// `@json`.
20	///
21	/// The value is an arbitrary JSON value.
22	Json,
23
24	/// `@none`
25	None,
26
27	/// `@vocab`
28	Vocab,
29
30	/// IRI type.
31	Iri(IriBuf),
32}
33
34impl JsonLdType {
35	/// Turns this type into an IRI if possible.
36	pub fn into_iri(self) -> Result<IriBuf, Self> {
37		match self {
38			JsonLdType::Iri(id) => Ok(id),
39			typ => Err(typ),
40		}
41	}
42
43	/// Returns a reference to the type IRI if any.
44	pub fn as_iri(&self) -> Option<&Iri> {
45		match self {
46			JsonLdType::Iri(id) => Some(id),
47			_ => None,
48		}
49	}
50
51	/// Returns a JSON-LD string representation of the type.
52	pub fn as_str(&self) -> &str {
53		match self {
54			JsonLdType::Id => "@id",
55			JsonLdType::Json => "@json",
56			JsonLdType::None => "@none",
57			JsonLdType::Vocab => "@vocab",
58			JsonLdType::Iri(id) => id.as_ref(),
59		}
60	}
61}
62
63impl From<JsonLdType> for JsonLdTerm {
64	fn from(t: JsonLdType) -> JsonLdTerm {
65		match t {
66			JsonLdType::Id => JsonLdTerm::Keyword(JsonLdKeyword::Id),
67			JsonLdType::Json => JsonLdTerm::Keyword(JsonLdKeyword::Json),
68			JsonLdType::None => JsonLdTerm::Keyword(JsonLdKeyword::None),
69			JsonLdType::Vocab => JsonLdTerm::Keyword(JsonLdKeyword::Vocab),
70			JsonLdType::Iri(id) => JsonLdTerm::Id(JsonLdLenient::Valid(Id::Iri(id))),
71		}
72	}
73}
74
75impl TryFrom<JsonLdTerm> for JsonLdType {
76	type Error = JsonLdTerm;
77
78	fn try_from(term: JsonLdTerm) -> Result<JsonLdType, JsonLdTerm> {
79		match term {
80			JsonLdTerm::Keyword(JsonLdKeyword::Id) => Ok(JsonLdType::Id),
81			JsonLdTerm::Keyword(JsonLdKeyword::Json) => Ok(JsonLdType::Json),
82			JsonLdTerm::Keyword(JsonLdKeyword::None) => Ok(JsonLdType::None),
83			JsonLdTerm::Keyword(JsonLdKeyword::Vocab) => Ok(JsonLdType::Vocab),
84			JsonLdTerm::Id(JsonLdLenient::Valid(Id::Iri(id))) => Ok(JsonLdType::Iri(id)),
85			term => Err(term),
86		}
87	}
88}
89
90impl fmt::Display for JsonLdType {
91	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92		self.as_str().fmt(f)
93	}
94}