use crate::ArchiveError;
use crate::ConfigProblem;
use crate::ConfigSetting;
use crate::Result;
pub mod private {
pub trait Sealed {}
}
pub trait ClosedEnum: Copy + 'static + private::Sealed {
const ALL: &'static [Self];
const NAMES: &'static [&'static str];
fn as_str(self) -> &'static str;
fn parse_for(setting: ConfigSetting, value: &str) -> Result<Self> {
Self::ALL
.iter()
.copied()
.find(|variant| variant.as_str() == value)
.ok_or(ArchiveError::InvalidConfiguration {
setting,
problem: ConfigProblem::NotOneOf {
allowed: Self::NAMES,
},
})
}
}
macro_rules! closed_enum {
(
$(#[$meta:meta])*
$vis:vis enum $name:ident {
$( $(#[$vmeta:meta])* $variant:ident => $text:literal ),+ $(,)?
}
) => {
$(#[$meta])*
$vis enum $name {
$( $(#[$vmeta])* $variant ),+
}
impl $name {
pub const ALL: &'static [Self] = &[ $( Self::$variant ),+ ];
pub const NAMES: &'static [&'static str] = &[ $( $text ),+ ];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
$( Self::$variant => $text ),+
}
}
}
impl $crate::closed_enum::ClosedEnum for $name {
const ALL: &'static [Self] = Self::ALL;
const NAMES: &'static [&'static str] = Self::NAMES;
fn as_str(self) -> &'static str {
Self::as_str(self)
}
}
impl $crate::closed_enum::private::Sealed for $name {}
impl ::std::fmt::Display for $name {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
f.write_str(self.as_str())
}
}
};
}
pub(crate) use closed_enum;