yara_sys/errors/
compile.rs

1use crate::YARA_ERROR_LEVEL_ERROR;
2use crate::YARA_ERROR_LEVEL_WARNING;
3
4/// The level of an error while parsing a rule file.
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6pub enum CompileErrorLevel {
7    Error,
8    Warning,
9}
10
11impl CompileErrorLevel {
12    /// Convert from an i32 error code
13    ///
14    /// # Panics
15    ///
16    /// Panics if the code is not a valid value
17    pub fn from_code(code: i32) -> CompileErrorLevel {
18        match code as u32 {
19            YARA_ERROR_LEVEL_ERROR => CompileErrorLevel::Error,
20            YARA_ERROR_LEVEL_WARNING => CompileErrorLevel::Warning,
21            _ => panic!(
22                "Should be {} or {}",
23                YARA_ERROR_LEVEL_ERROR, YARA_ERROR_LEVEL_WARNING
24            ),
25        }
26    }
27
28    /// Convert from an i32 error code.
29    ///
30    /// Returns `Err` if the code is not a valide value.
31    pub fn try_from_code(code: i32) -> Result<CompileErrorLevel, i32> {
32        match code as u32 {
33            YARA_ERROR_LEVEL_ERROR => Ok(CompileErrorLevel::Error),
34            YARA_ERROR_LEVEL_WARNING => Ok(CompileErrorLevel::Warning),
35            _ => Err(code),
36        }
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn test_from_code() {
46        assert_eq!(
47            CompileErrorLevel::Error,
48            CompileErrorLevel::from_code(YARA_ERROR_LEVEL_ERROR as i32)
49        );
50        assert_eq!(
51            CompileErrorLevel::Warning,
52            CompileErrorLevel::from_code(YARA_ERROR_LEVEL_WARNING as i32)
53        );
54    }
55
56    #[test]
57    #[should_panic]
58    fn test_from_code_panic() {
59        CompileErrorLevel::from_code(64);
60    }
61
62    #[test]
63    fn test_try_from_code() {
64        assert_eq!(
65            Ok(CompileErrorLevel::Error),
66            CompileErrorLevel::try_from_code(YARA_ERROR_LEVEL_ERROR as i32)
67        );
68        assert_eq!(
69            Ok(CompileErrorLevel::Warning),
70            CompileErrorLevel::try_from_code(YARA_ERROR_LEVEL_WARNING as i32)
71        );
72        assert_eq!(Err(42), CompileErrorLevel::try_from_code(42));
73    }
74}