wikibase 0.3.0

A library to access Wikibase
Documentation
// validate.rs
//
// Copyright © 2018
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

use EntityType;
use regex::Regex;
use WikibaseError;

/// Returns true if the str is a valid integer.
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()))
    }
}

/// Checks the validity of a user-agent string and returns a Result
///
/// If the user-agent string is valid, the Result contains the 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())
}