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
use super::node::*;
use std::cell::RefCell;
use std::clone::Clone;
use std::fmt::Debug;

/// For validation.
///
#[derive(Debug)]
pub struct Error {
    pub label: String,
    pub msg: Vec<String>,
    pub tree: String,
}

/// Type synonym for `std::result::Result<Cherry<T>, Error>`.
///
/// Used in validation.
///
pub type Result<T> = std::result::Result<Cherry<T>, Error>;

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        (self.label == other.label) && (self.msg == other.msg)
    }
}

pub struct ValidateChain<T: Clone + Debug> {
    pub cherry: Cherry<T>,
    pub errors: RefCell<Vec<String>>,
}

///
/// Immediate proxy for validation
///
/// Provides method `into_result` to aggregate validation error.
///
impl<T: Clone + Debug> ValidateChain<T> {
    ///
    /// Aggregates validation error.
    ///
    /// Coverts `ValidateProxy<T>` to [`cherries::Result<T>`](../node/type.Result.html).
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate cherries;
    /// use cherries::{node::Leaf, validate::{Validate, Error}};
    /// extern crate uom;
    /// use uom::si::{f32::*, length::meter, area::square_meter};
    ///
    /// fn main() {
    ///    let x = Leaf::new()
    ///        .name("x")
    ///        .value(Length::new::<meter>(2.0))
    ///        .build();
    ///    let y = Leaf::new()
    ///        .name("y")
    ///        .value(Length::new::<meter>(1.0))
    ///        .build();
    ///    let res = x * y;
    ///    let validated = res
    ///        .validate("must be less than 1.0!!", |quantity| {
    ///            quantity < &Area::new::<square_meter>(1.0)
    ///        })
    ///        .validate("must be less than 0.0!!", |quantity| {
    ///            quantity < &Area::new::<square_meter>(0.0)
    ///        })
    ///        .into_result();
    ///    assert_eq!(
    ///        Err(Error {
    ///            label: "(mul)".to_string(),
    ///            msg: vec![
    ///                 "must be less than 1.0!!".to_string(),
    ///                 "must be less than 0.0!!".to_string()
    ///            ],
    ///            tree: "json tree".to_string(),
    ///        }),
    ///        validated
    ///    );
    /// }
    /// ```
    pub fn into_result(self) -> Result<T> {
        if self.errors.borrow().is_empty() {
            Ok(self.cherry.to_owned())
        } else {
            Err(Error {
                label: self.cherry.name().to_owned(),
                msg: self.errors.into_inner(),
                tree: self.cherry.to_json(),
            })
        }
    }
}

///
/// Trait: Validate
///
/// Provides method `validate`.
///
pub trait Validate<T: Clone + Debug> {
    fn validate<IntoString, Predicate>(
        self,
        msg: IntoString,
        predicate: Predicate,
    ) -> ValidateChain<T>
    where
        IntoString: Into<String>,
        Predicate: FnOnce(&T) -> bool;
}

///
/// Trait: Validate for `Cherry<T>`
///
/// Provides `validate` function.
/// `self.validate(predicate)` returns `ValidateProxy<T>`.
/// `ValidateProxy<T>` also has `validate` to chain for validation.
///
/// # Examples
///
/// ```
/// extern crate cherries;
/// use cherries::{node::Leaf, validate::{Validate, Error}};
/// extern crate uom;
/// use uom::si::{f32::*, length::meter, area::square_meter};
///
/// fn main() {
///    let x = Leaf::new()
///        .name("x")
///        .value(Length::new::<meter>(2.0))
///        .build();
///    let y = Leaf::new()
///        .name("y")
///        .value(Length::new::<meter>(1.0))
///        .build();
///    let res = x * y;
///    let validated = res
///        .validate("must be less than 1.0!!", |quantity| {
///            quantity < &Area::new::<square_meter>(1.0)
///        })
///        .into_result();
///    assert_eq!(
///        Err(Error {
///            label: "(mul)".to_string(),
///            msg: vec!["must be less than 1.0!!".to_string()],
///            tree: "json tree".to_string(),
///        }),
///        validated
///    );
/// }
/// ```
impl<T: Clone + Debug> Validate<T> for Cherry<T> {
    fn validate<IntoString, Predicate>(
        self,
        msg: IntoString,
        predicate: Predicate,
    ) -> ValidateChain<T>
    where
        IntoString: Into<String>,
        Predicate: FnOnce(&T) -> bool,
    {
        if predicate(&self.quantity()) {
            ValidateChain {
                cherry: self.to_owned(),
                errors: RefCell::new(vec![]),
            }
        } else {
            ValidateChain {
                cherry: self.to_owned(),
                errors: RefCell::new(vec![msg.into()]),
            }
        }
    }
}

///
/// For validation chaining.
///
/// `self.validate(predicate)` returns `ValidateProxy<T>`.
///
/// # Examples
///
/// ```
/// extern crate cherries;
/// use cherries::{node::Leaf, validate::{Validate, Error}};
/// extern crate uom;
/// use uom::si::{f32::*, length::meter, area::square_meter};
///
/// fn main() {
///    let x = Leaf::new()
///        .name("x")
///        .value(Length::new::<meter>(2.0))
///        .build();
///    let y = Leaf::new()
///        .name("y")
///        .value(Length::new::<meter>(1.0))
///        .build();
///    let res = x * y;
///    let validated = res
///        .validate("must be less than 1.0!!", |quantity| {
///            quantity < &Area::new::<square_meter>(1.0)
///        })
///        .validate("must be less than 0.0!!", |quantity| {
///            quantity < &Area::new::<square_meter>(0.0)
///        })
///        .into_result();
///    assert_eq!(
///        Err(Error {
///            label: "(mul)".to_string(),
///            msg: vec![
///                 "must be less than 1.0!!".to_string(),
///                 "must be less than 0.0!!".to_string()
///            ],
///            tree: "json tree".to_string(),
///        }),
///        validated
///    );
/// }
/// ```
impl<T: Clone + Debug> Validate<T> for ValidateChain<T> {
    fn validate<IntoString, Predicate>(
        self,
        msg: IntoString,
        predicate: Predicate,
    ) -> ValidateChain<T>
    where
        IntoString: Into<String>,
        Predicate: FnOnce(&T) -> bool,
    {
        if predicate(&self.cherry.quantity()) {
            self
        } else {
            self.errors.borrow_mut().push(msg.into());
            self
        }
    }
}