Skip to main content

jsonld_syntax/context/definition/
vocab.rs

1use crate::{CompactIri, ExpandableRef};
2use iri_rs::Iri;
3use rdfx::BlankId;
4
5#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7#[cfg_attr(feature = "serde", serde(transparent))]
8/// Value of the `@vocab` entry.
9///
10/// Kept as an unvalidated string: it may be an IRI, a compact IRI, a blank node
11/// identifier or a term of the surrounding context, and which one it is can
12/// only be told once the context is processed.
13pub struct Vocab(String);
14
15impl Vocab {
16    /// Parses this value as an IRI, returning `None` if it is not one.
17    #[must_use]
18    pub fn as_iri(&self) -> Option<Iri<&str>> {
19        Iri::parse(self.0.as_str()).ok()
20    }
21
22    /// Parses this value as a compact IRI, returning `None` if it is not one.
23    #[must_use]
24    pub fn as_compact_iri(&self) -> Option<&CompactIri> {
25        CompactIri::new(&self.0).ok()
26    }
27
28    /// Parses this value as a blank node identifier, returning `None` if it is
29    /// not one.
30    #[must_use]
31    pub fn as_blank_id(&self) -> Option<&BlankId> {
32        BlankId::new(&self.0).ok()
33    }
34
35    /// Returns this value as a string slice.
36    #[must_use]
37    pub fn as_str(&self) -> &str {
38        &self.0
39    }
40
41    /// Unwraps the underlying string.
42    #[must_use]
43    pub fn into_string(self) -> String {
44        self.0
45    }
46}
47
48impl From<String> for Vocab {
49    fn from(s: String) -> Self {
50        Self(s)
51    }
52}
53
54impl<'a> From<&'a Vocab> for ExpandableRef<'a> {
55    fn from(v: &'a Vocab) -> Self {
56        ExpandableRef::String(&v.0)
57    }
58}