use regex::Regex; use lazy_static::lazy_static; lazy_static! { pub static ref COW_TYPE: Regex = Regex::new(r"Cow<'[a-z]+,str>").unwrap(); } pub static NUMBER_TYPES: [&'static str; 36] = [ "usize", "u8", "u16", "u32", "u64", "isize", "i8", "i16", "i32", "i64", "f32", "f64", "Option", "Option", "Option", "Option", "Option", "Option", "Option", "Option", "Option", "Option", "Option", "Option", "Option>", "Option>", "Option>", "Option>", "Option>", "Option>", "Option>", "Option>", "Option>", "Option>", "Option>", "Option>", ]; pub fn assert_string_type(name: &str, field_type: &str) { if field_type != "String" && field_type != "&str" && !COW_TYPE.is_match(field_type) && field_type != "Option" && field_type != "Option>" && !(field_type.starts_with("Option<") && field_type.ends_with("str>")) && !(field_type.starts_with("Option>")) { panic!( "`{}` validator can only be used on String, &str, Cow<'_,str> or an Option of those", name ); } } pub fn assert_type_matches(field_name: String, field_type: &str, 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: &str) { if field_type != "String" && !field_type.starts_with("Vec<") && !field_type.starts_with("Option")) && !(field_type.starts_with("Option>")) && !COW_TYPE.is_match(field_type) && field_type != "&str" { panic!( "Validator `length` can only be used on types `String`, `&str`, Cow<'_,str> or `Vec` but found `{}` for field `{}`", field_type, field_name ); } } pub fn assert_has_range(field_name: String, field_type: &str) { if !NUMBER_TYPES.contains(&field_type) { panic!( "Validator `range` can only be used on number types but found `{}` for field `{}`", field_type, field_name ); } }