summaryrefslogtreecommitdiffstats
path: root/vendor/clap/examples/tutorial_builder/04_01_enum.rs
diff options
context:
space:
mode:
Diffstat (limited to 'vendor/clap/examples/tutorial_builder/04_01_enum.rs')
-rw-r--r--vendor/clap/examples/tutorial_builder/04_01_enum.rs44
1 files changed, 39 insertions, 5 deletions
diff --git a/vendor/clap/examples/tutorial_builder/04_01_enum.rs b/vendor/clap/examples/tutorial_builder/04_01_enum.rs
index ad2177c23..e8cf70f5c 100644
--- a/vendor/clap/examples/tutorial_builder/04_01_enum.rs
+++ b/vendor/clap/examples/tutorial_builder/04_01_enum.rs
@@ -1,15 +1,49 @@
-// Note: this requires the `cargo` feature
+use clap::{arg, builder::PossibleValue, command, value_parser, ValueEnum};
-use clap::{arg, command, value_parser, ValueEnum};
-
-#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Mode {
Fast,
Slow,
}
+// Can also be derived] with feature flag `derive`
+impl ValueEnum for Mode {
+ fn value_variants<'a>() -> &'a [Self] {
+ &[Mode::Fast, Mode::Slow]
+ }
+
+ fn to_possible_value<'a>(&self) -> Option<PossibleValue<'a>> {
+ Some(match self {
+ Mode::Fast => PossibleValue::new("fast"),
+ Mode::Slow => PossibleValue::new("slow"),
+ })
+ }
+}
+
+impl std::fmt::Display for Mode {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ self.to_possible_value()
+ .expect("no values are skipped")
+ .get_name()
+ .fmt(f)
+ }
+}
+
+impl std::str::FromStr for Mode {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ for variant in Self::value_variants() {
+ if variant.to_possible_value().unwrap().matches(s, false) {
+ return Ok(*variant);
+ }
+ }
+ Err(format!("Invalid variant: {}", s))
+ }
+}
+
fn main() {
- let matches = command!()
+ let matches = command!() // requires `cargo` feature
.arg(
arg!(<MODE>)
.help("What mode to run the program in")