fltrs 0.2.0

Filter for querying lists.
Documentation
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! # Fltrs
//!
//! *Easy to define filters for querying lists.* `Fltrs` has **no** dependencies!
//!
//! ## Overview
//!
//! Fltrs want to support creating easy, fast and expandable filters for iterable things (like Vec, Array, Map, Set, ...) in rust.
//! A filter is created based on an input string (query).
//! This has particular advantages if the filter is created at runtime, i.e. in a GUI or command line tool (CLI).
//!
//! ## Extensions:
//!
//! It is possible, to expand the filter/query to your own needs:
//! - create your own [`mod@crate::operator`]
//! - create a converter for the filter [`Value`] (e.g.: conversion of units).
//!
//! You can find examples on the [`Query`] builder page.
//!
//! ## Examples:
//!
//! ```
//! use fltrs::query;
//!
//! let result: Vec<_> = [3, 2, 1, 4, 5, 7, 5, 4, 3]
//!         .into_iter()
//!         .filter(query("> 1 and < 5").unwrap())
//!         .collect();
//!
//! assert_eq!(vec![3, 2, 4, 4, 3], result);
//! ```
//!
//! ```
//! use fltrs::query;
//!
//! let result: Vec<_> = ["Inge", "Petra", "Paul", "Egon", "Peter"]
//!         .into_iter()
//!         .filter(query("contains 'e'").unwrap())
//!         .collect();
//!
//! assert_eq!(vec!["Inge", "Petra", "Peter"], result);
//! ```
//!
//! ### Option queries:
//!
//! ```
//! use fltrs::query;
//!
//! let result: Vec<Option<char>> = [None, Some('a'), None, Some('b'), Some('c'), Some('a')]
//!         .into_iter()
//!         .filter(query(" != 'a' and not = none ").unwrap())
//!         .collect();
//!
//! assert_eq!(vec![Some('b'), Some('c')], result);
//! ```
//!
//! ### Nested and Not queries:
//!
//! ```
//! use fltrs::query;
//!
//! let result: Vec<_> = [3, 2, 1, 4, 5, 7, 5, 4, 3]
//!         .into_iter()
//!         .filter(query("(= 1 or = 5) and > 1").unwrap())
//!         .collect();
//!
//! assert_eq!(vec![5, 5], result);
//!```
//!
//!```
//! use fltrs::query;
//!
//! let result: Vec<_> = [3, 2, 1, 4, 5, 7, 5, 4, 3]
//!         .into_iter()
//!         .filter(query("not( (= 1 or = 5) and > 1)").unwrap())
//!         .collect();
//!
//! assert_eq!(vec![3, 2, 1, 4, 7, 4, 3], result);
//! ```
//!
//! ### Fltrs supported queries on structs too.
//!
//! This is possible, if the struct implement the trait: [`PathResolver`].
//!
//! ```
//! use fltrs::{PathResolver, Filterable, query};
//!
//! #[derive(PartialEq, Debug)]
//! struct Point {
//!     name: &'static str,
//!     x:    i32,
//!     y:    i32,
//! }
//!
//! impl PathResolver for Point {
//!     fn path_to_index(path: &str) -> Option<usize> {
//!         match path {
//!             "name"  => Some(0),
//!             "x"     => Some(1),
//!             "y"     => Some(2),
//!             _ => None,
//!         }
//!     }
//!
//!     fn value(&self, idx: usize) -> &dyn Filterable {
//!         match idx {
//!             0 => &self.name,
//!             1 => &self.x,
//!             _ => &self.y,
//!         }
//!     }
//! }
//!
//! let result: Vec<Point> =
//!     [
//!       Point { name: "Point_1_3", x: 1, y: 3},
//!       Point { name: "Point_3_3", x: 3, y: 3},
//!       Point { name: "Point_2_6", x: 2, y: 6},
//!     ]
//!      .into_iter()
//!      .filter(query(r#"x one_of [3, 7]"#).unwrap())
//!      .collect();
//!
//! assert_eq!(vec![Point { name: "Point_3_3", x: 3, y: 3}], result);
//! ```
//!

pub mod error;
pub mod operator;
mod parser;
mod query;
mod scanner;
mod token;
pub mod value;

pub use crate::error::FltrError;
use crate::operator::{OperatorFn, Operators};
use crate::parser::{parse, AsValueFn, Parser};
use crate::value::Value;

/// The default [`core::result::Result`] with the error: [`FltrError`].
pub type Result<T> = core::result::Result<T, FltrError>;

/// Is a replacement for the [`std::fmt::Display`] trait.
/// It is not possible to implement `Display` for the enum [`std::option::Option`].
pub trait AsString {
    fn as_string(&self) -> String;
}

macro_rules! as_string {
    ( $($t:ty) + ) => {
    $(
        impl AsString for $t {
            fn as_string(&self) -> String {
                self.to_string()
            }
        }

        impl AsString for Option<$t> {
            fn as_string(&self) -> String {
                match self {
                    Some(v) => v.to_string(),
                    None => String::new(),
                }
            }
        }

    ) *

    }
}

as_string! { bool char &str String usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 f32 f64 }

/// Filterable means, the given value can be compared to [`Value`] and implement the trait [`core::fmt::Display`].
pub trait Filterable: PartialEq<Value> + PartialOrd<Value> + AsString {}

impl<V: PartialEq<Value> + PartialOrd<Value> + AsString> Filterable for V {}

/// PathResolver is a possibility to get the value from a field of an given struct.
///
/// ### Example:
/// ```
/// use fltrs::{PathResolver, Filterable};
///
/// struct Point {
///     name: &'static str,
///     x:    i32,
///     y:    i32,
/// }
///
/// impl PathResolver for Point {
///     fn path_to_index(path: &str) -> Option<usize> {
///         match path {
///             "name"  => Some(0),
///             "x"     => Some(1),
///             "y"     => Some(2),
///             _ => None,
///         }
///     }
///
///     fn value(&self, idx: usize) -> &dyn Filterable {
///         match idx {
///             0 => &self.name,
///             1 => &self.x,
///             _ => &self.y,
///         }
///     }
/// }

pub trait PathResolver {
    /// Is the mapping from a path (struct field name) to an index (that is used by the value-function).
    /// If the path is not a valid, than is the return value: `None`.
    fn path_to_index(path: &str) -> Option<usize>;
    /// The value of the struct field with the given index.
    fn value(&self, idx: usize) -> &dyn Filterable;
}

impl<F: Filterable> PathResolver for F {
    fn path_to_index(_path: &str) -> Option<usize> {
        Some(0)
    }

    fn value(&self, _idx: usize) -> &dyn Filterable {
        self
    }
}

/// A Predicate is an boxed [`core::ops::Fn`].
pub type Predicate<PR> = Box<dyn Fn(&PR) -> bool>;

/// The `query` function create a [`Predicate`] respectively [`core::ops::Fn`] with which you can
/// execute a filter on a given slice.
///
/// ### Example
/// ```
/// use fltrs::query;
///
/// assert_eq!(
///     ["Inge", "Paul", "Peter", "Ina"],
///     ["Inge", "Paul", "Peter", "Jasmin", "Ina", "Mario"]
///                 .into_iter()
///                 .filter(query(r#"starts_with "In" or starts_with 'P'"#).unwrap())
///                 .collect::<Vec<&str>>()
///                 .as_slice(),
/// );
/// ```
pub fn query<PR: PathResolver + 'static>(query: &str) -> Result<Predicate<PR>> {
    crate::query::query(parse(query)?, &Operators::<PR>::default())
}

/// The Query is an builder to configure the [`query()`]. It is possible, to extend the Operators in the modul: [`mod@crate::operator`].
///
/// ### Example
///
/// Create your own operator:
///
/// ```
/// use fltrs::{value::Value, PathResolver, Predicate, Query, Result, query};
///
/// fn upper_eq<PR: PathResolver>(idx: usize, v: Value) -> Result<Predicate<PR>> {
///     Ok(Box::new(
///         move |pr| {
///           if let Value::Text(t) = &v {
///               return pr.value(idx).as_string().to_uppercase().eq(&t.to_uppercase());
///           }
///           false
///         }
///      ))
/// }
///
/// let query = Query::build()
///              .operators(&[("upper_eq", upper_eq)])
///              .query(r#" upper_eq "ab" "#)
///              .unwrap();
///
/// let result: Vec<&str> = ["yz", "aB", "Ab", "xY"].into_iter().filter(query).collect();
///
/// assert_eq!(vec!["aB", "Ab"], result);
///
/// ```
///
/// Create your own `as [convert function]` (for example: conversion of units):
///
/// ```
/// use fltrs::{value::Value, PathResolver, Predicate, Query, Result, query};
///
/// let query = Query::build()
///              .as_value_fn(&[("kbyte", |v| {
///                     if let Value::Int(x) = v {
///                         return Value::Int(x * 1024);
///                     }
///                     v
///                   }
///                 )])
///              .query(r#" > 1 as kbyte and < 6 as kbyte "#)
///              .unwrap();
///
/// // list of bytes
/// let result: Vec<i32> = [100, 1025, 7000, 4001].into_iter().filter(query).collect();
///
/// assert_eq!(vec![1025, 4001], result);
///
/// ```

pub struct Query<PR> {
    ops: Operators<PR>,
    as_value_fn: Vec<(&'static str, AsValueFn)>,
}

impl<PR: PathResolver + 'static> Query<PR> {
    pub fn build() -> Self {
        Self {
            ops: Operators::default(),
            as_value_fn: vec![],
        }
    }

    pub fn operators(mut self, ops: &[(&'static str, OperatorFn<PR>)]) -> Self {
        self.ops.op.extend_from_slice(ops);
        self
    }

    pub fn as_value_fn(mut self, fns: &[(&'static str, AsValueFn)]) -> Self {
        self.as_value_fn.extend_from_slice(fns);
        self
    }

    pub fn query(&self, query: &str) -> Result<Predicate<PR>> {
        let mut p = Parser::new(query);
        p.ops = self.ops.get_ops_names();
        p.as_value_fns = self.as_value_fn.clone();
        crate::query::query(p.parse()?, &self.ops)
    }
}

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

    #[test]
    fn iter_char_space() -> Result<()> {
        let result: Vec<char> = [' ', 'a', ' ', 'b', ' ']
            .into_iter()
            .filter(query(r#"= ' '"#)?)
            .collect();
        assert_eq!(vec![' ', ' ', ' '], result);

        Ok(())
    }

    #[test_case(" > 1 " => vec![Some(2), Some(3)] ; "> 1" )]
    #[test_case(" one_of [1, 2] " => vec![Some(1), Some(2)] ; "one_of 1 2" )]
    #[test_case(" one_of [1, none] " => vec![None, Some(1), None, None] ; "one_of 1 none" )]
    #[test_case(" = " => vec![None, None, None] ; "eq" )]
    #[test_case(" = none" => vec![None, None, None] ; "eq none" )]
    #[test_case(" = None" => vec![None, None, None] ; "eq upper None" )]
    #[test_case(" = null" => vec![None, None, None] ; "eq null" )]
    #[test_case(" = Null" => vec![None, None, None] ; "eq upper Null" )]
    #[test_case(" is_empty " => vec![None, None, None] ; "is_empty")]
    #[test_case(" not is_empty" => vec![Some(1), Some(2), Some(3)] ; "not is_empty" )]
    #[test_case(" not < 2" => vec![None, None, Some(2), Some(3), None] ; "not less 2" )]
    fn iter_option(query_str: &str) -> Vec<Option<i32>> {
        let result: Vec<Option<i32>> = [None, Some(1), None, Some(2), Some(3), None]
            .into_iter()
            .filter(query(query_str).unwrap())
            .collect();
        result
    }

    #[derive(PartialEq, Debug)]
    struct Point {
        x: i8,
        y: i16,
    }

    impl Point {
        fn new(x: i8, y: i16) -> Self {
            Self { x, y }
        }
    }

    impl PathResolver for Point {
        fn path_to_index(path: &str) -> Option<usize> {
            match path {
                "x" => Some(0),
                "y" => Some(1),
                _ => None,
            }
        }

        fn value(&self, idx: usize) -> &dyn Filterable {
            match idx {
                0 => &self.x,
                _ => &self.y,
            }
        }
    }

    #[cfg(feature = "regex")]
    #[test]
    fn iter_regex() -> Result<()> {
        assert_eq!(
            2,
            [1, 22, 333]
                .into_iter()
                .filter(query(r#"regex "[0-9]{2}""#)?)
                .count()
        );

        Ok(())
    }

    #[cfg(feature = "regex")]
    #[test]
    fn iter_point_regex() -> Result<()> {
        assert_eq!(
            1,
            [Point::new(22, 4), Point::new(3, 5)]
                .into_iter()
                .filter(query(r#"x regex "[0-9]{2}""#)?)
                .count()
        );

        Ok(())
    }

    #[test]
    fn iter_point_fltrs() -> Result<()> {
        assert_eq!(
            1,
            [Point::new(2, 4), Point::new(3, 5)]
                .into_iter()
                .filter(query("x > 1 and  y < 5")?)
                .count()
        );

        Ok(())
    }

    #[test]
    fn iter_point_one_of() -> Result<()> {
        assert_eq!(
            2,
            [Point::new(2, 4), Point::new(3, 5), Point::new(4, 6)]
                .into_iter()
                .filter(query("x one_of [1, 2, 7, 4]")?)
                .count()
        );

        Ok(())
    }

    #[test]
    fn iter_str_empty() -> Result<()> {
        let result: Vec<&str> = ["", "abc", "", "xyz", ""]
            .into_iter()
            .filter(query("is_empty")?)
            .collect();
        assert_eq!(vec!["", "", ""], result);

        let result: Vec<&str> = ["", "abc", "", "xyz", ""]
            .into_iter()
            .filter(query(r#"= """#)?)
            .collect();
        assert_eq!(vec!["", "", ""], result);

        Ok(())
    }

    #[test]
    fn iter_str_not_empty() -> Result<()> {
        let result: Vec<&str> = ["", "abc", "", "xyz", ""]
            .into_iter()
            .filter(query("not is_empty")?)
            .collect();
        assert_eq!(vec!["abc", "xyz"], result);

        let result: Vec<&str> = ["", "abc", "", "xyz", ""]
            .into_iter()
            .filter(query(r#"not ( = "")"#)?)
            .collect();
        assert_eq!(vec!["abc", "xyz"], result);

        Ok(())
    }

    #[test]
    fn iter_str_one_of_empty() -> Result<()> {
        let result: Vec<&str> = ["", "abc", "", "xyz", ""]
            .into_iter()
            .filter(query(r#"one_of [""]"#)?)
            .collect();
        assert_eq!(vec!["", "", ""], result);

        Ok(())
    }
}