Skip to main content

rdfx/pattern/
resource_or_variable.rs

1use crate::vocabulary::EmbedIntoVocabulary;
2
3/// Resource or variable.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6pub enum ResourceOrVar<T, X> {
7    Resource(T),
8    Var(X),
9}
10
11impl<T: crate::__seal::Sealed, X> crate::__seal::Sealed for ResourceOrVar<T, X> {}
12impl<T: crate::IsSubject, X> crate::IsSubject for ResourceOrVar<T, X> {}
13impl<T: crate::IsPredicate, X> crate::IsPredicate for ResourceOrVar<T, X> {}
14impl<T: crate::IsObject, X> crate::IsObject for ResourceOrVar<T, X> {}
15impl<T: crate::IsGraph, X> crate::IsGraph for ResourceOrVar<T, X> {}
16
17impl<T, X> ResourceOrVar<T, X> {
18    pub fn map<U>(self, f: impl Fn(T) -> U) -> ResourceOrVar<U, X> {
19        match self {
20            Self::Resource(t) => ResourceOrVar::Resource(f(t)),
21            Self::Var(x) => ResourceOrVar::Var(x),
22        }
23    }
24
25    pub const fn as_ref(&self) -> ResourceOrVar<&T, &X> {
26        match self {
27            Self::Resource(t) => ResourceOrVar::Resource(t),
28            Self::Var(x) => ResourceOrVar::Var(x),
29        }
30    }
31
32    pub fn is_id_or(&self, f: impl FnOnce(&X) -> bool) -> bool {
33        match self {
34            Self::Resource(_) => true,
35            Self::Var(x) => f(x),
36        }
37    }
38}
39
40impl<T, X> From<T> for ResourceOrVar<T, X> {
41    fn from(value: T) -> Self {
42        Self::Resource(value)
43    }
44}
45
46impl<V, T: EmbedIntoVocabulary<V>, X> EmbedIntoVocabulary<V> for ResourceOrVar<T, X> {
47    type Embedded = ResourceOrVar<T::Embedded, X>;
48
49    fn embed_into_vocabulary(self, vocabulary: &mut V) -> Self::Embedded {
50        match self {
51            Self::Resource(term) => ResourceOrVar::Resource(term.embed_into_vocabulary(vocabulary)),
52            Self::Var(x) => ResourceOrVar::Var(x),
53        }
54    }
55}