json_ld_serialization/
lib.rs1use std::hash::Hash;
7
8use json_ld_core::{ExpandedDocument, Node, Object};
9
10use linked_data::{rdf_types::Vocabulary, LinkedData, LinkedDataResource, LinkedDataSubject};
11use rdf_types::{
12 interpretation::{
13 ReverseBlankIdInterpretation, ReverseIriInterpretation, ReverseLiteralInterpretation,
14 },
15 vocabulary::IriVocabularyMut,
16 Interpretation,
17};
18
19mod expanded;
20
21use expanded::SerializeExpandedDocument;
22
23pub use expanded::{serialize_node_with, serialize_object_with};
24
25#[derive(Debug, thiserror::Error)]
26pub enum Error {
27 #[error("invalid graph label")]
28 InvalidGraph,
29
30 #[error("invalid predicate")]
31 InvalidPredicate,
32
33 #[error("invalid node object")]
34 InvalidNode,
35
36 #[error("reverse properties on lists are not supported")]
37 ListReverseProperty,
38
39 #[error("included nodes on lists are not supported")]
40 ListInclude,
41}
42
43pub fn serialize(value: &impl LinkedData) -> Result<ExpandedDocument, Error> {
45 serialize_with(&mut (), &mut (), value)
46}
47
48pub fn serialize_with<V, I>(
51 vocabulary: &mut V,
52 interpretation: &mut I,
53 value: &impl LinkedData<I, V>,
54) -> Result<ExpandedDocument<V::Iri, V::BlankId>, Error>
55where
56 V: Vocabulary + IriVocabularyMut,
57 V::Iri: Clone + Eq + Hash,
58 V::BlankId: Clone + Eq + Hash,
59 I: Interpretation
60 + ReverseIriInterpretation<Iri = V::Iri>
61 + ReverseBlankIdInterpretation<BlankId = V::BlankId>
62 + ReverseLiteralInterpretation<Literal = V::Literal>,
63{
64 let serializer = SerializeExpandedDocument::new(vocabulary, interpretation);
65
66 value.visit(serializer)
67}
68
69pub fn serialize_object(
71 value: &(impl LinkedDataSubject + LinkedDataResource),
72) -> Result<Object, Error> {
73 serialize_object_with(&mut (), &mut (), value)
74}
75
76pub fn serialize_node(
78 value: &(impl LinkedDataSubject + LinkedDataResource),
79) -> Result<Node, Error> {
80 serialize_node_with(&mut (), &mut (), value)
81}