enumcapsulate/lib.rs
1//! Traits and corresponding derive macros for enum-based encapsulation.
2
3#[cfg(feature = "macros")]
4pub use enumcapsulate_macros::*;
5
6/// Creates an instance of `Self` from the unambiguous field type of one of its variants.
7pub trait FromVariant<T> {
8 /// Converts to this type from the variant's type.
9 fn from_variant(variant: T) -> Self;
10}
11
12/// Provides owned access to the current variant's field.
13pub trait AsVariant<T> {
14 /// Returns a the inner value as `T` if it is of type `T`, or `None` if it isn’t.
15 fn as_variant(&self) -> Option<T>;
16}
17
18/// Provides borrowed access to the current variant's field.
19pub trait AsVariantRef<T> {
20 /// Returns a the inner value as `&T` if it is of type `T`, or `None` if it isn’t.
21 fn as_variant_ref(&self) -> Option<&T>;
22}
23
24/// Provides mutable borrowed access to the current variant's field.
25pub trait AsVariantMut<T> {
26 /// Returns a the inner value as `&mut T` if it is of type `T`, or `None` if it isn’t.
27 fn as_variant_mut(&mut self) -> Option<&mut T>;
28}
29
30/// Returns the current variant's field, consuming `self`.
31pub trait IntoVariant<T>: Sized {
32 /// Returns the inner value if it is of type `T`, or `Err(self)` if it isn’t.
33 fn into_variant(self) -> Result<T, Self>;
34}
35
36/// Convenience umbrella trait used to do a cheap
37///
38/// - reference-to-reference
39/// - mutable-to-mutable reference
40/// - reference-to-value
41/// - value-to-value
42///
43/// conversion between an outer enum's and its inner variant's type.
44pub trait VariantDowncast {
45 /// Returns some reference to the inner value if it is of type `T`, or `None`` if it isn’t.
46 fn as_variant_downcast_ref<T>(&self) -> Option<&T>
47 where
48 Self: AsVariantRef<T>,
49 {
50 self.as_variant_ref()
51 }
52
53 /// Returns some mutable reference to the inner value if it is of type `T`, or `None` if it isn’t.
54 fn as_variant_downcast_mut<T>(&mut self) -> Option<&mut T>
55 where
56 Self: AsVariantMut<T>,
57 {
58 self.as_variant_mut()
59 }
60
61 /// Returns a copy of the inner value if it is of type `T`, or `None`` if it isn’t.
62 fn as_variant_downcast<T>(&self) -> Option<T>
63 where
64 T: Clone,
65 Self: AsVariant<T>,
66 {
67 self.as_variant()
68 }
69
70 /// Converts this type into the variant's type.
71 fn into_variant_downcast<T>(self) -> Result<T, Self>
72 where
73 Self: IntoVariant<T>,
74 {
75 self.into_variant()
76 }
77}
78
79/// Used to obtain an enum variant's discriminant.
80pub trait VariantDiscriminant {
81 type Discriminant: Eq;
82
83 /// Returns the variant's discriminant.
84 fn variant_discriminant(&self) -> Self::Discriminant;
85}