getargs/
opt.rs

1use core::fmt::{Display, Formatter};
2
3use crate::{Arg, Argument};
4
5/// A short or long option.
6///
7/// This enum can be returned by calls to
8/// [`Options::next_opt`][crate::Options::next_opt] and represents a
9/// short or long command-line option name (but not value).
10#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
11pub enum Opt<A: Argument> {
12    /// A short option, like `-f`. Does not include the leading `-`.
13    Short(A::ShortOpt),
14    /// A long option, like `--file`. Does not include the leading `--`.
15    Long(A),
16}
17
18impl<A: Argument> TryFrom<Arg<A>> for Opt<A> {
19    type Error = ();
20
21    fn try_from(value: Arg<A>) -> Result<Self, Self::Error> {
22        match value {
23            Arg::Short(short) => Ok(Self::Short(short)),
24            Arg::Long(long) => Ok(Self::Long(long)),
25            _ => Err(()),
26        }
27    }
28}
29
30impl<S: Display, A: Argument<ShortOpt = S> + Display> Display for Opt<A> {
31    fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
32        match self {
33            Opt::Short(c) => write!(f, "-{}", c),
34            Opt::Long(s) => write!(f, "--{}", s),
35        }
36    }
37}