Skip to main content

rdf_types/
util.rs

1//! Small iterator adapters shared by the fallible/owned trait
2//! implementations of this crate.
3use std::marker::PhantomData;
4
5use into_owned_trait::IntoOwned;
6
7use crate::{Quad, Triple};
8
9/// Wraps a infallible iterator into one yielding
10/// [`Result<I::Item, Infallible>`](std::convert::Infallible), so it can be
11/// used where a fallible iterator is expected.
12pub struct InfallibleIterator<I>(pub I);
13
14impl<I: Iterator> Iterator for InfallibleIterator<I> {
15	type Item = Result<I::Item, std::convert::Infallible>;
16
17	fn next(&mut self) -> Option<Self::Item> {
18		self.0.next().map(Ok)
19	}
20}
21
22/// Wraps an iterator over `Triple<S, P, O>` into one over `Quad<S, P, O, G>`,
23/// leaving the graph component of every quad to `None`.
24pub struct TriplesIntoQuads<I, G>(I, PhantomData<G>);
25
26impl<I, G> TriplesIntoQuads<I, G> {
27	/// Wraps the given triples iterator.
28	pub fn new(inner: I) -> Self {
29		Self(inner, PhantomData)
30	}
31}
32
33impl<S, P, O, G, I: Iterator<Item = Triple<S, P, O>>> Iterator for TriplesIntoQuads<I, G> {
34	type Item = Quad<S, P, O, G>;
35
36	fn next(&mut self) -> Option<Self::Item> {
37		self.0.next().map(|t| t.into_quad(None))
38	}
39}
40
41/// Wraps an iterator over `Triple<R>` into one over `Triple<R::Owned>` using
42/// the `IntoOwned` trait.
43pub struct TriplesIntoOwned<I>(pub I);
44
45impl<R: IntoOwned, I: Iterator<Item = Triple<R>>> Iterator for TriplesIntoOwned<I> {
46	type Item = Triple<R::Owned>;
47
48	fn next(&mut self) -> Option<Self::Item> {
49		self.0.next().map(|t| t.map(IntoOwned::into_owned))
50	}
51}
52
53/// Wraps an iterator over `Quad<R>` into one over `Quad<R::Owned>` using the
54/// `IntoOwned` trait.
55pub struct QuadsIntoOwned<I>(pub I);
56
57impl<R: IntoOwned, I: Iterator<Item = Quad<R>>> Iterator for QuadsIntoOwned<I> {
58	type Item = Quad<R::Owned>;
59
60	fn next(&mut self) -> Option<Self::Item> {
61		self.0.next().map(|q| q.map(IntoOwned::into_owned))
62	}
63}
64
65/// Turns an `Option<I>` into an iterator, yielding the items of `I` if
66/// there is one, or nothing (`None`) otherwise.
67pub struct OptionIterator<I>(pub Option<I>);
68
69impl<I: Iterator> Iterator for OptionIterator<I> {
70	type Item = I::Item;
71
72	fn next(&mut self) -> Option<Self::Item> {
73		self.0.as_mut().and_then(I::next)
74	}
75}