use std::fmt;
use std::str::FromStr;
use crate::types::tokens::error::TokenError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Var {
SessionId,
Arguments,
Tmpdir,
Home,
AirsstackHome,
ProjectDir,
}
impl Var {
const ALL: [Self; 6] = [
Self::SessionId,
Self::Arguments,
Self::Tmpdir,
Self::Home,
Self::AirsstackHome,
Self::ProjectDir,
];
pub fn new(word: &str) -> Result<Self, TokenError> {
Self::ALL
.into_iter()
.find(|var| var.as_str() == word)
.ok_or_else(|| TokenError::UnknownVar {
text: word.to_owned(),
})
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::SessionId => "session_id",
Self::Arguments => "arguments",
Self::Tmpdir => "tmpdir",
Self::Home => "home",
Self::AirsstackHome => "airsstack_home",
Self::ProjectDir => "project_dir",
}
}
pub(super) fn known_names() -> String {
Self::ALL.map(Self::as_str).join(", ")
}
}
impl fmt::Display for Var {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Var {
type Err = TokenError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::new(text)
}
}
impl TryFrom<&str> for Var {
type Error = TokenError;
fn try_from(text: &str) -> Result<Self, Self::Error> {
Self::new(text)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn var_parses_each_known_name() {
for var in Var::ALL {
let name = var.to_string();
assert_eq!(Var::new(&name), Ok(var));
}
assert_eq!(
Var::ALL.map(|v| v.to_string()),
[
"session_id",
"arguments",
"tmpdir",
"home",
"airsstack_home",
"project_dir"
]
);
}
#[test]
fn var_refuses_unknown_with_known_list() {
for name in ["session", "core/tmpdir"] {
assert_eq!(
Var::new(name).map_err(|e| e.to_string()),
Err(format!(
"unknown var \"{name}\" (known: session_id, arguments, tmpdir, home, airsstack_home, project_dir)"
))
);
}
}
#[test]
fn var_builds_alike_through_new_from_str_and_try_from() {
fn shown(built: Result<Var, TokenError>) -> Result<String, String> {
built
.map(|value| value.to_string())
.map_err(|error| error.to_string())
}
for text in ["arguments", "cwd"] {
let expected = shown(Var::new(text));
assert_eq!(shown(text.parse::<Var>()), expected);
assert_eq!(shown(Var::try_from(text)), expected);
}
assert!(Var::new("arguments").is_ok());
assert!(Var::new("cwd").is_err());
}
}