ffi_enum/
lib.rs

1#![cfg_attr(not(test), no_std)]
2
3use thiserror::Error;
4
5#[doc(hidden)]
6#[path = "private.rs"]
7pub mod __private;
8#[doc(inline)]
9pub use macros::ffi_enum;
10
11/// Re-exports of commonly used traits and types
12pub mod prelude {
13    pub use crate::{ffi_enum, FfiEnum as _, FfiEnumExt as _};
14}
15
16/// Types generated from `ffi_enum` implement this trait which provides essential type and constant information.
17pub trait FfiEnum: Copy + Eq {
18    /// The rusty `enum` type of the `ffi_enum` type
19    type Enum: TryFrom<Self, Error = Error> + Into<Self>;
20
21    /// The representation type of the `ffi_enum` type
22    type Repr: Copy + From<Self> + Into<Self>;
23}
24
25/// Convenient operations on `FfiEnum`
26pub trait FfiEnumExt: FfiEnum {
27    /// Indicates whether the value is known
28    fn is_known(self) -> bool;
29
30    /// Gets the integer representation of the value
31    fn repr(self) -> Self::Repr;
32
33    /// Gets the rust enum of the value
34    fn into_enum(self) -> Self::Enum;
35}
36
37impl<T: FfiEnum> FfiEnumExt for T {
38    #[inline(always)]
39    fn is_known(self) -> bool {
40        Self::Enum::try_from(self).is_ok()
41    }
42
43    #[inline(always)]
44    fn repr(self) -> Self::Repr {
45        self.into()
46    }
47
48    #[inline(always)]
49    fn into_enum(self) -> Self::Enum {
50        self.try_into().unwrap()
51    }
52}
53
54/// Error type which `ffi_enum` generated operation may return
55#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
56pub enum Error {
57    /// `ffi_enum` generated type accepts any binary pattern as a valid value, which means some operations that requires a valid value may fail with an unknown value
58    #[error("value of ffi_enum type is an unknown variant")]
59    UnknownVariant,
60    /// The value of the `ffi_enum` type is out of range
61    #[error(transparent)]
62    TryFromInt(#[from] core::num::TryFromIntError),
63}