misskey_api/model/
query.rs

1use crate::model::note::Tag;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Serialize, Deserialize, Debug, Clone, Default)]
6#[serde(transparent)]
7pub struct Query<T>(pub Vec<Vec<T>>);
8
9impl<T> Query<T> {
10    /// Creates an empty [`Query`].
11    pub fn new() -> Self {
12        Query(vec![])
13    }
14
15    /// Creates [`Query`] from a vector which represents disjunction of conjunctions of `T`.
16    pub fn from_vec(vec: Vec<Vec<T>>) -> Self {
17        Query(vec)
18    }
19
20    /// Turns [`Query`] into a vector which represents disjunction of conjunctions of `T`.
21    pub fn into_vec(self) -> Vec<Vec<T>> {
22        self.0
23    }
24
25    /// Creates [`Query`] from a single element.
26    pub fn atom(x: impl Into<T>) -> Self {
27        Query(vec![vec![x.into()]])
28    }
29
30    /// Disjunction of two queries.
31    pub fn or(mut self, rhs: impl Into<Self>) -> Self {
32        let mut rhs = rhs.into();
33        self.0.extend(rhs.0.drain(..));
34        self
35    }
36
37    /// Conjunction of two queries. This operation is expensive for large rhs
38    /// and implemented just for syntactic brevity of small queries.
39    ///
40    /// For building larger queries, consider using [`Query::or`] or [`Query::from_vec`].
41    pub fn and(mut self, rhs: impl Into<Self>) -> Self
42    where
43        T: Clone,
44    {
45        let rhs: Self = rhs.into();
46        let mut result = Vec::new();
47        for and_lhs in self.0.drain(..) {
48            for and_rhs in rhs.0.clone() {
49                let mut and = and_lhs.clone();
50                and.extend(and_rhs);
51                result.push(and);
52            }
53        }
54        Query(result)
55    }
56}
57
58impl<T> From<T> for Query<T> {
59    fn from(x: T) -> Query<T> {
60        Query(vec![vec![x]])
61    }
62}
63
64// we can't `impl<T, U> From<T> for Query<U> where T: Into<U>`
65// however these `impl`s cover most use case
66
67impl From<&str> for Query<String> {
68    fn from(x: &str) -> Query<String> {
69        Query(vec![vec![x.to_string()]])
70    }
71}
72
73impl From<&str> for Query<Tag> {
74    fn from(x: &str) -> Query<Tag> {
75        Query(vec![vec![Tag(x.to_string())]])
76    }
77}