rdftk_core 0.5.6

This crate provides the core RDF data model; concrete implementations for Statements and Literals, along with a Resource type that provides a builder-like experience for models.
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
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
/*!
The [`Graph`] type implements an optionally named collection of statements.

# Example

```rust
use rdftk_core::model::graph::Graph;
use rdftk_core::model::statement::Statement;

fn simple_graph_writer(graph: &Graph)
{
    for statement in graph.statements() {
        println!("{}", statement);
    }
}
```
*/

use crate::error::Error;
use crate::model::features::{Featured, FEATURE_GRAPH_DUPLICATES, FEATURE_RDF_STAR};
use crate::model::statement::{BlankNode, ObjectNode, Statement, SubjectNode};
use bimap::BiHashMap;
use rdftk_iri::{Iri, IriExtra, Name, QName};
use rdftk_names::{dc, foaf, owl, rdf, rdfs, skos, xsd};
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Display, Formatter};
use std::hash::Hash;
use std::iter::FusedIterator;
use std::str::FromStr;

// ------------------------------------------------------------------------------------------------
// Public Types
// ------------------------------------------------------------------------------------------------

///
/// This type denotes the identifier for a graph in a data set; a graph name MUST be either an Iri
/// or a blank node.
///
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum GraphName {
    BNode(BlankNode),
    Iri(Iri),
}

// ------------------------------------------------------------------------------------------------

///
/// Implementation of a mapping from a prefix `Name` to an `Iri`. Prefix mappings are commonly used
/// in the serialization of graphs.
///
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PrefixMapping {
    map: BiHashMap<Option<Name>, Iri>,
}

// ------------------------------------------------------------------------------------------------

///
/// A graph is an unordered list of statements and may include duplicates.
/// Note that this trait represents an immutable graph, a type should also implement the
/// `MutableGraph` trait for mutation.
///
#[derive(Clone, Debug, Default)]
pub struct Graph {
    name: Option<GraphName>,
    statements: Statements,
    mappings: PrefixMapping,
}

// ------------------------------------------------------------------------------------------------
// Private Types
// ------------------------------------------------------------------------------------------------

#[derive(Clone, Debug)]
enum Statements {
    Unique(HashSet<Statement>),
    NonUnique(Vec<Statement>),
}

#[derive(Debug)]
enum StatementIter<'a> {
    Unique(std::collections::hash_set::Iter<'a, Statement>),
    NonUnique(std::slice::Iter<'a, Statement>),
}

// ------------------------------------------------------------------------------------------------
// Implementations ❱ Graph Names
// ------------------------------------------------------------------------------------------------

impl Display for GraphName {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match &self {
                Self::BNode(node) => format!("_:{}", node),
                Self::Iri(iri) => format!("<{}>", iri),
            }
        )
    }
}

impl From<Name> for GraphName {
    fn from(name: Name) -> Self {
        Self::BNode(BlankNode::from(name))
    }
}

impl From<&Name> for GraphName {
    fn from(name: &Name) -> Self {
        Self::BNode(BlankNode::from(name))
    }
}

impl From<BlankNode> for GraphName {
    fn from(name: BlankNode) -> Self {
        Self::BNode(name)
    }
}

impl From<&BlankNode> for GraphName {
    fn from(name: &BlankNode) -> Self {
        Self::BNode(name.clone())
    }
}

impl From<Iri> for GraphName {
    fn from(name: Iri) -> Self {
        Self::Iri(name)
    }
}

impl From<&Iri> for GraphName {
    fn from(name: &Iri) -> Self {
        Self::Iri(name.clone())
    }
}

impl From<SubjectNode> for GraphName {
    fn from(value: SubjectNode) -> Self {
        match value {
            SubjectNode::Blank(v) => Self::BNode(v.clone()),
            SubjectNode::Resource(v) => Self::Iri(v.clone()),
            _ => unreachable!(),
        }
    }
}

impl GraphName {
    ///
    /// Construct a new graph name, as a blank node with a randomly assigned name.
    ///
    pub fn blank() -> Self {
        Self::BNode(BlankNode::generate())
    }

    ///
    /// Construct a new graph name, as a blank node with the specified name.
    ///
    pub fn blank_named<S>(name: S) -> Result<Self, Error>
    where
        S: AsRef<str>,
    {
        Ok(Self::BNode(BlankNode::from_str(name.as_ref())?))
    }

    ///
    /// Construct a new graph name, with an Iri naming a resource.
    ///
    pub fn named(name: Iri) -> Self {
        Self::Iri(name)
    }

    ///
    /// Return `true` if this graph name is a blank node, else `false`.
    ///
    pub fn is_blank(&self) -> bool {
        matches!(self, Self::BNode(_))
    }

    ///
    /// Return a blank node string, if `self.is_blank()`, else `None`.
    ///
    pub fn as_blank(&self) -> Option<&BlankNode> {
        match &self {
            Self::BNode(s) => Some(s),
            _ => None,
        }
    }

    ///
    /// Return `true` if this graph name is an Iri, else `false`.
    ///
    pub fn is_iri(&self) -> bool {
        matches!(self, Self::Iri(_))
    }

    ///
    /// Return a named node Iri, if `self.is_iri()`, else `None`.
    ///
    pub fn as_iri(&self) -> Option<&Iri> {
        match &self {
            Self::Iri(u) => Some(u),
            _ => None,
        }
    }
}

// ------------------------------------------------------------------------------------------------
// Implementations ❱ Prefix Mappings
// ------------------------------------------------------------------------------------------------

impl PrefixMapping {
    // --------------------------------------------------------------------------------------------
    // Constructors
    // --------------------------------------------------------------------------------------------

    pub fn common() -> Self {
        Self::default()
            .with_dc_elements()
            .with_owl()
            .with_rdf()
            .with_rdfs()
            .with_skos()
            .with_xsd()
    }

    ///
    /// Construct a new mapping instance with the provided default namespace.
    ///
    pub fn with_default(self, iri: Iri) -> Self
    where
        Self: Sized,
    {
        let mut mut_self = self;
        mut_self.set_default_namespace(iri);
        mut_self
    }

    ///
    /// Include the common "dc::terms" mapping.
    ///
    pub fn with_dc_terms(self) -> Self
    where
        Self: Sized,
    {
        let mut mut_self = self;
        mut_self.insert_dc_terms();
        mut_self
    }

    ///
    /// Include the common "dc::elements" mapping.
    ///
    pub fn with_dc_elements(self) -> Self
    where
        Self: Sized,
    {
        let mut mut_self = self;
        mut_self.insert_dc_elements();
        mut_self
    }

    ///
    /// Include the common "foaf" mapping.
    ///
    pub fn with_foaf(self) -> Self
    where
        Self: Sized,
    {
        let mut mut_self = self;
        mut_self.insert_foaf();
        mut_self
    }

    ///
    /// Include the common "owl" mapping.
    ///
    pub fn with_owl(self) -> Self
    where
        Self: Sized,
    {
        let mut mut_self = self;
        mut_self.insert_owl();
        mut_self
    }

    ///
    /// Include the common "rdf" mapping.
    ///
    pub fn with_rdf(self) -> Self
    where
        Self: Sized,
    {
        let mut mut_self = self;
        mut_self.insert_rdf();
        mut_self
    }

    ///
    /// Include the common "rdfs" mapping.
    ///
    pub fn with_rdfs(self) -> Self
    where
        Self: Sized,
    {
        let mut mut_self = self;
        mut_self.insert_rdfs();
        mut_self
    }

    ///
    /// Include the common "xsd" (XML Schema Data types) mapping.
    ///
    pub fn with_xsd(self) -> Self
    where
        Self: Sized,
    {
        let mut mut_self = self;
        mut_self.insert_xsd();
        mut_self
    }

    ///
    /// Include the common "skos"  mapping.
    ///
    pub fn with_skos(self) -> Self
    where
        Self: Sized,
    {
        let mut mut_self = self;
        mut_self.insert_skos();
        mut_self
    }

    pub fn with(self, prefix: Name, iri: Iri) -> Self
    where
        Self: Sized,
    {
        let mut mut_self = self;
        mut_self.insert(prefix, iri);
        mut_self
    }

    // --------------------------------------------------------------------------------------------
    // Collection methods
    // --------------------------------------------------------------------------------------------

    ///
    /// Returns `true` if there are no mappings in this instance, else `false`.
    ///
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    ///
    /// Return the number of mappings in this instance.
    ///
    pub fn len(&self) -> usize {
        self.map.len()
    }

    ///
    /// Get the default namespace mapping, if present.
    ///
    pub fn get_default_namespace(&self) -> Option<&Iri> {
        self.map.get_by_left(&None)
    }

    ///
    /// Set the default namespace mapping.
    ///
    pub fn set_default_namespace(&mut self, iri: Iri) {
        let _ = self.map.insert(None, iri);
    }

    pub fn remove_default_namespace(&mut self) {
        let _ = self.map.remove_by_left(&None);
    }

    ///
    /// Get the namespace Iri associated with this provided prefix, if present.
    ///
    pub fn get_namespace(&self, prefix: &Name) -> Option<&Iri> {
        self.map.get_by_left(&Some(prefix.clone()))
    }

    ///
    /// Get the prefix associated with this provided namespace URI, if present.
    ///
    pub fn get_prefix(&self, namespace: &Iri) -> Option<&Option<Name>> {
        self.map.get_by_right(namespace)
    }

    ///
    /// Return an iterator over the contained mappings.
    ///
    pub fn mappings<'a>(&'a self) -> Box<dyn Iterator<Item = (&'a Option<Name>, &'a Iri)> + 'a> {
        Box::new(self.map.iter())
    }

    ///
    /// Insert a mapping from the prefix string to the namespace Iri.
    ///
    pub fn insert(&mut self, prefix: Name, iri: Iri) {
        let _ = self.map.insert(Some(prefix), iri);
    }

    pub fn insert_owl(&mut self) {
        self.insert(owl::default_prefix().clone(), owl::namespace().clone());
    }

    pub fn insert_rdf(&mut self) {
        self.insert(rdf::default_prefix().clone(), rdf::namespace().clone());
    }

    pub fn insert_rdfs(&mut self) {
        self.insert(rdfs::default_prefix().clone(), rdfs::namespace().clone());
    }

    pub fn insert_xsd(&mut self) {
        self.insert(xsd::default_prefix().clone(), xsd::namespace().clone());
    }

    pub fn insert_foaf(&mut self) {
        self.insert(foaf::default_prefix().clone(), foaf::namespace().clone());
    }

    pub fn insert_dc_elements(&mut self) {
        self.insert(
            dc::elements::default_prefix().clone(),
            dc::elements::namespace().clone(),
        );
    }

    pub fn insert_dc_terms(&mut self) {
        self.insert(
            dc::terms::default_prefix().clone(),
            dc::terms::namespace().clone(),
        );
    }

    pub fn insert_skos(&mut self) {
        self.insert(skos::default_prefix().clone(), skos::namespace().clone());
    }

    pub fn insert_skos_xl(&mut self) {
        self.insert(
            skos::xl::default_prefix().clone(),
            skos::xl::namespace().clone(),
        );
    }

    pub fn insert_skos_iso(&mut self) {
        self.insert(
            skos::iso::default_prefix().clone(),
            skos::iso::namespace().clone(),
        );
    }

    ///
    /// Remove a mapping for the provided prefix. This operation has no effect if no mapping is present.
    ///
    pub fn remove(&mut self, prefix: &Name) {
        let _ = self.map.remove_by_left(&Some(prefix.clone()));
    }

    ///
    /// Remove all mappings from this instance.
    ///
    pub fn clear(&mut self) {
        self.map.clear();
    }

    // --------------------------------------------------------------------------------------------
    // QName Mapping
    // --------------------------------------------------------------------------------------------

    ///
    /// Expand a qname into an Iri, if possible.
    ///
    pub fn expand(&self, qname: &QName) -> Option<Iri> {
        let prefix = if let Some(prefix) = qname.prefix() {
            self.get_namespace(prefix)
        } else {
            self.get_default_namespace()
        };
        match prefix {
            None => None,
            Some(namespace) => namespace.make_name(qname.name().clone()),
        }
    }

    ///
    /// Compress an Iri into a qname, if possible.
    ///
    pub fn compress(&self, iri: &Iri) -> Option<QName> {
        let (iri, name) = if let Some((iri, name)) = iri.split() {
            (iri, name)
        } else {
            return None;
        };
        match self.get_prefix(&iri) {
            None => None,
            Some(None) => Some(QName::new_unqualified(name).unwrap()),
            Some(Some(prefix)) => Some(QName::new(prefix.clone(), name).unwrap()),
        }
    }
}

// ------------------------------------------------------------------------------------------------
// Implementations ❱ Graphs
// ------------------------------------------------------------------------------------------------

impl Featured for Graph {
    fn supports_feature(&self, feature: &Iri) -> bool {
        (*feature == *FEATURE_GRAPH_DUPLICATES && self.statements.is_unique())
            || *feature == *FEATURE_RDF_STAR
    }
}

impl From<Statement> for Graph {
    fn from(value: Statement) -> Self {
        Self::from_iter([value])
    }
}

impl From<Vec<Statement>> for Graph {
    fn from(value: Vec<Statement>) -> Self {
        Graph::from_iter(value)
    }
}

impl FromIterator<Statement> for Graph {
    fn from_iter<T: IntoIterator<Item = Statement>>(iter: T) -> Self {
        Self {
            statements: Statements::NonUnique(iter.into_iter().collect()),
            ..Default::default()
        }
    }
}

impl Graph {
    // --------------------------------------------------------------------------------------------
    // Constructors
    // --------------------------------------------------------------------------------------------

    pub fn named<N>(name: N) -> Self
    where
        N: Into<GraphName>,
    {
        Self {
            name: Some(name.into()),
            ..Default::default()
        }
    }

    pub fn unique() -> Self {
        Self {
            statements: Statements::Unique(Default::default()),
            ..Default::default()
        }
    }

    pub fn unique_named<N>(name: N) -> Self
    where
        N: Into<GraphName>,
    {
        Self {
            name: Some(name.into()),
            ..Self::unique()
        }
    }

    pub fn with_mappings(self, mappings: PrefixMapping) -> Self {
        Self { mappings, ..self }
    }

    pub fn with_statements(self, statements: Vec<Statement>) -> Self {
        Self {
            statements: match self.statements {
                Statements::Unique(_) => Statements::Unique(HashSet::from_iter(statements)),
                Statements::NonUnique(_) => Statements::NonUnique(statements),
            },
            ..self
        }
    }

    // --------------------------------------------------------------------------------------------
    // Cardinality
    // --------------------------------------------------------------------------------------------

    ///
    /// Returns `true` if there are no statements in this graph, else `false`.
    ///
    pub fn is_empty(&self) -> bool {
        self.statements.is_empty()
    }

    ///
    /// Return the number of statements in this graph.
    ///
    pub fn len(&self) -> usize {
        self.statements.len()
    }

    // --------------------------------------------------------------------------------------------
    // Name
    // --------------------------------------------------------------------------------------------

    ///
    /// Returns `true` if this graph instance has a name.
    ///
    pub fn is_named(&self) -> bool {
        self.name().is_some()
    }

    ///
    /// Return the name of this graph.
    ///
    pub fn name(&self) -> Option<&GraphName> {
        self.name.as_ref()
    }

    ///
    /// Set the name of this graph.
    ///
    pub fn set_name(&mut self, name: GraphName) {
        self.name = Some(name);
    }

    ///
    /// Remove the name of this graph.
    ///
    pub fn unset_name(&mut self) {
        self.name = None;
    }

    // --------------------------------------------------------------------------------------------
    // Query
    // --------------------------------------------------------------------------------------------

    ///
    /// Returns `true` if this graph contains any statement with the provided subject, else `false`.
    ///
    pub fn contains_subject(&self, subject: &SubjectNode) -> bool {
        self.statements.iter().any(|st| st.subject() == subject)
    }

    ///
    /// Returns `true` if this graph contains the provided statement, else `false`.
    ///
    pub fn contains(&self, statement: &Statement) -> bool {
        !self
            .matches(
                Some(statement.subject()),
                Some(statement.predicate()),
                Some(statement.object()),
            )
            .is_empty()
    }

    ///
    /// Returns `true` if this graph contains the any statement with the provided subject,
    /// predicate, and object, else `false`.
    ///
    pub fn contains_all(
        &self,
        subject: &SubjectNode,
        predicate: &Iri,
        object: &ObjectNode,
    ) -> bool {
        !self
            .matches(Some(subject), Some(predicate), Some(object))
            .is_empty()
    }

    ///
    /// Returns `true` if this graph contains the any statement with the provided subject,
    /// predicate, and object, else `false`.
    ///
    pub fn matches(
        &self,
        subject: Option<&SubjectNode>,
        predicate: Option<&Iri>,
        object: Option<&ObjectNode>,
    ) -> HashSet<&Statement> {
        self.statements
            .iter()
            .filter(|st| {
                (subject.is_some() && st.subject() == subject.unwrap())
                    && (predicate.is_some() && st.predicate() == predicate.unwrap())
                    && (object.is_some() && st.object() == object.unwrap())
            })
            .collect()
    }

    // --------------------------------------------------------------------------------------------
    // Iterators
    // --------------------------------------------------------------------------------------------

    ///
    /// Return an iterator over all the statements in the graph.
    ///
    pub fn statements(&self) -> impl Iterator<Item = &Statement> {
        self.statements.iter()
    }

    ///
    /// Return a set of all subjects in the graph, note that this is a set so that it removes
    /// duplicates.
    ///
    pub fn subjects(&self) -> HashSet<&SubjectNode> {
        self.statements.iter().map(|st| st.subject()).collect()
    }

    ///
    /// Return a set of all subjects that are not blank nodes
    ///
    pub fn node_subjects(&self) -> HashSet<&SubjectNode> {
        self.subjects()
            .into_iter()
            .filter(|s| !s.is_blank())
            .collect()
    }

    ///
    /// Return a set of all subjects that are blank nodes
    ///
    pub fn blank_node_subjects(&self) -> HashSet<&SubjectNode> {
        self.subjects()
            .into_iter()
            .filter(|s| s.is_blank())
            .collect()
    }

    ///
    /// Return a set of all predicate in the graph, note that this is a set so that it removes
    /// duplicates.
    ///
    pub fn predicates(&self) -> HashSet<&Iri> {
        self.statements.iter().map(|st| st.predicate()).collect()
    }

    ///
    /// Return a set of all predicate referenced by the provided subject in graph, note that
    /// this is a set so that it removes duplicates.
    ///
    pub fn predicates_for(&self, subject: &SubjectNode) -> HashSet<&Iri> {
        self.statements
            .iter()
            .filter_map(|st| {
                if st.subject() == subject {
                    Some(st.predicate())
                } else {
                    None
                }
            })
            .collect()
    }

    ///
    /// Return a set of all objects in the graph, note that this is a set so that it removes
    /// duplicates.
    ///
    pub fn objects(&self) -> HashSet<&ObjectNode> {
        self.statements.iter().map(|st| st.object()).collect()
    }

    ///
    /// Return a set of all objects referenced by the provided subject and predicate in the graph,
    /// note that this is a set so that it removes duplicates.
    ///
    pub fn objects_for(&self, subject: &SubjectNode, predicate: &Iri) -> HashSet<&ObjectNode> {
        self.statements
            .iter()
            .filter_map(|st| {
                if st.subject() == subject && st.predicate() == predicate {
                    Some(st.object())
                } else {
                    None
                }
            })
            .collect()
    }

    // --------------------------------------------------------------------------------------------
    // Namespace Management
    // --------------------------------------------------------------------------------------------

    ///
    /// Returns the set of prefix mappings held by the graph.
    ///
    pub fn prefix_mappings(&self) -> &PrefixMapping {
        &self.mappings
    }

    ///
    /// Set the prefix mappings held by the graph.
    ///
    pub fn set_prefix_mappings(&mut self, mappings: PrefixMapping) {
        self.mappings = mappings;
    }

    // --------------------------------------------------------------------------------------------
    // Mutators
    // --------------------------------------------------------------------------------------------

    ///
    /// Insert a new statement into the graph.
    ///
    pub fn insert(&mut self, statement: Statement) {
        self.statements.insert(statement);
    }

    ///
    /// Merge another graph into this one. Note that the graphs are required to have the same
    /// implementation type based in the type qualifiers for `StatementIter`.
    ///
    pub fn merge(&mut self, other: &Self) {
        other.statements().for_each(|st| self.insert(st.clone()))
    }

    ///
    /// Remove any duplicates within the graph, replacing any number of identical statements with
    /// just one. This will return a list of all statements removed.
    ///
    /// This method does nothing if this graph has does not support the feature
    /// `FEATURE_GRAPH_DUPLICATES` and will therefore always return an empty list.
    ///
    pub fn dedup(&mut self) -> Vec<Statement> {
        if self.statements.is_unique() {
            Default::default()
        } else {
            let (keep, discard) = self.statements.iter().fold(
                (HashSet::<Statement>::default(), Vec::default()),
                |(mut keep, mut discard), st| {
                    if keep.contains(st) {
                        discard.push(st.clone());
                    } else {
                        let _ = keep.insert(st.clone());
                    }
                    (keep, discard)
                },
            );
            self.statements = Statements::NonUnique(Vec::from_iter(keep));
            discard
        }
    }

    ///
    /// Remove any statement that matches the provided. If a graph has duplicates this method does
    /// not differentiate between them.
    ///
    pub fn remove(&mut self, statement: &Statement) {
        self.statements.remove(statement);
    }

    ///
    /// Remove all statements from this graph that have the provided subject.
    ///
    pub fn remove_all_for(&mut self, subject: &SubjectNode) -> Vec<Statement> {
        let (keep, discard) = self.statements.iter().fold(
            (Default::default(), Default::default()),
            |(mut keep, mut discard): (Vec<Statement>, Vec<Statement>), st| {
                if st.subject() == subject {
                    keep.push(st.clone());
                } else {
                    discard.push(st.clone());
                }
                (keep, discard)
            },
        );
        if self.statements.is_unique() {
            self.statements = Statements::Unique(HashSet::from_iter(keep));
        } else {
            self.statements = Statements::NonUnique(keep);
        }

        discard
    }

    ///
    /// Remove all statements from this graph.
    ///
    pub fn clear(&mut self) {
        self.statements.clear()
    }

    ///
    /// Replace all blank nodes with new, unique Iris. This creates a new graph and leaves the initial
    /// graph unchanged. The base Iri is used to create identifiers, it's path will be replaced
    /// entirely by a well-known format.
    ///
    /// For example, given the following input graph with blank nodes:
    ///
    /// ```ttl
    /// <https://example.org/p/me> <https://example.org/v/name> _:B0f21 .
    /// _:B0f21 <https://example.org/v/firstName> "My" .
    /// _:B0f21 <https://example.org/v/lastName> "Name" .
    /// ```
    ///
    /// the call to `skolemize`,
    ///
    /// ```rust,ignore
    /// let base = Iri::from_str("https://example.com/me").unwrap();
    /// graph.skolemize(&base)
    /// ```
    ///
    /// results in a new graph containing replacement IRIs.
    ///
    /// ```ttl
    /// <https://example.org/p/me>
    ///   <https://example.org/v/name>
    ///   <https://example.com/.well-known/genid/62D22842-0D24-4911-AE7D-DF4DE06FD62F> .
    /// <https://example.com/.well-known/genid/62D22842-0D24-4911-AE7D-DF4DE06FD62F>
    ///   <https://example.org/v/firstName>
    ///   "My" .
    /// <https://example.com/.well-known/genid/62D22842-0D24-4911-AE7D-DF4DE06FD62F>
    ///   <https://example.org/v/lastName>
    ///   "Name" .
    /// ```
    pub fn skolemize(self, base: &Iri) -> Result<Self, Error> {
        let mut mapping: HashMap<BlankNode, Iri> = Default::default();

        let mut new_graph = Self::default();

        for statement in self.statements() {
            let mut new_statement = statement.clone();
            if let Some(blank) = new_statement.subject().as_blank() {
                if !mapping.contains_key(blank) {
                    let _ = mapping.insert(blank.clone(), base.genid()?);
                }
                let name = mapping.get(blank).unwrap().clone();
                let subject = SubjectNode::from(name);
                new_statement.set_subject(subject);
            }
            if let Some(blank) = new_statement.object().as_blank() {
                if !mapping.contains_key(blank) {
                    let _ = mapping.insert(blank.clone(), base.genid()?);
                }
                let name = mapping.get(blank).unwrap().clone();
                let object = ObjectNode::from(name);
                new_statement.set_object(object);
            }
            new_graph.insert(new_statement);
        }

        Ok(new_graph)
    }
}

// ------------------------------------------------------------------------------------------------
// Implementations > Statements Enum
// ------------------------------------------------------------------------------------------------

impl Default for Statements {
    fn default() -> Self {
        Self::NonUnique(Default::default())
    }
}

impl Statements {
    fn len(&self) -> usize {
        match self {
            Self::Unique(vs) => vs.len(),
            Self::NonUnique(vs) => vs.len(),
        }
    }

    fn is_empty(&self) -> bool {
        match self {
            Self::Unique(vs) => vs.is_empty(),
            Self::NonUnique(vs) => vs.is_empty(),
        }
    }

    fn insert(&mut self, st: Statement) -> bool {
        match self {
            Self::Unique(vs) => vs.insert(st),
            Self::NonUnique(vs) => {
                vs.push(st);
                true
            }
        }
    }

    fn remove(&mut self, st: &Statement) -> bool {
        match self {
            Self::Unique(vs) => vs.remove(st),
            Self::NonUnique(vs) => {
                vs.retain(|e| e != st);
                true
            }
        }
    }

    fn clear(&mut self) {
        match self {
            Self::Unique(vs) => vs.clear(),
            Self::NonUnique(vs) => vs.clear(),
        }
    }

    fn is_unique(&self) -> bool {
        matches!(self, Self::Unique(_))
    }

    fn iter(&self) -> StatementIter<'_> {
        match self {
            Self::Unique(vs) => StatementIter::Unique(vs.iter()),
            Self::NonUnique(vs) => StatementIter::NonUnique(vs.iter()),
        }
    }

    #[allow(dead_code)]
    fn into_unique(self) -> Self {
        match self {
            Statements::Unique(_) => self,
            Statements::NonUnique(vs) => Statements::Unique(HashSet::from_iter(vs)),
        }
    }

    #[allow(dead_code)]
    fn into_non_unique(self) -> Self {
        match self {
            Statements::NonUnique(_) => self,
            Statements::Unique(vs) => Statements::NonUnique(Vec::from_iter(vs)),
        }
    }
}

// ------------------------------------------------------------------------------------------------
// Implementations > Statement Iterator
// ------------------------------------------------------------------------------------------------

impl<'a> Iterator for StatementIter<'a> {
    type Item = &'a Statement;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            StatementIter::Unique(vs) => vs.next(),
            StatementIter::NonUnique(vs) => vs.next(),
        }
    }
}

impl ExactSizeIterator for StatementIter<'_> {
    fn len(&self) -> usize {
        match self {
            StatementIter::Unique(vs) => vs.len(),
            StatementIter::NonUnique(vs) => vs.len(),
        }
    }
}

impl FusedIterator for StatementIter<'_> {}