dia_args/docs/
option.rs

1/*
2==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--
3
4Dia-Args
5
6Copyright (C) 2018-2019, 2021-2025  Anonymous
7
8There are several releases over multiple years,
9they are listed as ranges, such as: "2018-2019".
10
11This program is free software: you can redistribute it and/or modify
12it under the terms of the GNU Lesser General Public License as published by
13the Free Software Foundation, either version 3 of the License, or
14(at your option) any later version.
15
16This program is distributed in the hope that it will be useful,
17but WITHOUT ANY WARRANTY; without even the implied warranty of
18MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19GNU Lesser General Public License for more details.
20
21You should have received a copy of the GNU Lesser General Public License
22along with this program.  If not, see <https://www.gnu.org/licenses/>.
23
24::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
25*/
26
27//! # Option
28
29use {
30    core::{
31        fmt::{self, Display},
32        option::Option as RustOption,
33    },
34    std::borrow::Cow,
35    super::{Cfg, I18n},
36};
37
38/// # Option
39///
40/// ## Examples
41///
42/// ```
43/// use std::borrow::Cow;
44/// use dia_args::docs::{self, Option};
45///
46/// // All these constants are convenient while working with Args.
47/// // And you can also use them for Option.
48///
49/// const OPTION_PORT: &[&str] = &["-p", "--port"];
50/// const OPTION_PORT_VALUES: &[u16] = &[0, 64009];
51/// const OPTION_PORT_DEFAULT: u16 = OPTION_PORT_VALUES[1];
52/// const OPTION_PORT_DOCS: Cow<str> = Cow::Borrowed("Port for server.");
53///
54/// let _option = Option::new(
55///     OPTION_PORT, false,
56///     OPTION_PORT_VALUES,
57///     Some(OPTION_PORT_DEFAULT),
58///     OPTION_PORT_DOCS,
59/// );
60/// // Here you can pass this option to Docs::new(...)
61/// ```
62#[derive(Clone)]
63pub struct Option<'a> {
64    names: &'a [&'a str],
65    required: bool,
66    values: Vec<String>,
67    default: RustOption<String>,
68    docs: Cow<'a, str>,
69}
70
71impl<'a> Option<'a> {
72
73    /// # Makes new instance
74    pub fn new<T>(names: &'a [&'a str], required: bool, values: &[T], default: RustOption<T>, docs: Cow<'a, str>) -> Self where T: Display {
75        Self {
76            names,
77            required,
78            values: values.iter().map(|v| v.to_string()).collect(),
79            default: default.map(|v| v.to_string()),
80            docs,
81        }
82    }
83
84    /// # Formats self
85    pub fn format(&self, cfg: &Cfg, i18n: &I18n, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
86        let tab = cfg.tab_len().saturating_mul(cfg.tab_level().into());
87        f.write_str(&super::format(&format!("{:?}", self.names), tab, cfg.columns()))?;
88
89        let tab = cfg.tab_len().saturating_mul(cfg.tab_level().saturating_add(1).into());
90        f.write_str(&super::format(&format!("{}: {}", i18n.required, self.required), tab, cfg.columns()))?;
91        if self.values.is_empty() == false {
92            let mut tmp = String::new();
93            for (i, v) in self.values.iter().enumerate() {
94                if i > 0 {
95                    tmp.push_str(", ");
96                }
97                tmp.push_str(&v);
98            }
99            f.write_str(&super::format(&format!("{}: {}", i18n.values, tmp), tab, cfg.columns()))?;
100        }
101        if let Some(default) = &self.default {
102            f.write_str(&super::format(&format!("{}: {}", i18n.default, default), tab, cfg.columns()))?;
103        }
104        f.write_str(super::LINE_BREAK)?;
105        f.write_str(&super::format(&self.docs, tab, cfg.columns()))?;
106        f.write_str(super::LINE_BREAK)?;
107
108        Ok(())
109    }
110
111}
112
113impl<'a> From<Option<'a>> for Cow<'a, Option<'a>> {
114
115    fn from(option: Option<'a>) -> Self {
116        Cow::Owned(option)
117    }
118
119}
120
121impl<'a> From<&'a Option<'a>> for Cow<'a, Option<'a>> {
122
123    fn from(option: &'a Option<'a>) -> Self {
124        Cow::Borrowed(option)
125    }
126
127}