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
use super::{AllowedType, Attribute};
use crate::definition::Type;
use crate::error::{Error, ValidationError};
use crate::validator::{Context, DocumentPath, State};

use std::collections::HashSet;

use serde_json;

#[derive(Clone, Debug, PartialEq)]
pub enum NumericType {
    Number,
    Integer,
}

#[derive(Debug)]
pub struct NumericMin {
    name: String,
    value: f64,
    typ: NumericType,
    is_exclusive: bool,
}

impl NumericMin {
    pub fn new(is_exclusive: bool, mut path: DocumentPath, ctx: &Context) -> Result<Self, Error> {
        let obj = ctx.raw_definition();

        let typ = match Type::new(obj, path.clone())? {
            Type::Number => NumericType::Number,
            Type::Integer => NumericType::Integer,
            typ => return Err(Error::ForbiddenType { path, typ }),
        };

        let value = match obj.get(ctx.name().as_str()) {
            Some(value) => {
                path.add(ctx.name().as_str());
                extract_numeric(value, typ.clone(), path)?
            }
            None => {
                return Err(Error::MissingAttribute {
                    path,
                    attr: ctx.name(),
                })
            }
        };

        Ok(NumericMin {
            name: ctx.name(),
            value,
            typ,
            is_exclusive,
        })
    }

    pub fn allowed_types() -> HashSet<AllowedType> {
        let mut set = HashSet::<AllowedType>::new();
        set.insert(AllowedType::new(Type::Number, false));
        set.insert(AllowedType::new(Type::Integer, false));
        set
    }

    pub fn build_inclusive(
        _: &mut State,
        path: DocumentPath,
        ctx: &Context,
    ) -> Result<Box<Attribute>, Error> {
        Ok(Box::new(NumericMin::new(false, path, ctx)?))
    }

    pub fn build_exclusive(
        _: &mut State,
        path: DocumentPath,
        ctx: &Context,
    ) -> Result<Box<Attribute>, Error> {
        Ok(Box::new(NumericMin::new(true, path, ctx)?))
    }
}

impl Attribute for NumericMin {
    fn validate(
        &self,
        _: &State,
        path: Vec<String>,
        input: &serde_json::Value,
    ) -> Result<(), ValidationError> {
        if self.typ == NumericType::Number {
            let val = match input.as_f64() {
                Some(val) => val,
                None => {
                    return Err(ValidationError::Failure {
                        rule: "type".to_string(),
                        path: path,
                        message: "Value must be a number.".to_string(),
                    })
                }
            };

            if val <= self.value && self.is_exclusive {
                return Err(ValidationError::Failure {
                    rule: self.name.clone(),
                    path: path,
                    message: format!("Value must be greater than {}.", self.value),
                });
            } else if val < self.value {
                return Err(ValidationError::Failure {
                    rule: self.name.clone(),
                    path: path,
                    message: format!("Value must be greater than or equal to {}.", self.value),
                });
            }
        } else {
            let val = match input.as_i64() {
                Some(val) => val,
                None => {
                    return Err(ValidationError::Failure {
                        rule: "type".to_string(),
                        path: path,
                        message: "Value must be an integer.".to_string(),
                    })
                }
            };

            if val <= self.value as i64 && self.is_exclusive {
                return Err(ValidationError::Failure {
                    rule: self.name.clone(),
                    path: path,
                    message: format!("Value must be greater than {}.", self.value as i64),
                });
            } else if val < self.value as i64 {
                return Err(ValidationError::Failure {
                    rule: self.name.clone(),
                    path: path,
                    message: format!(
                        "Value must be greater than or equal to {}.",
                        self.value as i64
                    ),
                });
            }
        }

        Ok(())
    }
}

fn extract_numeric(
    value: &serde_json::Value,
    typ: NumericType,
    path: DocumentPath,
) -> Result<f64, Error> {
    if typ == NumericType::Number {
        match value.as_f64() {
            Some(val) => Ok(val),
            None => Err(Error::InvalidValue {
                path,
                value: value.clone(),
            }),
        }
    } else {
        match value.as_i64() {
            Some(val) => Ok(val as f64),
            None => Err(Error::InvalidValue {
                path,
                value: value.clone(),
            }),
        }
    }
}