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    /// A sample of an unknown values
25    ///
26    /// Note that a `ffi_enum` accepts any value of the representation type, so `some_value != FfiEnum::UNKNOWN` **does not**
27    /// indicate that `some_value` is known
28    const UNKNOWN: Self;
29}
30
31/// Convenient operations on `FfiEnum`
32pub trait FfiEnumExt: FfiEnum {
33    /// Indicates whether the value is known
34    fn is_known(self) -> bool;
35
36    /// Gets the integer representation of the value
37    fn repr(self) -> Self::Repr;
38
39    /// Gets the rust enum of the value
40    fn into_enum(self) -> Self::Enum;
41}
42
43impl<T: FfiEnum> FfiEnumExt for T {
44    #[inline(always)]
45    fn is_known(self) -> bool {
46        Self::Enum::try_from(self).is_ok()
47    }
48
49    #[inline(always)]
50    fn repr(self) -> Self::Repr {
51        self.into()
52    }
53
54    #[inline(always)]
55    fn into_enum(self) -> Self::Enum {
56        self.try_into().unwrap()
57    }
58}
59
60/// Error type which `ffi_enum` generated operation may return
61#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
62pub enum Error {
63    /// `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
64    #[error("value of ffi_enum type is an unknown variant")]
65    UnknownVariant,
66    /// The value of the `ffi_enum` type is out of range
67    #[error(transparent)]
68    TryFromInt(#[from] core::num::TryFromIntError),
69}