exarch_core/closed_enum.rs
1//! Declarative table for enums whose variants have a stable string form.
2
3use crate::ArchiveError;
4use crate::ConfigProblem;
5use crate::ConfigSetting;
6use crate::Result;
7
8pub mod private {
9 pub trait Sealed {}
10}
11
12/// An enum with a fixed set of variants and a stable string form for each.
13///
14/// Implemented only inside this crate, by the table macro behind every closed
15/// enum, so a front end can parse the string of any of them through one typed
16/// entry point instead of matching strings itself.
17///
18/// # Examples
19///
20/// ```
21/// use exarch_core::ClosedEnum;
22/// use exarch_core::ConfigSetting;
23/// use exarch_core::ZipConsistencyPolicy;
24///
25/// let policy = ZipConsistencyPolicy::parse_for(ConfigSetting::ZipConsistency, "ignore")?;
26/// assert_eq!(policy, ZipConsistencyPolicy::Ignore);
27/// assert!(ZipConsistencyPolicy::parse_for(ConfigSetting::ZipConsistency, "x").is_err());
28/// assert_eq!(ZipConsistencyPolicy::NAMES, &["enforce", "ignore"]);
29/// # Ok::<(), exarch_core::ArchiveError>(())
30/// ```
31pub trait ClosedEnum: Copy + 'static + private::Sealed {
32 /// Every variant, in declaration order.
33 const ALL: &'static [Self];
34
35 /// The string form of every variant, in declaration order.
36 const NAMES: &'static [&'static str];
37
38 /// The stable string form of this variant.
39 fn as_str(self) -> &'static str;
40
41 /// Parses the string form of a variant.
42 ///
43 /// # Errors
44 ///
45 /// [`ArchiveError::InvalidConfiguration`] naming `setting` with
46 /// [`ConfigProblem::NotOneOf`] listing [`NAMES`](Self::NAMES) for any other
47 /// string.
48 fn parse_for(setting: ConfigSetting, value: &str) -> Result<Self> {
49 Self::ALL
50 .iter()
51 .copied()
52 .find(|variant| variant.as_str() == value)
53 .ok_or(ArchiveError::InvalidConfiguration {
54 setting,
55 problem: ConfigProblem::NotOneOf {
56 allowed: Self::NAMES,
57 },
58 })
59 }
60}
61
62/// Defines an enum together with `ALL`, `NAMES`, `as_str` and `Display` from
63/// one table.
64///
65/// The variant set, the `ALL` slice and the string spellings all come from the
66/// same `Variant => "text"` table, so they cannot drift apart. Variants are
67/// emitted in table order, which matters for derived `PartialOrd`/`Ord`.
68macro_rules! closed_enum {
69 (
70 $(#[$meta:meta])*
71 $vis:vis enum $name:ident {
72 $( $(#[$vmeta:meta])* $variant:ident => $text:literal ),+ $(,)?
73 }
74 ) => {
75 $(#[$meta])*
76 $vis enum $name {
77 $( $(#[$vmeta])* $variant ),+
78 }
79
80 impl $name {
81 /// Every variant, in declaration order.
82 pub const ALL: &'static [Self] = &[ $( Self::$variant ),+ ];
83
84 /// The string form of every variant, in declaration order.
85 pub const NAMES: &'static [&'static str] = &[ $( $text ),+ ];
86
87 /// Returns the stable string form shared by `Display` and all
88 /// language bindings.
89 #[must_use]
90 pub const fn as_str(self) -> &'static str {
91 match self {
92 $( Self::$variant => $text ),+
93 }
94 }
95 }
96
97 impl $crate::closed_enum::ClosedEnum for $name {
98 const ALL: &'static [Self] = Self::ALL;
99 const NAMES: &'static [&'static str] = Self::NAMES;
100
101 fn as_str(self) -> &'static str {
102 Self::as_str(self)
103 }
104 }
105
106 impl $crate::closed_enum::private::Sealed for $name {}
107
108 impl ::std::fmt::Display for $name {
109 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
110 f.write_str(self.as_str())
111 }
112 }
113 };
114}
115
116pub(crate) use closed_enum;