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
/// A helper to build a search query.
#[derive(Debug)]
pub struct SearchQueryBuilder(String);

impl SearchQueryBuilder {
    /// Make a new [`SearchQueryBuilder`].
    pub fn new() -> Self {
        SearchQueryBuilder(String::new())
    }

    /// Add a tag.
    ///
    /// Spaces are replaced with underscores, so this only adds one tag.
    pub fn add_tag(&mut self, tag: &str) -> &mut Self {
        self.0.reserve(tag.len());
        for c in tag.chars() {
            if c == ' ' {
                self.0.push('_');
            } else {
                self.0.push(c);
            }
        }
        self.0.push(' ');

        self
    }

    /// Call [`SearchQueryBuilder::add_tag`] on each element of the given iterator.
    pub fn add_tag_iter<I, S>(&mut self, iter: I) -> &mut Self
    where
        I: Iterator<Item = S>,
        S: AsRef<str>,
    {
        for s in iter {
            self.add_tag(s.as_ref());
        }

        self
    }

    /// Take the built query string out.
    ///
    /// This resets this builder's state.
    /// The backing string is returned, so this does not preserve the string allocation.
    pub fn take_query_string(&mut self) -> String {
        if self.0.ends_with(' ') {
            self.0.pop();
        }

        std::mem::take(&mut self.0)
    }

    /// Convert into a usable query string.
    pub fn into_query_string(mut self) -> String {
        if self.0.ends_with(' ') {
            self.0.pop();
        }

        self.0
    }
}

impl From<SearchQueryBuilder> for String {
    fn from(search_query_builder: SearchQueryBuilder) -> Self {
        search_query_builder.into_query_string()
    }
}

impl Default for SearchQueryBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn build_search_query_works() {
        let query = SearchQueryBuilder::new()
            .add_tag("deep space waifu")
            .take_query_string();
        assert_eq!(query, "deep_space_waifu");
    }
}