Skip to content

Commit 821cdf7

Browse files
committed
impl Display for Argument
1 parent 9a595c6 commit 821cdf7

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

src/lib.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,47 @@ impl<'a> Argument<'a> {
173173
}
174174
}
175175

176+
impl<'a> Display for Argument<'a> {
177+
/// Outputs a representation of the argument that approximates the original string.
178+
///
179+
/// This function manually attempts to recreate the original string that was parsed into this
180+
/// argument. It doesn't necessarily have to reflect the original, which is the case with
181+
/// values like `--option=value` - the `=` will be lost.
182+
///
183+
/// # Examples
184+
///
185+
/// ```rust
186+
/// use std::borrow::Cow;
187+
/// use sap::Argument;
188+
///
189+
/// // Long option
190+
/// let arg = Argument::Long("foo");
191+
/// assert_eq!(arg.to_string(), "--foo");
192+
///
193+
/// // Short option
194+
/// let arg = Argument::Short('o');
195+
/// assert_eq!(arg.to_string(), "-o");
196+
///
197+
/// // Value argument
198+
/// let arg = Argument::Value(Cow::Borrowed("bar"));
199+
/// assert_eq!(arg.to_string(), "bar");
200+
///
201+
/// // Stdio argument
202+
/// let arg = Argument::Stdio;
203+
/// assert_eq!(arg.to_string(), "-");
204+
/// ```
205+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206+
use Argument::{Long, Short, Stdio, Value};
207+
208+
match self {
209+
Long(s) => write!(f, "--{s}"),
210+
Short(ch) => write!(f, "-{ch}"),
211+
Value(cow) => write!(f, "{cow}"),
212+
Stdio => write!(f, "-"),
213+
}
214+
}
215+
}
216+
176217
/// A stateful command-line argument parser.
177218
///
178219
/// The `Parser` processes arguments one at a time using an iterator-based approach,

0 commit comments

Comments
 (0)