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
//! Contains types and traits for nonexhaustive enums.
//!
//! The most important type here is [NonExhaustive](./nonexhaustive/struct.NonExhaustive.html),
//! which allows passing an enum which used the
//! `#[derive(StableAbi)] #[sabi(kind(WithNonExhaustive(...)))]`
//! attributes through ffi.
//!

#[doc(hidden)]
pub mod doc_enums;

#[cfg(any(feature = "testing", feature = "nonexhaustive_examples"))]
pub mod examples;

pub(crate) mod alt_c_functions;
pub(crate) mod nonexhaustive;
pub(crate) mod traits;
pub(crate) mod vtable;

pub(crate) use self::vtable::NonExhaustiveVtable_Ref;

pub use self::{
    nonexhaustive::{
        DiscrAndEnumInfo, NonExhaustive, NonExhaustiveFor, NonExhaustiveSharedOps, NonExhaustiveWI,
        NonExhaustiveWS, UnwrapEnumError,
    },
    traits::{
        DeserializeEnum, EnumInfo, GetEnumInfo, GetNonExhaustive, SerializeEnum, ValidDiscriminant,
    },
    vtable::GetVTable,
};

pub(crate) use self::traits::GetSerializeEnumProxy;

/////////////////////////////////////////////////////////////

/// Asserts that the size and alignment of an enum are valid for its default storage.
pub fn assert_nonexhaustive<T>()
where
    T: GetEnumInfo,
    T: GetVTable<<T as GetEnumInfo>::DefaultStorage, <T as GetEnumInfo>::DefaultInterface>,
{
    #[derive(Debug)]
    #[allow(dead_code)]
    struct TypeAndStorageLayout {
        type_: &'static str,
        type_size: usize,
        type_alignment: usize,
        storage_: &'static str,
        storage_size: usize,
        storage_alignment: usize,
    }

    let lay = TypeAndStorageLayout {
        type_: std::any::type_name::<T>(),
        type_size: std::mem::size_of::<T>(),
        type_alignment: std::mem::align_of::<T>(),
        storage_: std::any::type_name::<<T as GetEnumInfo>::DefaultStorage>(),
        storage_size: std::mem::size_of::<T::DefaultStorage>(),
        storage_alignment: std::mem::align_of::<T::DefaultStorage>(),
    };

    assert!(
        NonExhaustiveFor::<T>::check_alignment(),
        "The alignment of the storage is different than the enum:\n{:#?}",
        lay
    );

    assert!(
        NonExhaustiveFor::<T>::check_size(),
        "The size of the storage is smaller than the enum:\n{:#?}",
        lay
    );
}