gemachain_program/
decode_error.rs

1use num_traits::FromPrimitive;
2
3/// Allows custom errors to be decoded back to their original enum
4pub trait DecodeError<E> {
5    fn decode_custom_error_to_enum(custom: u32) -> Option<E>
6    where
7        E: FromPrimitive,
8    {
9        E::from_u32(custom)
10    }
11    fn type_of() -> &'static str;
12}
13
14#[cfg(test)]
15mod tests {
16    use super::*;
17    use num_derive::FromPrimitive;
18
19    #[test]
20    fn test_decode_custom_error_to_enum() {
21        #[derive(Debug, FromPrimitive, PartialEq)]
22        enum TestEnum {
23            A,
24            B,
25            C,
26        }
27        impl<T> DecodeError<T> for TestEnum {
28            fn type_of() -> &'static str {
29                "TestEnum"
30            }
31        }
32        assert_eq!(TestEnum::decode_custom_error_to_enum(0), Some(TestEnum::A));
33        assert_eq!(TestEnum::decode_custom_error_to_enum(1), Some(TestEnum::B));
34        assert_eq!(TestEnum::decode_custom_error_to_enum(2), Some(TestEnum::C));
35        let option: Option<TestEnum> = TestEnum::decode_custom_error_to_enum(3);
36        assert_eq!(option, None);
37    }
38}