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
use regex::Regex;
use EntityType;
use WikibaseError;
fn number_is_integer(string: &str) -> bool {
match string.parse::<u64>() {
Ok(_) => true,
Err(_) => false,
}
}
pub fn parse_wikibase_entity_type(entity_id: &str) -> Result<EntityType, WikibaseError> {
if entity_id.chars().count() < 2 {
return Err(WikibaseError::Validation("ID is too short".to_string()));
}
let first_char = match entity_id.chars().nth(0) {
Some(value) => value,
None => {
return Err(WikibaseError::Validation(
"Error getting first character of string".to_string(),
))
}
};
if number_is_integer(&entity_id[1..]) == false {
return Err(WikibaseError::Serialization(
"Wikibase ID is not a valid integer".to_string(),
));
}
match first_char {
'P' => Ok(EntityType::Property),
'Q' => Ok(EntityType::Item),
_ => Err(WikibaseError::Serialization(
"Wikibase ID does not have a P or Q prefix".to_string(),
)),
}
}
pub fn validate_user_agent(user_agent: &str) -> Result<String, WikibaseError> {
let re = Regex::new(r"(?P<user_agent>[a-zA-Z0-9-_]+/[0-9\.]+)").unwrap();
let valid = match re.captures(user_agent) {
Some(value) => value,
None => {
return Err(WikibaseError::Configuration(
"User agent is not valid".to_string(),
))
}
};
Ok(valid["user_agent"].to_string())
}