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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use crate::{
	object,
	syntax::{Keyword, Term},
	util, Id, Indexed, Object, Objects, Reference, ToReference,
};
use cc_traits::MapInsert;
use generic_json::{JsonClone, JsonHash};
use iref::{Iri, IriBuf};
use std::collections::HashSet;
use std::convert::TryFrom;
use std::hash::{Hash, Hasher};

pub mod properties;
pub mod reverse_properties;

pub use properties::Properties;
pub use reverse_properties::ReverseProperties;

/// Node object.
///
/// A node object represents zero or more properties of a node in the graph serialized by a JSON-LD document.
/// A node is defined by its identifier (`@id` field), types, properties and reverse properties.
/// In addition, a node may represent a graph (`@graph field`) and includes nodes
/// (`@included` field).
// NOTE it may be better to use BTreeSet instead of HashSet to have some ordering?
//      in which case the Json bound should be lifted.
#[derive(PartialEq, Eq)]
pub struct Node<J: JsonHash, T: Id = IriBuf> {
	/// Identifier.
	///
	/// This is the `@id` field.
	pub(crate) id: Option<Reference<T>>,

	/// Types.
	///
	/// This is the `@type` field.
	pub(crate) types: Vec<Reference<T>>,

	/// Associated graph.
	///
	/// This is the `@graph` field.
	pub(crate) graph: Option<HashSet<Indexed<Object<J, T>>>>,

	/// Included nodes.
	///
	/// This is the `@included` field.
	pub(crate) included: Option<HashSet<Indexed<Self>>>,

	/// Properties.
	///
	/// Any non-keyword field.
	pub(crate) properties: Properties<J, T>,

	/// Reverse properties.
	///
	/// This is the `@reverse` field.
	pub(crate) reverse_properties: ReverseProperties<J, T>,
}

impl<J: JsonHash, T: Id> Default for Node<J, T> {
	#[inline(always)]
	fn default() -> Self {
		Self::new()
	}
}

impl<J: JsonHash, T: Id> Node<J, T> {
	/// Creates a new empty node.
	#[inline(always)]
	pub fn new() -> Self {
		Self {
			id: None,
			types: Vec::new(),
			graph: None,
			included: None,
			properties: Properties::new(),
			reverse_properties: ReverseProperties::new(),
		}
	}

	/// Creates a new empty node with the given id.
	#[inline(always)]
	pub fn with_id(id: Reference<T>) -> Self {
		Self {
			id: Some(id),
			types: Vec::new(),
			graph: None,
			included: None,
			properties: Properties::new(),
			reverse_properties: ReverseProperties::new(),
		}
	}

	/// Checks if the node object has the given term as key.
	///
	/// # Example
	/// ```
	/// # use json_ld::syntax::{Term, Keyword};
	/// # let node: json_ld::Node<serde_json::Value> = json_ld::Node::new();
	///
	/// // Checks if the JSON object representation of the node has an `@id` key.
	/// if node.has_key(&Term::Keyword(Keyword::Id)) {
	///   // ...
	/// }
	/// ```
	#[inline(always)]
	pub fn has_key(&self, key: &Term<T>) -> bool {
		match key {
			Term::Keyword(Keyword::Id) => self.id.is_some(),
			Term::Keyword(Keyword::Type) => !self.types.is_empty(),
			Term::Keyword(Keyword::Graph) => self.graph.is_some(),
			Term::Keyword(Keyword::Included) => self.included.is_some(),
			Term::Keyword(Keyword::Reverse) => !self.reverse_properties.is_empty(),
			Term::Ref(prop) => self.properties.contains(prop),
			_ => false,
		}
	}

	/// Get the identifier of the node.
	///
	/// This correspond to the `@id` field of the JSON object.
	#[inline(always)]
	pub fn id(&self) -> Option<&Reference<T>> {
		self.id.as_ref()
	}

	/// Get the node's as an IRI if possible.
	///
	/// Returns the node's IRI id if any. Returns `None` otherwise.
	#[inline(always)]
	pub fn as_iri(&self) -> Option<Iri> {
		if let Some(id) = &self.id {
			id.as_iri()
		} else {
			None
		}
	}

	/// Get the node's id, is any, as a string slice.
	///
	/// Returns `None` if the node has no `@id` field.
	#[inline(always)]
	pub fn as_str(&self) -> Option<&str> {
		match self.as_iri() {
			Some(iri) => Some(iri.into_str()),
			None => None,
		}
	}

	/// Get the list of the node's types.
	#[inline(always)]
	pub fn types(&self) -> &[Reference<T>] {
		self.types.as_ref()
	}

	/// Checks if the node has the given type.
	#[inline]
	pub fn has_type<U>(&self, ty: &U) -> bool
	where
		Reference<T>: PartialEq<U>,
	{
		for self_ty in &self.types {
			if self_ty == ty {
				return true;
			}
		}

		false
	}

	/// Tests if the node is empty.
	///
	/// It is empty is every field other than `@id` is empty.
	#[inline]
	pub fn is_empty(&self) -> bool {
		self.types.is_empty()
			&& self.graph.is_none()
			&& self.included.is_none()
			&& self.properties.is_empty()
			&& self.reverse_properties.is_empty()
	}

	/// Tests if the node is a graph object (has a `@graph` field, and optionally an `@id` field).
	/// Note that node objects may have a @graph entry,
	/// but are not considered graph objects if they include any other entries other than `@id`.
	#[inline]
	pub fn is_graph(&self) -> bool {
		self.graph.is_some()
			&& self.types.is_empty()
			&& self.included.is_none()
			&& self.properties.is_empty()
			&& self.reverse_properties.is_empty()
	}

	/// Tests if the node is a simple graph object (a graph object without `@id` field)
	#[inline(always)]
	pub fn is_simple_graph(&self) -> bool {
		self.id.is_none() && self.is_graph()
	}

	/// If the node is a graph object, get the graph.
	#[inline(always)]
	pub fn graph(&self) -> Option<&HashSet<Indexed<Object<J, T>>>> {
		self.graph.as_ref()
	}

	/// If the node is a graph object, get the mutable graph.
	#[inline(always)]
	pub fn graph_mut(&mut self) -> Option<&mut HashSet<Indexed<Object<J, T>>>> {
		self.graph.as_mut()
	}

	/// Set the graph.
	#[inline(always)]
	pub fn set_graph(&mut self, graph: Option<HashSet<Indexed<Object<J, T>>>>) {
		self.graph = graph
	}

	/// Get the set of nodes included by this node.
	///
	/// This correspond to the `@included` field in the JSON representation.
	#[inline(always)]
	pub fn included(&self) -> Option<&HashSet<Indexed<Self>>> {
		self.included.as_ref()
	}

	/// Get the mutable set of nodes included by this node.
	///
	/// This correspond to the `@included` field in the JSON representation.
	#[inline(always)]
	pub fn included_mut(&mut self) -> Option<&mut HashSet<Indexed<Self>>> {
		self.included.as_mut()
	}

	/// Set the set of nodes included by the node.
	#[inline(always)]
	pub fn set_included(&mut self, included: Option<HashSet<Indexed<Self>>>) {
		self.included = included
	}

	/// Returns a reference to the properties of the node.
	#[inline(always)]
	pub fn properties(&self) -> &Properties<J, T> {
		&self.properties
	}

	/// Returns a reference to the reverse properties of the node.
	#[inline(always)]
	pub fn reverse_properties(&self) -> &ReverseProperties<J, T> {
		&self.reverse_properties
	}

	/// Get all the objects associated to the node with the given property.
	#[inline(always)]
	pub fn get<'a, Q: ToReference<T>>(&self, prop: Q) -> Objects<J, T>
	where
		T: 'a,
	{
		self.properties.get(prop)
	}

	/// Get one of the objects associated to the node with the given property.
	///
	/// If multiple objects are attached to the node with this property, there are no guaranties
	/// on which object will be returned.
	#[inline(always)]
	pub fn get_any<'a, Q: ToReference<T>>(&self, prop: Q) -> Option<&Indexed<Object<J, T>>>
	where
		T: 'a,
	{
		self.properties.get_any(prop)
	}

	/// Associates the given object to the node through the given property.
	#[inline(always)]
	pub fn insert(&mut self, prop: Reference<T>, value: Indexed<Object<J, T>>) {
		self.properties.insert(prop, value)
	}

	/// Associates all the given objects to the node through the given property.
	///
	/// If there already exists objects associated to the given reverse property,
	/// `reverse_value` is added to the list. Duplicate objects are not removed.
	#[inline(always)]
	pub fn insert_all<Objects: Iterator<Item = Indexed<Object<J, T>>>>(
		&mut self,
		prop: Reference<T>,
		values: Objects,
	) {
		self.properties.insert_all(prop, values)
	}

	/// Associates the given node to the reverse property.
	///
	/// If there already exists nodes associated to the given reverse property,
	/// `reverse_value` is added to the list. Duplicate nodes are not removed.
	#[inline(always)]
	pub fn insert_reverse(&mut self, reverse_prop: Reference<T>, reverse_value: Indexed<Self>) {
		self.reverse_properties.insert(reverse_prop, reverse_value)
	}

	/// Associates all the given nodes to the reverse property.
	#[inline(always)]
	pub fn insert_all_reverse<Nodes: Iterator<Item = Indexed<Self>>>(
		&mut self,
		reverse_prop: Reference<T>,
		reverse_values: Nodes,
	) {
		self.reverse_properties
			.insert_all(reverse_prop, reverse_values)
	}

	/// Tests if the node is an unnamed graph object.
	///
	/// Returns `true` is the only field of the object is a `@graph` field.
	/// Returns `false` otherwise.
	#[inline]
	pub fn is_unnamed_graph(&self) -> bool {
		self.graph.is_some()
			&& self.id.is_none()
			&& self.types.is_empty()
			&& self.included.is_none()
			&& self.properties.is_empty()
			&& self.reverse_properties.is_empty()
	}

	/// Returns the node as an unnamed graph, if it is one.
	///
	/// The unnamed graph is returned as a set of indexed objects.
	/// Fails and returns itself if the node is *not* an unnamed graph.
	#[inline(always)]
	pub fn into_unnamed_graph(self) -> Result<HashSet<Indexed<Object<J, T>>>, Self> {
		if self.is_unnamed_graph() {
			Ok(self.graph.unwrap())
		} else {
			Err(self)
		}
	}
}

impl<J: JsonHash, T: Id> object::Any<J, T> for Node<J, T> {
	#[inline(always)]
	fn as_ref(&self) -> object::Ref<J, T> {
		object::Ref::Node(self)
	}
}

impl<J: JsonHash, T: Id> TryFrom<Object<J, T>> for Node<J, T> {
	type Error = Object<J, T>;

	#[inline(always)]
	fn try_from(obj: Object<J, T>) -> Result<Node<J, T>, Object<J, T>> {
		match obj {
			Object::Node(node) => Ok(node),
			obj => Err(obj),
		}
	}
}

impl<J: JsonHash, T: Id> Hash for Node<J, T> {
	#[inline]
	fn hash<H: Hasher>(&self, h: &mut H) {
		self.id.hash(h);
		self.types.hash(h);
		util::hash_set_opt(&self.graph, h);
		util::hash_set_opt(&self.included, h);
		self.properties.hash(h);
		self.reverse_properties.hash(h)
	}
}

impl<J: JsonHash + JsonClone, K: util::JsonFrom<J>, T: Id> util::AsJson<J, K> for Node<J, T> {
	fn as_json_with(&self, meta: impl Clone + Fn(Option<&J::MetaData>) -> K::MetaData) -> K {
		let mut obj = K::Object::default();

		if let Some(id) = &self.id {
			obj.insert(
				K::new_key(Keyword::Id.into_str(), meta(None)),
				id.as_json_with(meta.clone()),
			);
		}

		if !self.types.is_empty() {
			obj.insert(
				K::new_key(Keyword::Type.into_str(), meta(None)),
				self.types.as_json_with(meta.clone()),
			);
		}

		if let Some(graph) = &self.graph {
			obj.insert(
				K::new_key(Keyword::Graph.into_str(), meta(None)),
				graph.as_json_with(meta.clone()),
			);
		}

		if let Some(included) = &self.included {
			obj.insert(
				K::new_key(Keyword::Included.into_str(), meta(None)),
				included.as_json_with(meta.clone()),
			);
		}

		if !self.reverse_properties.is_empty() {
			let mut reverse = K::Object::default();
			for (key, value) in &self.reverse_properties {
				reverse.insert(
					K::new_key(key.as_str(), meta(None)),
					value.as_json_with(meta.clone()),
				);
			}

			obj.insert(
				K::new_key(Keyword::Reverse.into_str(), meta(None)),
				K::object(reverse, meta(None)),
			);
		}

		for (key, value) in &self.properties {
			obj.insert(
				K::new_key(key.as_str(), meta(None)),
				value.as_json_with(meta.clone()),
			);
		}

		K::object(obj, meta(None))
	}
}

impl<J: JsonHash + JsonClone, K: util::JsonFrom<J>, T: Id> util::AsJson<J, K>
	for HashSet<Indexed<Node<J, T>>>
{
	#[inline(always)]
	fn as_json_with(&self, meta: impl Clone + Fn(Option<&J::MetaData>) -> K::MetaData) -> K {
		let array = self
			.iter()
			.map(|value| value.as_json_with(meta.clone()))
			.collect();
		K::array(array, meta(None))
	}
}

/// Iterator through indexed nodes.
pub struct Nodes<'a, J: JsonHash, T: Id>(Option<std::slice::Iter<'a, Indexed<Node<J, T>>>>);

impl<'a, J: JsonHash, T: Id> Nodes<'a, J, T> {
	#[inline(always)]
	pub(crate) fn new(inner: Option<std::slice::Iter<'a, Indexed<Node<J, T>>>>) -> Self {
		Self(inner)
	}
}

impl<'a, J: JsonHash, T: Id> Iterator for Nodes<'a, J, T> {
	type Item = &'a Indexed<Node<J, T>>;

	#[inline(always)]
	fn next(&mut self) -> Option<&'a Indexed<Node<J, T>>> {
		match &mut self.0 {
			None => None,
			Some(it) => it.next(),
		}
	}
}