jsonld-syntax 0.24.0

JSON-LD syntax
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use crate::{CompactIri, Keyword, intern::intern_static};
use iri_rs::Iri;
use rdfx::BlankId;
use std::{borrow::Borrow, cmp::Ordering, fmt, hash::Hash};

/// Context key.
///
/// Stores the canonical `&'static str` returned by the process-wide interner
/// directly, so [`Key::as_str`] is a single load and equality on equal logical
/// strings short-circuits via pointer equality (the interner guarantees a
/// unique allocation per interned string).
///
/// Interned strings are never freed: memory usage grows with the number of
/// distinct keys the process parses. See the [`crate::intern`] module
/// documentation for the implications when parsing untrusted input.
#[derive(Clone, Copy, Debug)]
pub struct Key(&'static str);

impl Key {
    /// Parses this key as an IRI, returning `None` if it is not one.
    #[must_use]
    pub fn as_iri(&self) -> Option<Iri<&str>> {
        Iri::parse(self.0).ok()
    }

    /// Parses this key as a compact IRI, returning `None` if it is not one.
    #[must_use]
    pub fn as_compact_iri(&self) -> Option<&CompactIri> {
        CompactIri::new(self.0).ok()
    }

    /// Parses this key as a blank node identifier, returning `None` if it is
    /// not one.
    #[must_use]
    pub fn as_blank_id(&self) -> Option<&BlankId> {
        BlankId::new(self.0).ok()
    }

    /// Returns the interned string of this key.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        self.0
    }

    /// Returns the length of this key, in bytes.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Checks whether this key is the empty string.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Copies this key into a newly allocated `String`.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0.to_owned()
    }

    /// Checks whether this key is keyword-like: an `@` followed by ASCII
    /// letters. See [`crate::is_keyword_like`].
    #[must_use]
    pub fn is_keyword_like(&self) -> bool {
        crate::is_keyword_like(self.0)
    }
}

impl PartialEq for Key {
    fn eq(&self, other: &Self) -> bool {
        // Interned strings are pointer-unique, so a pointer/length match is
        // sufficient and faster than byte comparison.
        std::ptr::eq(self.0.as_ptr(), other.0.as_ptr()) && self.0.len() == other.0.len()
    }
}

impl Eq for Key {}

impl PartialOrd for Key {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Key {
    fn cmp(&self, other: &Self) -> Ordering {
        if self == other { Ordering::Equal } else { self.0.cmp(other.0) }
    }
}

impl From<jstrict::object::Key> for Key {
    fn from(k: jstrict::object::Key) -> Self {
        Self::from(k.into_string())
    }
}

#[allow(clippy::derived_hash_with_manual_eq)]
impl Hash for Key {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // Hash via the underlying string so that `Borrow<str>` lookups
        // (e.g. `HashMap::get(&"foo")`) stay equivalent.
        self.0.hash(state);
    }
}

impl From<String> for Key {
    fn from(k: String) -> Self {
        Self(intern_static(&k))
    }
}

impl<'a> From<&'a str> for Key {
    fn from(value: &'a str) -> Self {
        Self(intern_static(value))
    }
}

impl fmt::Display for Key {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl Borrow<str> for Key {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Key {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Key {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct Visitor;

        impl serde::de::Visitor<'_> for Visitor {
            type Value = Key;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a string")
            }

            // `visit_borrowed_str` and `visit_string` forward here by
            // default; the interner only needs `&str`, so one method covers
            // borrowing formats, owned buffers (`from_reader`, escaped
            // keys) and serde's internal `Content` buffering
            // (`#[serde(flatten)]`) alike.
            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Key, E> {
                Ok(Key::from(v))
            }
        }

        deserializer.deserialize_str(Visitor)
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
/// Borrowed context definition key.
pub struct KeyRef<'a>(&'a str);

impl<'a> KeyRef<'a> {
    /// Checks whether this key is the empty string.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Checks whether this key is keyword-like: an `@` followed by ASCII
    /// letters. See [`crate::is_keyword_like`].
    #[must_use]
    pub fn is_keyword_like(&self) -> bool {
        crate::is_keyword_like(self.as_str())
    }

    /// Returns the borrowed string of this key.
    #[must_use]
    pub fn as_str(&self) -> &'a str {
        self.0
    }

    /// Interns this key and returns the owned [`Key`].
    #[must_use]
    pub fn to_owned(self) -> Key {
        Key::from(self.0)
    }
}

impl<'a> From<&'a str> for KeyRef<'a> {
    fn from(s: &'a str) -> Self {
        Self(s)
    }
}

impl<'a> From<&'a Key> for KeyRef<'a> {
    fn from(k: &'a Key) -> Self {
        Self(k.as_str())
    }
}

impl fmt::Display for KeyRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
/// Context definition key that may also be a JSON-LD keyword.
pub enum KeyOrKeyword {
    /// A JSON-LD keyword.
    Keyword(Keyword),
    /// A term key.
    Key(Key),
}

impl KeyOrKeyword {
    /// Checks whether this is the empty key. A keyword is never empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        match self {
            Self::Keyword(_) => false,
            Self::Key(k) => k.is_empty(),
        }
    }

    /// Returns the keyword, or `None` if this is a term key.
    #[must_use]
    pub fn into_keyword(self) -> Option<Keyword> {
        match self {
            Self::Keyword(k) => Some(k),
            Self::Key(_) => None,
        }
    }

    /// Returns the term key, or `None` if this is a keyword.
    #[must_use]
    pub fn into_key(self) -> Option<Key> {
        match self {
            Self::Keyword(_) => None,
            Self::Key(k) => Some(k),
        }
    }

    /// Returns the keyword, or `None` if this is a term key.
    #[must_use]
    pub fn as_keyword(&self) -> Option<Keyword> {
        match self {
            Self::Keyword(k) => Some(*k),
            Self::Key(_) => None,
        }
    }

    /// Borrows the term key, or returns `None` if this is a keyword.
    #[must_use]
    pub fn as_key(&self) -> Option<&Key> {
        match self {
            Self::Keyword(_) => None,
            Self::Key(k) => Some(k),
        }
    }

    /// Returns this value as it is spelled in the context.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Keyword(k) => k.into_str(),
            Self::Key(k) => k.as_str(),
        }
    }
}

#[allow(clippy::derived_hash_with_manual_eq)]
impl Hash for KeyOrKeyword {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.as_str().hash(state);
    }
}

impl fmt::Display for KeyOrKeyword {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Key(k) => k.fmt(f),
            Self::Keyword(k) => k.fmt(f),
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
/// Borrowed context definition key that may also be a keyword.
pub enum KeyOrKeywordRef<'a> {
    /// A JSON-LD keyword.
    Keyword(Keyword),
    /// A term key.
    Key(KeyRef<'a>),
}

impl<'a> KeyOrKeywordRef<'a> {
    /// Interns the term key, if any, and returns the owned [`KeyOrKeyword`].
    #[must_use]
    pub fn to_owned(self) -> KeyOrKeyword {
        match self {
            Self::Keyword(k) => KeyOrKeyword::Keyword(k),
            Self::Key(k) => KeyOrKeyword::Key(k.to_owned()),
        }
    }

    /// Returns this value as it is spelled in the context.
    #[must_use]
    pub fn as_str(&self) -> &'a str {
        match self {
            Self::Keyword(k) => k.into_str(),
            Self::Key(k) => k.as_str(),
        }
    }
}

impl<'a> From<&'a str> for KeyOrKeywordRef<'a> {
    fn from(s: &'a str) -> Self {
        match Keyword::try_from(s) {
            Ok(k) => Self::Keyword(k),
            Err(_) => Self::Key(s.into()),
        }
    }
}

impl<'a> From<&'a KeyOrKeyword> for KeyOrKeywordRef<'a> {
    fn from(k: &'a KeyOrKeyword) -> Self {
        match k {
            KeyOrKeyword::Keyword(k) => Self::Keyword(*k),
            KeyOrKeyword::Key(k) => Self::Key(k.into()),
        }
    }
}

impl<'a> From<KeyRef<'a>> for KeyOrKeywordRef<'a> {
    fn from(k: KeyRef<'a>) -> Self {
        Self::Key(k)
    }
}

impl<'a> From<&'a Key> for KeyOrKeywordRef<'a> {
    fn from(k: &'a Key) -> Self {
        Self::Key(k.into())
    }
}

/// Context definition key that may also be the `@type` entry.
pub enum KeyOrType {
    /// A term key.
    Key(Key),
    /// The `@type` entry.
    Type,
}

impl KeyOrType {
    /// Returns this value as it is spelled in the context.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Key(k) => k.as_str(),
            Self::Type => "@type",
        }
    }
}

impl fmt::Display for KeyOrType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

#[cfg(all(test, feature = "serde"))]
mod tests {
    #![allow(clippy::unwrap_used)]
    use super::*;
    use jstrict::Parse;

    /// `#[serde(flatten)]` on `Definition::bindings` buffers entries into
    /// serde's internal `Content` representation and replays keys through
    /// `visit_str` (transient, not borrowed). The former
    /// `<&str>::deserialize`-based impl failed on that path.
    #[test]
    fn key_deserializes_through_serde_content_buffer() {
        let (value, _) = jstrict::Value::parse_str(r#"{"@vocab": "http://example.com/", "term": "http://example.com/term"}"#).unwrap();
        let definition: crate::context::Definition = crate::from_value(value).unwrap();
        assert!(definition.bindings.get(&Key::from("term")).is_some());
    }

    /// Owned-string input (`visit_string` → `visit_str`), as produced by
    /// escaped keys and reader-based formats.
    #[test]
    fn key_deserializes_from_owned_string() {
        let (value, _) = jstrict::Value::parse_str(r#""api""#).unwrap();
        let key: Key = crate::from_value(value).unwrap();
        assert_eq!(key.as_str(), "api");
    }
}