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
76
77
78
79
80
81
82
83
use core::{
    convert::TryFrom,
    fmt::{self, Display, Formatter},
};

use crate::{InvalidConversionError, Value};

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum PixelFormat {
    RGB = 0,
    BGR = 1,
    GrayScale = 2,
}

impl From<PixelFormat> for i32 {
    fn from(p: PixelFormat) -> i32 { p as i32 }
}

impl From<PixelFormat> for u32 {
    fn from(p: PixelFormat) -> u32 { p as u32 }
}

impl From<PixelFormat> for Value {
    fn from(p: PixelFormat) -> Value { Value::Integer(p.into()) }
}

impl TryFrom<i32> for PixelFormat {
    type Error = PixelFormatConversionError;

    fn try_from(i: i32) -> Result<PixelFormat, Self::Error> {
        match i {
            0 => Ok(PixelFormat::RGB),
            1 => Ok(PixelFormat::BGR),
            2 => Ok(PixelFormat::GrayScale),
            _ => Err(PixelFormatConversionError::InvalidConstant { value: i }),
        }
    }
}

impl TryFrom<Value> for PixelFormat {
    type Error = PixelFormatConversionError;

    fn try_from(value: Value) -> Result<PixelFormat, Self::Error> {
        let integer = i32::try_from(value)?;
        PixelFormat::try_from(integer)
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum PixelFormatConversionError {
    InvalidConstant { value: i32 },
    Value(InvalidConversionError),
}

impl From<InvalidConversionError> for PixelFormatConversionError {
    fn from(e: InvalidConversionError) -> Self {
        PixelFormatConversionError::Value(e)
    }
}

impl Display for PixelFormatConversionError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            PixelFormatConversionError::InvalidConstant { value } => {
                write!(f, "{} isn't a valid pixel format", value)
            },
            PixelFormatConversionError::Value(_) => {
                write!(f, "Unable to convert from a Value")
            },
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for PixelFormatConversionError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            PixelFormatConversionError::InvalidConstant { .. } => None,
            PixelFormatConversionError::Value(e) => Some(e),
        }
    }
}