use {
core::{
fmt::{self, Display},
option::Option as RustOption,
},
std::borrow::Cow,
super::{Cfg, I18n},
};
#[derive(Clone)]
pub struct Option<'a> {
names: &'a [&'a str],
required: bool,
values: Vec<String>,
default: RustOption<String>,
docs: Cow<'a, str>,
}
impl<'a> Option<'a> {
pub fn new<T>(names: &'a [&'a str], required: bool, values: &[T], default: RustOption<T>, docs: Cow<'a, str>) -> Self where T: Display {
Self {
names,
required,
values: values.iter().map(|v| v.to_string()).collect(),
default: default.map(|v| v.to_string()),
docs,
}
}
pub fn format(&self, cfg: &Cfg, i18n: &I18n, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let tab = cfg.tab_len().saturating_mul(cfg.tab_level().into());
f.write_str(&super::format(&format!("{:?}", self.names), tab, cfg.columns()))?;
let tab = cfg.tab_len().saturating_mul(cfg.tab_level().saturating_add(1).into());
f.write_str(&super::format(&format!("{}: {}", i18n.required, self.required), tab, cfg.columns()))?;
if self.values.is_empty() == false {
let mut tmp = String::new();
for (i, v) in self.values.iter().enumerate() {
if i > 0 {
tmp.push_str(", ");
}
tmp.push_str(&v);
}
f.write_str(&super::format(&format!("{}: {}", i18n.values, tmp), tab, cfg.columns()))?;
}
if let Some(default) = &self.default {
f.write_str(&super::format(&format!("{}: {}", i18n.default, default), tab, cfg.columns()))?;
}
f.write_str(super::LINE_BREAK)?;
f.write_str(&super::format(&self.docs, tab, cfg.columns()))?;
f.write_str(super::LINE_BREAK)?;
Ok(())
}
}
impl<'a> From<Option<'a>> for Cow<'a, Option<'a>> {
fn from(option: Option<'a>) -> Self {
Cow::Owned(option)
}
}
impl<'a> From<&'a Option<'a>> for Cow<'a, Option<'a>> {
fn from(option: &'a Option<'a>) -> Self {
Cow::Borrowed(option)
}
}