sdl2/
common.rs

1use std::error::Error;
2use std::fmt;
3
4/// A given integer was so big that its representation as a C integer would be
5/// negative.
6#[derive(Debug, Clone, PartialEq)]
7pub enum IntegerOrSdlError {
8    IntegerOverflows(&'static str, u32),
9    SdlError(String),
10}
11/// Validates and converts the given u32 to a positive C integer.
12pub fn validate_int(value: u32, name: &'static str) -> Result<::libc::c_int, IntegerOrSdlError> {
13    use self::IntegerOrSdlError::*;
14    // Many SDL functions will accept `int` values, even if it doesn't make sense
15    // for the values to be negative.
16    // In the cases that SDL doesn't check negativity, passing negative values
17    // could be unsafe.
18    // For example, `SDL_JoystickGetButton` uses the index argument to access an
19    // array without checking if it's negative, which could potentially lead to
20    // segmentation faults.
21    if value >= 1 << 31 {
22        Err(IntegerOverflows(name, value))
23    } else {
24        Ok(value as ::libc::c_int)
25    }
26}
27
28impl fmt::Display for IntegerOrSdlError {
29    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
30        use self::IntegerOrSdlError::*;
31
32        match *self {
33            IntegerOverflows(name, value) => write!(f, "Integer '{}' overflows ({})", name, value),
34            SdlError(ref e) => write!(f, "SDL error: {}", e),
35        }
36    }
37}
38
39impl Error for IntegerOrSdlError {}