Skip to main content

jsonld_syntax/context/term_definition/
index.rs

1use crate::CompactIri;
2use iri_rs::Iri;
3use std::{fmt, hash::Hash};
4
5#[derive(Clone, PartialOrd, Ord, Debug)]
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7#[cfg_attr(feature = "serde", serde(transparent))]
8/// Value of the `@index` entry of a term definition: the property carrying the
9/// index of the values in an index map.
10pub struct Index(String);
11
12impl Index {
13    /// Parses this value as an IRI, returning `None` if it is not one.
14    #[must_use]
15    pub fn as_iri(&self) -> Option<Iri<&str>> {
16        Iri::parse(self.0.as_str()).ok()
17    }
18
19    /// Parses this value as a compact IRI, returning `None` if it is not one.
20    #[must_use]
21    pub fn as_compact_iri(&self) -> Option<&CompactIri> {
22        CompactIri::new(&self.0).ok()
23    }
24
25    /// Returns this value as a string slice.
26    #[must_use]
27    pub fn as_str(&self) -> &str {
28        &self.0
29    }
30
31    /// Unwraps the underlying string.
32    #[must_use]
33    pub fn into_string(self) -> String {
34        self.0
35    }
36}
37
38impl PartialEq for Index {
39    fn eq(&self, other: &Self) -> bool {
40        self.0 == other.0
41    }
42}
43
44impl fmt::Display for Index {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        self.0.fmt(f)
47    }
48}
49
50impl Eq for Index {}
51
52impl Hash for Index {
53    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
54        self.as_str().hash(state);
55    }
56}
57
58impl From<String> for Index {
59    fn from(s: String) -> Self {
60        Self(s)
61    }
62}