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
//! Tools for constructing [filter expressions], as used by e.g. the `find` command.
//!
//! [filter expressions]: https://www.musicpd.org/doc/html/protocol.html#filters

use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::ops::Not;

use crate::command::{escape_argument, Argument};

/// Special tag which checks *all* tag types.
///
/// Provided here to avoid typos.
pub static ANY: &str = "any";

/// Magic value which checks for the absence of the tag with which it is used.
///
/// Provided here to have more apparent meaning than a simple empty string literal.
pub static IS_ABSENT: &str = "";

/// A [filter expression].
///
/// [filter expression]: https://www.musicpd.org/doc/html/protocol.html#filters
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Filter(FilterType);

/// Operators which can be used in filter expressions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Operator {
    /// Equality (`==`)
    Equal,
    /// Negated equality (`!=`)
    NotEqual,
    /// Substring matching (`contains`)
    Contain,
    /// Perl-style regex matching (`=~`)
    Match,
    /// Negated Perl-style regex matching (`!~`)
    NotMatch,
}

/// Error returned when attempting to construct invalid filter expressions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FilterError {
    /// Attempted to filter for an empty tag.
    EmptyTag,
}

impl Error for FilterError {}

impl fmt::Display for FilterError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FilterError::EmptyTag => write!(f, "Attmpted to construct a filter for an empty tag"),
        }
    }
}

/// Internal filter variant type
#[derive(Clone, Debug, PartialEq, Eq)]
enum FilterType {
    Tag {
        tag: Cow<'static, str>,
        operator: Operator,
        value: Cow<'static, str>,
    },
    Not(Box<FilterType>),
    And(Vec<FilterType>),
}

impl Filter {
    /// Create a filter which selects on the given `tag`, using the given [`operator`], for the
    /// given `value`.
    ///
    /// An error is returned when the given `tag` is empty, but `value` may be empty (which results
    /// in the filter only matching if the `tag` is **not** present, see also [`IS_ABSENT`]).
    ///
    /// The magic value [`any`] checks for the value in any tag.
    ///
    /// ```
    /// use mpd_protocol::command::Argument;
    /// use mpd_protocol::filter::{FilterError, Filter, Operator};
    ///
    /// assert_eq!(
    ///     Filter::tag("artist", Operator::Equal, "foo\'s bar\"").unwrap().render(),
    ///     "(artist == \"foo\\\'s bar\\\"\")"
    /// );
    /// assert_eq!(
    ///     Filter::tag("", Operator::Equal, "").unwrap_err(),
    ///     FilterError::EmptyTag
    /// );
    /// ```
    ///
    /// [`operator`]: enum.Operator.html
    /// [`IS_ABSENT`]: static.iS_ABSENT.html
    /// [`any`]: static.ANY.html
    pub fn tag(
        tag: impl Into<Cow<'static, str>>,
        operator: Operator,
        value: impl Into<Cow<'static, str>>,
    ) -> Result<Self, FilterError> {
        let tag = tag.into();
        if tag.is_empty() {
            Err(FilterError::EmptyTag)
        } else {
            Ok(Filter(FilterType::Tag {
                tag,
                operator,
                value: value.into(),
            }))
        }
    }

    /// Create a filter which checks where the given `tag` is equal to the given `value`.
    ///
    /// Similar to [`tag`], but always checks for equality and panics when the given `tag` is
    /// invalid.
    ///
    /// ```
    /// use mpd_protocol::{Filter, command::Argument};
    ///
    /// assert_eq!(
    ///     Filter::equal("artist", "hello world").render(),
    ///     "(artist == \"hello world\")"
    /// );
    /// ```
    ///
    /// [`tag`]: #method.tag
    pub fn equal(tag: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>) -> Self {
        Filter::tag(tag, Operator::Equal, value).expect("Invalid filter expression")
    }

    /// Negate the filter.
    ///
    /// You can also use the negation operator (`!`) if you prefer to negate at the start of an
    /// expression.
    ///
    /// ```
    /// use mpd_protocol::{Filter, command::Argument};
    ///
    /// assert_eq!(
    ///     Filter::equal("artist", "hello").negate().render(),
    ///     "(!(artist == \"hello\"))"
    /// );
    /// ```
    pub fn negate(mut self) -> Self {
        self.0 = FilterType::Not(Box::new(self.0));
        self
    }

    /// Chain the given filter onto this one with an `AND`.
    ///
    /// Automatically flattens nested `AND` conditions.
    ///
    /// ```
    /// use mpd_protocol::{Filter, command::Argument};
    ///
    /// assert_eq!(
    ///     Filter::equal("artist", "foo").and(Filter::equal("album", "bar")).render(),
    ///     "((artist == \"foo\") AND (album == \"bar\"))"
    /// );
    /// ```
    pub fn and(self, other: Self) -> Self {
        let mut out = match self.0 {
            FilterType::And(inner) => inner,
            condition => {
                let mut out = Vec::with_capacity(2);
                out.push(condition);
                out
            }
        };

        match other.0 {
            FilterType::And(inner) => {
                for c in inner {
                    out.push(c);
                }
            }
            condition => out.push(condition),
        }

        Self(FilterType::And(out))
    }
}

impl Argument for Filter {
    fn render(self) -> Cow<'static, str> {
        Cow::Owned(self.0.render())
    }
}

impl Not for Filter {
    type Output = Self;

    fn not(self) -> Self::Output {
        self.negate()
    }
}

impl Operator {
    fn to_str(self) -> &'static str {
        match self {
            Operator::Equal => "==",
            Operator::NotEqual => "!=",
            Operator::Contain => "contains",
            Operator::Match => "=~",
            Operator::NotMatch => "!~",
        }
    }
}

impl FilterType {
    fn render(self) -> String {
        match self {
            FilterType::Tag {
                tag,
                operator,
                value,
            } => format!(
                "({} {} \"{}\")",
                tag,
                operator.to_str(),
                escape_argument(&value)
            ),
            FilterType::Not(inner) => format!("(!{})", inner.render()),
            FilterType::And(inner) => {
                assert!(inner.len() >= 2);
                let inner = inner.into_iter().map(|s| s.render()).collect::<Vec<_>>();

                // Wrapping parens
                let mut capacity = 2;
                // Lengths of the actual commands
                capacity += inner.iter().map(|s| s.len()).sum::<usize>();
                // " AND " join operators
                capacity += (inner.len() - 1) * 5;

                let mut out = String::with_capacity(capacity);

                out.push('(');

                let mut first = true;
                for filter in inner {
                    if first {
                        first = false;
                    } else {
                        out.push_str(" AND ");
                    }

                    out.push_str(&filter);
                }

                out.push(')');

                out
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Argument, Filter, FilterError, Operator};

    #[test]
    fn filter_simple_equal() {
        assert_eq!(
            Filter::equal("artist", "foo\'s bar\"").render(),
            "(artist == \"foo\\\'s bar\\\"\")"
        );
    }

    #[test]
    fn filter_other_operator() {
        assert_eq!(
            Filter::tag("artist", Operator::Contain, "mep mep")
                .unwrap()
                .render(),
            "(artist contains \"mep mep\")"
        );
    }

    #[test]
    fn filter_empty_value() {
        assert_eq!(
            Filter::tag("", Operator::Equal, "mep mep").unwrap_err(),
            FilterError::EmptyTag,
        );
    }

    #[test]
    fn filter_not() {
        assert_eq!(
            Filter::equal("artist", "hello").negate().render(),
            "(!(artist == \"hello\"))"
        );
    }

    #[test]
    fn filter_and() {
        let first = Filter::equal("artist", "hello");
        let second = Filter::equal("album", "world");

        assert_eq!(
            first.and(second).render(),
            "((artist == \"hello\") AND (album == \"world\"))"
        );
    }

    #[test]
    fn filter_and_multiple() {
        let first = Filter::equal("artist", "hello");
        let second = Filter::equal("album", "world");
        let third = Filter::equal("title", "foo");

        assert_eq!(
            first.and(second).and(third).render(),
            "((artist == \"hello\") AND (album == \"world\") AND (title == \"foo\"))"
        );
    }
}