newtype_enum/
unstable.rs

1//! Unstable traits and types.
2//!
3//! All traits and types in this module are unstable. They could change in the future.
4
5use crate::Enum;
6use core::hint::unreachable_unchecked;
7
8/// Mark a type as a newtype variant of an [`Enum`](../trait.Enum.html) `E`.
9///
10/// Use the [`newtype_enum`](../attr.newtype_enum.html) macro to implement this trait for your enum variants.
11///
12/// **NOTE**: All methods in this trait are unstable. Use their counterpart in the [`Enum`](../trait.Enum.html) trait.
13pub trait VariantCore<E: Enum>: Sized {
14    /// Convert this newtype variant into the enum `E`.
15    fn into_enum(self) -> E;
16
17    /// Convert an enum into this newtype variant.
18    fn from_enum(e: E) -> Option<Self>;
19
20    /// Get a reference to this this newtype variant.
21    fn ref_enum(e: &E) -> Option<&Self>;
22
23    /// Get a mutable reference to this this newtype variant.
24    fn mut_enum(e: &mut E) -> Option<&mut Self>;
25
26    /// Check if an enum currently holds this newtype variant.
27    ///
28    /// If this method returns `true`, it is safe to call one of the `enum_unchecked` methods.
29    fn is_enum_variant(e: &E) -> bool {
30        Self::ref_enum(e).is_some()
31    }
32
33    /// Convert an enum into this newtype variants and unwrap the value.
34    ///
35    /// This method is equivalent to `Self::from(e).unwrap()`.
36    ///
37    /// Implementors **should** write this method without an intermediate `Option<V>` value.
38    /// This sometimes allows the compiler to optimize the code better.
39    fn from_enum_unwrap(e: E) -> Self {
40        match Self::from_enum(e) {
41            Some(v) => v,
42            None => panic!("called `Variant::from_enum_unwrap` on another enum variant"),
43        }
44    }
45
46    /// Convert an enum into this newtype variant.
47    unsafe fn from_enum_unchecked(e: E) -> Self {
48        match Self::from_enum(e) {
49            Some(v) => v,
50            None => unreachable_unchecked(),
51        }
52    }
53
54    /// Get a reference to this this newtype variant.
55    unsafe fn ref_enum_unchecked(e: &E) -> &Self {
56        match Self::ref_enum(e) {
57            Some(v) => v,
58            None => unreachable_unchecked(),
59        }
60    }
61
62    /// Get a mutable reference to this this newtype variant.
63    unsafe fn mut_enum_unchecked(e: &mut E) -> &mut Self {
64        match Self::mut_enum(e) {
65            Some(v) => v,
66            None => unreachable_unchecked(),
67        }
68    }
69}