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
use liquid_error;

use value::Value;

/// Expected return type of a `Filter`.
pub type FilterResult = Result<Value, liquid_error::Error>;

/// A trait for creating custom tags. This is a simple type alias for a function.
///
/// This function will be called whenever the parser encounters a tag and returns
/// a new [Renderable](trait.Renderable.html) based on its parameters. The received parameters
/// specify the name of the tag, the argument [Tokens](lexer/enum.Token.html) passed to
/// the tag and the global [`LiquidOptions`](struct.LiquidOptions.html).
pub trait FilterValue: Send + Sync + FilterValueClone {
    /// Filter `input` based on `arguments`.
    fn filter(&self, input: &Value, arguments: &[Value]) -> FilterResult;
}

/// Support cloning of `Box<FilterValue>`.
pub trait FilterValueClone {
    /// Cloning of `dyn FilterValue`.
    fn clone_box(&self) -> Box<FilterValue>;
}

impl<T> FilterValueClone for T
where
    T: 'static + FilterValue + Clone,
{
    fn clone_box(&self) -> Box<FilterValue> {
        Box::new(self.clone())
    }
}

impl Clone for Box<FilterValue> {
    fn clone(&self) -> Box<FilterValue> {
        self.clone_box()
    }
}

/// Function signature that can act as a `FilterValue`.
pub type FnFilterValue = fn(&Value, &[Value]) -> FilterResult;

#[derive(Clone)]
struct FnValueFilter {
    filter: FnFilterValue,
}

impl FnValueFilter {
    fn new(filter: FnFilterValue) -> Self {
        Self { filter }
    }
}

impl FilterValue for FnValueFilter {
    fn filter(&self, input: &Value, arguments: &[Value]) -> FilterResult {
        (self.filter)(input, arguments)
    }
}

#[derive(Clone)]
enum EnumValueFilter {
    Fun(FnValueFilter),
    Heap(Box<FilterValue>),
}

/// Custom `Box<FilterValue>` with a `FnFilterValue` optimization.
#[derive(Clone)]
pub struct BoxedValueFilter {
    filter: EnumValueFilter,
}

impl FilterValue for BoxedValueFilter {
    fn filter(&self, input: &Value, arguments: &[Value]) -> FilterResult {
        match self.filter {
            EnumValueFilter::Fun(ref f) => f.filter(input, arguments),
            EnumValueFilter::Heap(ref f) => f.filter(input, arguments),
        }
    }
}

impl From<fn(&Value, &[Value]) -> FilterResult> for BoxedValueFilter {
    fn from(filter: FnFilterValue) -> BoxedValueFilter {
        let filter = EnumValueFilter::Fun(FnValueFilter::new(filter));
        Self { filter }
    }
}

impl From<Box<FilterValue>> for BoxedValueFilter {
    fn from(filter: Box<FilterValue>) -> BoxedValueFilter {
        let filter = EnumValueFilter::Heap(filter);
        Self { filter }
    }
}