From b31fd25cc5cec96ccee737ba1313c6e9f702f32a Mon Sep 17 00:00:00 2001 From: Vincent Prouillet Date: Fri, 26 May 2017 00:49:54 +0900 Subject: Revamp --- validator_derive/src/asserts.rs | 54 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 validator_derive/src/asserts.rs (limited to 'validator_derive/src/asserts.rs') diff --git a/validator_derive/src/asserts.rs b/validator_derive/src/asserts.rs new file mode 100644 index 0000000..65db5cf --- /dev/null +++ b/validator_derive/src/asserts.rs @@ -0,0 +1,54 @@ + +pub static NUMBER_TYPES: [&'static str; 24] = [ + "usize", "u8", "u16", "u32", "u64", + "isize", "i8", "i16", "i32", "i64", + "f32", "f64", + + "Option", "Option", "Option", "Option", "Option", + "Option", "Option", "Option", "Option", "Option", + "Option", "Option", +]; + + +pub fn assert_string_type(name: &str, field_type: &String) { + if field_type != "String" + && field_type != "&str" + && field_type != "Option" + && !(field_type.starts_with("Option<") && field_type.ends_with("str>")) { + panic!("`{}` validator can only be used on String, &str or an Option of those", name); + } +} + +pub fn assert_type_matches(field_name: String, field_type: &String, field_type2: Option<&String>) { + if let Some(t2) = field_type2 { + if field_type != t2 { + panic!("Invalid argument for `must_match` validator of field `{}`: types of field can't match", field_name); + } + } else { + panic!("Invalid argument for `must_match` validator of field `{}`: the other field doesn't exist in struct", field_name); + } +} + +pub fn assert_has_len(field_name: String, field_type: &String) { + if field_type != "String" + && !field_type.starts_with("Vec<") + && !field_type.starts_with("Option")) + && field_type != "&str" { + panic!( + "Validator `length` can only be used on types `String`, `&str` or `Vec` but found `{}` for field `{}`", + field_type, field_name + ); + } +} + +pub fn assert_has_range(field_name: String, field_type: &String) { + if !NUMBER_TYPES.contains(&field_type.as_ref()) { + panic!( + "Validator `range` can only be used on number types but found `{}` for field `{}`", + field_type, field_name + ); + } +} -- cgit v1.2.3