json_ld_core/flattening/
environment.rs1use crate::{Id, ValidId, ValidVocabularyId, VocabularyId};
2use rdf_types::{Generator, Vocabulary};
3use std::collections::HashMap;
4use std::hash::Hash;
5
6pub struct Environment<'n, N: Vocabulary, G> {
7 vocabulary: &'n mut N,
8 generator: G,
9 map: HashMap<N::BlankId, ValidVocabularyId<N>>,
10}
11
12impl<'n, N: Vocabulary, G> Environment<'n, N, G> {
13 pub fn new(vocabulary: &'n mut N, generator: G) -> Self {
14 Self {
15 vocabulary,
16 generator,
17 map: HashMap::new(),
18 }
19 }
20}
21
22impl<'n, V: Vocabulary, G: Generator<V>> Environment<'n, V, G>
23where
24 V::Iri: Clone,
25 V::BlankId: Clone + Hash + Eq,
26{
27 pub fn assign(&mut self, blank_id: V::BlankId) -> ValidId<V::Iri, V::BlankId> {
28 use std::collections::hash_map::Entry;
29 match self.map.entry(blank_id) {
30 Entry::Occupied(entry) => entry.get().clone(),
31 Entry::Vacant(entry) => {
32 let id = self.generator.next(self.vocabulary);
33 entry.insert(id.clone());
34 id
35 }
36 }
37 }
38
39 pub fn assign_node_id(&mut self, r: Option<&VocabularyId<V>>) -> Id<V::Iri, V::BlankId> {
40 match r {
41 Some(Id::Valid(ValidId::Blank(id))) => self.assign(id.clone()).into(),
42 Some(r) => r.clone(),
43 None => self.next().into(),
44 }
45 }
46
47 #[allow(clippy::should_implement_trait)]
48 pub fn next(&mut self) -> ValidId<V::Iri, V::BlankId> {
49 self.generator.next(self.vocabulary)
50 }
51}