Struct clap::builder::PossibleValue

source ·
pub struct PossibleValue { /* private fields */ }
Expand description

A possible value of an argument.

This is used for specifying possible values of Args.

See also PossibleValuesParser

NOTE: Most likely you can use strings, rather than PossibleValue as it is only required to hide single values from help messages and shell completions or to attach help to possible values.

Examples

let cfg = Arg::new("config")
    .action(ArgAction::Set)
    .value_name("FILE")
    .value_parser([
        PossibleValue::new("fast"),
        PossibleValue::new("slow").help("slower than fast"),
        PossibleValue::new("secret speed").hide(true)
    ]);

Implementations§

Create a PossibleValue with its name.

The name will be used to decide whether this value was provided by the user to an argument.

NOTE: In case it is not hidden it will also be shown in help messages for arguments that use it as a possible value and have not hidden them through Arg::hide_possible_values(true).

Examples
PossibleValue::new("fast")
Examples found in repository?
src/builder/possible_value.rs (line 232)
231
232
233
    fn from(s: S) -> Self {
        Self::new(s)
    }
More examples
Hide additional examples
src/builder/value_parser.rs (line 1726)
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
    fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> {
        crate::util::TRUE_LITERALS
            .iter()
            .chain(crate::util::FALSE_LITERALS.iter())
            .copied()
            .map(|l| crate::builder::PossibleValue::new(l).hide(l != "true" && l != "false"))
    }
}

impl TypedValueParser for FalseyValueParser {
    type Value = bool;

    fn parse_ref(
        &self,
        cmd: &crate::Command,
        _arg: Option<&crate::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, crate::Error> {
        let value = ok!(value.to_str().ok_or_else(|| {
            crate::Error::invalid_utf8(
                cmd,
                crate::output::Usage::new(cmd).create_usage_with_title(&[]),
            )
        }));
        let value = if value.is_empty() {
            false
        } else {
            crate::util::str_to_bool(value).unwrap_or(true)
        };
        Ok(value)
    }

    fn possible_values(
        &self,
    ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
        Some(Box::new(Self::possible_values()))
    }
}

impl Default for FalseyValueParser {
    fn default() -> Self {
        Self::new()
    }
}

/// Parse bool-like string values, everything else is `true`
///
/// See also:
/// - [`ValueParser::bool`] for different human readable bool representations
/// - [`FalseyValueParser`] for assuming non-false is true
///
/// # Example
///
/// Usage:
/// ```rust
/// let mut cmd = clap::Command::new("raw")
///     .arg(
///         clap::Arg::new("append")
///             .value_parser(clap::builder::BoolishValueParser::new())
///             .required(true)
///     );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
/// let port: bool = *m.get_one("append")
///     .expect("required");
/// assert_eq!(port, true);
/// ```
///
/// Semantics:
/// ```rust
/// # use std::ffi::OsStr;
/// # use clap::builder::TypedValueParser;
/// # let cmd = clap::Command::new("test");
/// # let arg = None;
/// let value_parser = clap::builder::BoolishValueParser::new();
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("100")).is_err());
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("true")).unwrap(), true);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("Yes")).unwrap(), true);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oN")).unwrap(), true);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("1")).unwrap(), true);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("false")).unwrap(), false);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("No")).unwrap(), false);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oFF")).unwrap(), false);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), false);
/// ```
#[derive(Copy, Clone, Debug)]
#[non_exhaustive]
pub struct BoolishValueParser {}

impl BoolishValueParser {
    /// Parse bool-like string values, everything else is `true`
    pub fn new() -> Self {
        Self {}
    }

    fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> {
        crate::util::TRUE_LITERALS
            .iter()
            .chain(crate::util::FALSE_LITERALS.iter())
            .copied()
            .map(|l| crate::builder::PossibleValue::new(l).hide(l != "true" && l != "false"))
    }
src/util/color.rs (line 97)
94
95
96
97
98
99
100
101
102
    fn to_possible_value(&self) -> Option<PossibleValue> {
        Some(match self {
            Self::Auto => {
                PossibleValue::new("auto").help("Use colored output if writing to a terminal/TTY")
            }
            Self::Always => PossibleValue::new("always").help("Always use colored output"),
            Self::Never => PossibleValue::new("never").help("Never use colored output"),
        })
    }

Sets the help description of the value.

This is typically displayed in completions (where supported) and should be a short, one-line description.

Examples
PossibleValue::new("slow")
    .help("not fast")
Examples found in repository?
src/util/color.rs (line 97)
94
95
96
97
98
99
100
101
102
    fn to_possible_value(&self) -> Option<PossibleValue> {
        Some(match self {
            Self::Auto => {
                PossibleValue::new("auto").help("Use colored output if writing to a terminal/TTY")
            }
            Self::Always => PossibleValue::new("always").help("Always use colored output"),
            Self::Never => PossibleValue::new("never").help("Never use colored output"),
        })
    }

Hides this value from help and shell completions.

This is an alternative to hiding through Arg::hide_possible_values(true), if you only want to hide some values.

Examples
PossibleValue::new("secret")
    .hide(true)
Examples found in repository?
src/builder/value_parser.rs (line 1726)
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
    fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> {
        crate::util::TRUE_LITERALS
            .iter()
            .chain(crate::util::FALSE_LITERALS.iter())
            .copied()
            .map(|l| crate::builder::PossibleValue::new(l).hide(l != "true" && l != "false"))
    }
}

impl TypedValueParser for FalseyValueParser {
    type Value = bool;

    fn parse_ref(
        &self,
        cmd: &crate::Command,
        _arg: Option<&crate::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, crate::Error> {
        let value = ok!(value.to_str().ok_or_else(|| {
            crate::Error::invalid_utf8(
                cmd,
                crate::output::Usage::new(cmd).create_usage_with_title(&[]),
            )
        }));
        let value = if value.is_empty() {
            false
        } else {
            crate::util::str_to_bool(value).unwrap_or(true)
        };
        Ok(value)
    }

    fn possible_values(
        &self,
    ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
        Some(Box::new(Self::possible_values()))
    }
}

impl Default for FalseyValueParser {
    fn default() -> Self {
        Self::new()
    }
}

/// Parse bool-like string values, everything else is `true`
///
/// See also:
/// - [`ValueParser::bool`] for different human readable bool representations
/// - [`FalseyValueParser`] for assuming non-false is true
///
/// # Example
///
/// Usage:
/// ```rust
/// let mut cmd = clap::Command::new("raw")
///     .arg(
///         clap::Arg::new("append")
///             .value_parser(clap::builder::BoolishValueParser::new())
///             .required(true)
///     );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
/// let port: bool = *m.get_one("append")
///     .expect("required");
/// assert_eq!(port, true);
/// ```
///
/// Semantics:
/// ```rust
/// # use std::ffi::OsStr;
/// # use clap::builder::TypedValueParser;
/// # let cmd = clap::Command::new("test");
/// # let arg = None;
/// let value_parser = clap::builder::BoolishValueParser::new();
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("100")).is_err());
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("true")).unwrap(), true);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("Yes")).unwrap(), true);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oN")).unwrap(), true);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("1")).unwrap(), true);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("false")).unwrap(), false);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("No")).unwrap(), false);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oFF")).unwrap(), false);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), false);
/// ```
#[derive(Copy, Clone, Debug)]
#[non_exhaustive]
pub struct BoolishValueParser {}

impl BoolishValueParser {
    /// Parse bool-like string values, everything else is `true`
    pub fn new() -> Self {
        Self {}
    }

    fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> {
        crate::util::TRUE_LITERALS
            .iter()
            .chain(crate::util::FALSE_LITERALS.iter())
            .copied()
            .map(|l| crate::builder::PossibleValue::new(l).hide(l != "true" && l != "false"))
    }

Sets a hidden alias for this argument value.

Examples
PossibleValue::new("slow")
    .alias("not-fast")

Sets multiple hidden aliases for this argument value.

Examples
PossibleValue::new("slow")
    .aliases(["not-fast", "snake-like"])

Reflection

Get the name of the argument value

Examples found in repository?
src/builder/possible_value.rs (line 201)
200
201
202
    pub fn get_name_and_aliases(&self) -> impl Iterator<Item = &str> + '_ {
        std::iter::once(self.get_name()).chain(self.aliases.iter().map(|s| s.as_str()))
    }
More examples
Hide additional examples
src/util/color.rs (line 71)
68
69
70
71
72
73
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.to_possible_value()
            .expect("no values are skipped")
            .get_name()
            .fmt(f)
    }
src/builder/value_parser.rs (line 1051)
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
    fn parse_ref(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, crate::Error> {
        let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false);
        let possible_vals = || {
            E::value_variants()
                .iter()
                .filter_map(|v| v.to_possible_value())
                .filter(|v| !v.is_hide_set())
                .map(|v| v.get_name().to_owned())
                .collect::<Vec<_>>()
        };

        let value = ok!(value.to_str().ok_or_else(|| {
            crate::Error::invalid_value(
                cmd,
                value.to_string_lossy().into_owned(),
                &possible_vals(),
                arg.map(ToString::to_string)
                    .unwrap_or_else(|| "...".to_owned()),
            )
        }));
        let value = ok!(E::value_variants()
            .iter()
            .find(|v| {
                v.to_possible_value()
                    .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value")
                    .matches(value, ignore_case)
            })
            .ok_or_else(|| {
            crate::Error::invalid_value(
                cmd,
                value.to_owned(),
                &possible_vals(),
                arg.map(ToString::to_string)
                    .unwrap_or_else(|| "...".to_owned()),
            )
            }))
            .clone();
        Ok(value)
    }

    fn possible_values(
        &self,
    ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
        Some(Box::new(
            E::value_variants()
                .iter()
                .filter_map(|v| v.to_possible_value()),
        ))
    }
}

impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> Default for EnumValueParser<E> {
    fn default() -> Self {
        Self::new()
    }
}

/// Verify the value is from an enumerated set of [`PossibleValue`][crate::builder::PossibleValue].
///
/// See also:
/// - [`EnumValueParser`] for directly supporting [`ValueEnum`][crate::ValueEnum] types
/// - [`TypedValueParser::map`] for adapting values to a more specialized type, like an external
///   enums that can't implement [`ValueEnum`][crate::ValueEnum]
///
/// # Example
///
/// Usage:
/// ```rust
/// let mut cmd = clap::Command::new("raw")
///     .arg(
///         clap::Arg::new("color")
///             .value_parser(clap::builder::PossibleValuesParser::new(["always", "auto", "never"]))
///             .required(true)
///     );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "always"]).unwrap();
/// let port: &String = m.get_one("color")
///     .expect("required");
/// assert_eq!(port, "always");
/// ```
///
/// Semantics:
/// ```rust
/// # use std::ffi::OsStr;
/// # use clap::builder::TypedValueParser;
/// # let cmd = clap::Command::new("test");
/// # let arg = None;
/// let value_parser = clap::builder::PossibleValuesParser::new(["always", "auto", "never"]);
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("always")).unwrap(), "always");
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("auto")).unwrap(), "auto");
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("never")).unwrap(), "never");
/// ```
#[derive(Clone, Debug)]
pub struct PossibleValuesParser(Vec<super::PossibleValue>);

impl PossibleValuesParser {
    /// Verify the value is from an enumerated set pf [`PossibleValue`][crate::builder::PossibleValue].
    pub fn new(values: impl Into<PossibleValuesParser>) -> Self {
        values.into()
    }
}

impl TypedValueParser for PossibleValuesParser {
    type Value = String;

    fn parse_ref(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, crate::Error> {
        TypedValueParser::parse(self, cmd, arg, value.to_owned())
    }

    fn parse(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        value: std::ffi::OsString,
    ) -> Result<String, crate::Error> {
        let value = ok!(value.into_string().map_err(|_| {
            crate::Error::invalid_utf8(
                cmd,
                crate::output::Usage::new(cmd).create_usage_with_title(&[]),
            )
        }));

        let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false);
        if self.0.iter().any(|v| v.matches(&value, ignore_case)) {
            Ok(value)
        } else {
            let possible_vals = self
                .0
                .iter()
                .filter(|v| !v.is_hide_set())
                .map(|v| v.get_name().to_owned())
                .collect::<Vec<_>>();

            Err(crate::Error::invalid_value(
                cmd,
                value,
                &possible_vals,
                arg.map(ToString::to_string)
                    .unwrap_or_else(|| "...".to_owned()),
            ))
        }
    }

    fn possible_values(
        &self,
    ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
        Some(Box::new(self.0.iter().cloned()))
    }
}

impl<I, T> From<I> for PossibleValuesParser
where
    I: IntoIterator<Item = T>,
    T: Into<super::PossibleValue>,
{
    fn from(values: I) -> Self {
        Self(values.into_iter().map(|t| t.into()).collect())
    }
}

/// Parse number that fall within a range of values
///
/// **NOTE:** To capture negative values, you will also need to set
/// [`Arg::allow_negative_numbers`][crate::Arg::allow_negative_numbers] or
/// [`Arg::allow_hyphen_values`][crate::Arg::allow_hyphen_values].
///
/// # Example
///
/// Usage:
/// ```rust
/// let mut cmd = clap::Command::new("raw")
///     .arg(
///         clap::Arg::new("port")
///             .long("port")
///             .value_parser(clap::value_parser!(u16).range(3000..))
///             .action(clap::ArgAction::Set)
///             .required(true)
///     );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
/// let port: u16 = *m.get_one("port")
///     .expect("required");
/// assert_eq!(port, 3001);
/// ```
///
/// Semantics:
/// ```rust
/// # use std::ffi::OsStr;
/// # use clap::builder::TypedValueParser;
/// # let cmd = clap::Command::new("test");
/// # let arg = None;
/// let value_parser = clap::builder::RangedI64ValueParser::<i32>::new().range(-1..200);
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-200")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("300")).is_err());
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("-1")).unwrap(), -1);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), 0);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("50")).unwrap(), 50);
/// ```
#[derive(Copy, Clone, Debug)]
pub struct RangedI64ValueParser<T: std::convert::TryFrom<i64> + Clone + Send + Sync = i64> {
    bounds: (std::ops::Bound<i64>, std::ops::Bound<i64>),
    target: std::marker::PhantomData<T>,
}

impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync> RangedI64ValueParser<T> {
    /// Select full range of `i64`
    pub fn new() -> Self {
        Self::from(..)
    }

    /// Narrow the supported range
    pub fn range<B: RangeBounds<i64>>(mut self, range: B) -> Self {
        // Consideration: when the user does `value_parser!(u8).range()`
        // - Avoid programming mistakes by accidentally expanding the range
        // - Make it convenient to limit the range like with `..10`
        let start = match range.start_bound() {
            l @ std::ops::Bound::Included(i) => {
                debug_assert!(
                    self.bounds.contains(i),
                    "{} must be in {:?}",
                    i,
                    self.bounds
                );
                l.cloned()
            }
            l @ std::ops::Bound::Excluded(i) => {
                debug_assert!(
                    self.bounds.contains(&i.saturating_add(1)),
                    "{} must be in {:?}",
                    i,
                    self.bounds
                );
                l.cloned()
            }
            std::ops::Bound::Unbounded => self.bounds.start_bound().cloned(),
        };
        let end = match range.end_bound() {
            l @ std::ops::Bound::Included(i) => {
                debug_assert!(
                    self.bounds.contains(i),
                    "{} must be in {:?}",
                    i,
                    self.bounds
                );
                l.cloned()
            }
            l @ std::ops::Bound::Excluded(i) => {
                debug_assert!(
                    self.bounds.contains(&i.saturating_sub(1)),
                    "{} must be in {:?}",
                    i,
                    self.bounds
                );
                l.cloned()
            }
            std::ops::Bound::Unbounded => self.bounds.end_bound().cloned(),
        };
        self.bounds = (start, end);
        self
    }

    fn format_bounds(&self) -> String {
        let mut result = match self.bounds.0 {
            std::ops::Bound::Included(i) => i.to_string(),
            std::ops::Bound::Excluded(i) => i.saturating_add(1).to_string(),
            std::ops::Bound::Unbounded => i64::MIN.to_string(),
        };
        result.push_str("..");
        match self.bounds.1 {
            std::ops::Bound::Included(i) => {
                result.push('=');
                result.push_str(&i.to_string());
            }
            std::ops::Bound::Excluded(i) => {
                result.push_str(&i.to_string());
            }
            std::ops::Bound::Unbounded => {
                result.push_str(&i64::MAX.to_string());
            }
        }
        result
    }
}

impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync + 'static> TypedValueParser
    for RangedI64ValueParser<T>
where
    <T as std::convert::TryFrom<i64>>::Error: Send + Sync + 'static + std::error::Error + ToString,
{
    type Value = T;

    fn parse_ref(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        raw_value: &std::ffi::OsStr,
    ) -> Result<Self::Value, crate::Error> {
        let value = ok!(raw_value.to_str().ok_or_else(|| {
            crate::Error::invalid_utf8(
                cmd,
                crate::output::Usage::new(cmd).create_usage_with_title(&[]),
            )
        }));
        let value = ok!(value.parse::<i64>().map_err(|err| {
            let arg = arg
                .map(|a| a.to_string())
                .unwrap_or_else(|| "...".to_owned());
            crate::Error::value_validation(
                arg,
                raw_value.to_string_lossy().into_owned(),
                err.into(),
            )
            .with_cmd(cmd)
        }));
        if !self.bounds.contains(&value) {
            let arg = arg
                .map(|a| a.to_string())
                .unwrap_or_else(|| "...".to_owned());
            return Err(crate::Error::value_validation(
                arg,
                raw_value.to_string_lossy().into_owned(),
                format!("{} is not in {}", value, self.format_bounds()).into(),
            )
            .with_cmd(cmd));
        }

        let value: Result<Self::Value, _> = value.try_into();
        let value = ok!(value.map_err(|err| {
            let arg = arg
                .map(|a| a.to_string())
                .unwrap_or_else(|| "...".to_owned());
            crate::Error::value_validation(
                arg,
                raw_value.to_string_lossy().into_owned(),
                err.into(),
            )
            .with_cmd(cmd)
        }));

        Ok(value)
    }
}

impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync, B: RangeBounds<i64>> From<B>
    for RangedI64ValueParser<T>
{
    fn from(range: B) -> Self {
        Self {
            bounds: (range.start_bound().cloned(), range.end_bound().cloned()),
            target: Default::default(),
        }
    }
}

impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync> Default for RangedI64ValueParser<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Parse number that fall within a range of values
///
/// # Example
///
/// Usage:
/// ```rust
/// let mut cmd = clap::Command::new("raw")
///     .arg(
///         clap::Arg::new("port")
///             .long("port")
///             .value_parser(clap::value_parser!(u64).range(3000..))
///             .action(clap::ArgAction::Set)
///             .required(true)
///     );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
/// let port: u64 = *m.get_one("port")
///     .expect("required");
/// assert_eq!(port, 3001);
/// ```
///
/// Semantics:
/// ```rust
/// # use std::ffi::OsStr;
/// # use clap::builder::TypedValueParser;
/// # let cmd = clap::Command::new("test");
/// # let arg = None;
/// let value_parser = clap::builder::RangedU64ValueParser::<u32>::new().range(0..200);
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-200")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("300")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-1")).is_err());
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), 0);
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("50")).unwrap(), 50);
/// ```
#[derive(Copy, Clone, Debug)]
pub struct RangedU64ValueParser<T: std::convert::TryFrom<u64> = u64> {
    bounds: (std::ops::Bound<u64>, std::ops::Bound<u64>),
    target: std::marker::PhantomData<T>,
}

impl<T: std::convert::TryFrom<u64>> RangedU64ValueParser<T> {
    /// Select full range of `u64`
    pub fn new() -> Self {
        Self::from(..)
    }

    /// Narrow the supported range
    pub fn range<B: RangeBounds<u64>>(mut self, range: B) -> Self {
        // Consideration: when the user does `value_parser!(u8).range()`
        // - Avoid programming mistakes by accidentally expanding the range
        // - Make it convenient to limit the range like with `..10`
        let start = match range.start_bound() {
            l @ std::ops::Bound::Included(i) => {
                debug_assert!(
                    self.bounds.contains(i),
                    "{} must be in {:?}",
                    i,
                    self.bounds
                );
                l.cloned()
            }
            l @ std::ops::Bound::Excluded(i) => {
                debug_assert!(
                    self.bounds.contains(&i.saturating_add(1)),
                    "{} must be in {:?}",
                    i,
                    self.bounds
                );
                l.cloned()
            }
            std::ops::Bound::Unbounded => self.bounds.start_bound().cloned(),
        };
        let end = match range.end_bound() {
            l @ std::ops::Bound::Included(i) => {
                debug_assert!(
                    self.bounds.contains(i),
                    "{} must be in {:?}",
                    i,
                    self.bounds
                );
                l.cloned()
            }
            l @ std::ops::Bound::Excluded(i) => {
                debug_assert!(
                    self.bounds.contains(&i.saturating_sub(1)),
                    "{} must be in {:?}",
                    i,
                    self.bounds
                );
                l.cloned()
            }
            std::ops::Bound::Unbounded => self.bounds.end_bound().cloned(),
        };
        self.bounds = (start, end);
        self
    }

    fn format_bounds(&self) -> String {
        let mut result = match self.bounds.0 {
            std::ops::Bound::Included(i) => i.to_string(),
            std::ops::Bound::Excluded(i) => i.saturating_add(1).to_string(),
            std::ops::Bound::Unbounded => u64::MIN.to_string(),
        };
        result.push_str("..");
        match self.bounds.1 {
            std::ops::Bound::Included(i) => {
                result.push('=');
                result.push_str(&i.to_string());
            }
            std::ops::Bound::Excluded(i) => {
                result.push_str(&i.to_string());
            }
            std::ops::Bound::Unbounded => {
                result.push_str(&u64::MAX.to_string());
            }
        }
        result
    }
}

impl<T: std::convert::TryFrom<u64> + Clone + Send + Sync + 'static> TypedValueParser
    for RangedU64ValueParser<T>
where
    <T as std::convert::TryFrom<u64>>::Error: Send + Sync + 'static + std::error::Error + ToString,
{
    type Value = T;

    fn parse_ref(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        raw_value: &std::ffi::OsStr,
    ) -> Result<Self::Value, crate::Error> {
        let value = ok!(raw_value.to_str().ok_or_else(|| {
            crate::Error::invalid_utf8(
                cmd,
                crate::output::Usage::new(cmd).create_usage_with_title(&[]),
            )
        }));
        let value = ok!(value.parse::<u64>().map_err(|err| {
            let arg = arg
                .map(|a| a.to_string())
                .unwrap_or_else(|| "...".to_owned());
            crate::Error::value_validation(
                arg,
                raw_value.to_string_lossy().into_owned(),
                err.into(),
            )
            .with_cmd(cmd)
        }));
        if !self.bounds.contains(&value) {
            let arg = arg
                .map(|a| a.to_string())
                .unwrap_or_else(|| "...".to_owned());
            return Err(crate::Error::value_validation(
                arg,
                raw_value.to_string_lossy().into_owned(),
                format!("{} is not in {}", value, self.format_bounds()).into(),
            )
            .with_cmd(cmd));
        }

        let value: Result<Self::Value, _> = value.try_into();
        let value = ok!(value.map_err(|err| {
            let arg = arg
                .map(|a| a.to_string())
                .unwrap_or_else(|| "...".to_owned());
            crate::Error::value_validation(
                arg,
                raw_value.to_string_lossy().into_owned(),
                err.into(),
            )
            .with_cmd(cmd)
        }));

        Ok(value)
    }
}

impl<T: std::convert::TryFrom<u64>, B: RangeBounds<u64>> From<B> for RangedU64ValueParser<T> {
    fn from(range: B) -> Self {
        Self {
            bounds: (range.start_bound().cloned(), range.end_bound().cloned()),
            target: Default::default(),
        }
    }
}

impl<T: std::convert::TryFrom<u64>> Default for RangedU64ValueParser<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Implementation for [`ValueParser::bool`]
///
/// Useful for composing new [`TypedValueParser`]s
#[derive(Copy, Clone, Debug)]
#[non_exhaustive]
pub struct BoolValueParser {}

impl BoolValueParser {
    /// Implementation for [`ValueParser::bool`]
    pub fn new() -> Self {
        Self {}
    }

    fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> {
        ["true", "false"]
            .iter()
            .copied()
            .map(crate::builder::PossibleValue::new)
    }
}

impl TypedValueParser for BoolValueParser {
    type Value = bool;

    fn parse_ref(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, crate::Error> {
        let value = if value == std::ffi::OsStr::new("true") {
            true
        } else if value == std::ffi::OsStr::new("false") {
            false
        } else {
            // Intentionally showing hidden as we hide all of them
            let possible_vals = Self::possible_values()
                .map(|v| v.get_name().to_owned())
                .collect::<Vec<_>>();

            return Err(crate::Error::invalid_value(
                cmd,
                value.to_string_lossy().into_owned(),
                &possible_vals,
                arg.map(ToString::to_string)
                    .unwrap_or_else(|| "...".to_owned()),
            ));
        };
        Ok(value)
    }
src/parser/parser.rs (line 1319)
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
    fn verify_num_args(&self, arg: &Arg, raw_vals: &[OsString]) -> ClapResult<()> {
        if self.cmd.is_ignore_errors_set() {
            return Ok(());
        }

        let actual = raw_vals.len();
        let expected = arg.get_num_args().expect(INTERNAL_ERROR_MSG);

        if 0 < expected.min_values() && actual == 0 {
            // Issue 665 (https://github.com/clap-rs/clap/issues/665)
            // Issue 1105 (https://github.com/clap-rs/clap/issues/1105)
            return Err(ClapError::empty_value(
                self.cmd,
                &super::get_possible_values_cli(arg)
                    .iter()
                    .filter(|pv| !pv.is_hide_set())
                    .map(|n| n.get_name().to_owned())
                    .collect::<Vec<_>>(),
                arg.to_string(),
            ));
        } else if let Some(expected) = expected.num_values() {
            if expected != actual {
                debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues");
                return Err(ClapError::wrong_number_of_values(
                    self.cmd,
                    arg.to_string(),
                    expected,
                    actual,
                    Usage::new(self.cmd).create_usage_with_title(&[]),
                ));
            }
        } else if actual < expected.min_values() {
            return Err(ClapError::too_few_values(
                self.cmd,
                arg.to_string(),
                expected.min_values(),
                actual,
                Usage::new(self.cmd).create_usage_with_title(&[]),
            ));
        } else if expected.max_values() < actual {
            debug!("Validator::validate_arg_num_vals: Sending error TooManyValues");
            return Err(ClapError::too_many_values(
                self.cmd,
                raw_vals
                    .last()
                    .expect(INTERNAL_ERROR_MSG)
                    .to_string_lossy()
                    .into_owned(),
                arg.to_string(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            ));
        }

        Ok(())
    }
src/parser/validator.rs (line 48)
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    pub(crate) fn validate(
        &mut self,
        parse_state: ParseState,
        matcher: &mut ArgMatcher,
    ) -> ClapResult<()> {
        debug!("Validator::validate");
        let conflicts = Conflicts::with_args(self.cmd, matcher);
        let has_subcmd = matcher.subcommand_name().is_some();

        if let ParseState::Opt(a) = parse_state {
            debug!("Validator::validate: needs_val_of={:?}", a);

            let o = &self.cmd[&a];
            let should_err = if let Some(v) = matcher.args.get(o.get_id()) {
                v.all_val_groups_empty() && o.get_min_vals() != 0
            } else {
                true
            };
            if should_err {
                return Err(Error::empty_value(
                    self.cmd,
                    &get_possible_values_cli(o)
                        .iter()
                        .filter(|pv| !pv.is_hide_set())
                        .map(|n| n.get_name().to_owned())
                        .collect::<Vec<_>>(),
                    o.to_string(),
                ));
            }
        }

        if !has_subcmd && self.cmd.is_arg_required_else_help_set() {
            let num_user_values = matcher
                .args()
                .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent))
                .count();
            if num_user_values == 0 {
                let message = self.cmd.write_help_err(false);
                return Err(Error::display_help_error(self.cmd, message));
            }
        }
        if !has_subcmd && self.cmd.is_subcommand_required_set() {
            let bn = self
                .cmd
                .get_bin_name()
                .unwrap_or_else(|| self.cmd.get_name());
            return Err(Error::missing_subcommand(
                self.cmd,
                bn.to_string(),
                self.cmd
                    .all_subcommand_names()
                    .map(|s| s.to_owned())
                    .collect::<Vec<_>>(),
                Usage::new(self.cmd)
                    .required(&self.required)
                    .create_usage_with_title(&[]),
            ));
        }

        ok!(self.validate_conflicts(matcher, &conflicts));
        if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) {
            ok!(self.validate_required(matcher, &conflicts));
        }

        Ok(())
    }
src/output/help_template.rs (line 645)
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
    fn help(
        &mut self,
        arg: Option<&Arg>,
        about: &StyledStr,
        spec_vals: &str,
        next_line_help: bool,
        longest: usize,
    ) {
        debug!("HelpTemplate::help");

        // Is help on next line, if so then indent
        if next_line_help {
            debug!("HelpTemplate::help: Next Line...{:?}", next_line_help);
            self.none("\n");
            self.none(TAB);
            self.none(NEXT_LINE_INDENT);
        }

        let spaces = if next_line_help {
            TAB.len() + NEXT_LINE_INDENT.len()
        } else if let Some(true) = arg.map(|a| a.is_positional()) {
            longest + TAB_WIDTH * 2
        } else {
            longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
        };
        let trailing_indent = spaces; // Don't indent any further than the first line is indented
        let trailing_indent = self.get_spaces(trailing_indent);

        let mut help = about.clone();
        replace_newline_var(&mut help);
        if !spec_vals.is_empty() {
            if !help.is_empty() {
                let sep = if self.use_long && arg.is_some() {
                    "\n\n"
                } else {
                    " "
                };
                help.none(sep);
            }
            help.none(spec_vals);
        }
        let avail_chars = self.term_w.saturating_sub(spaces);
        debug!(
            "HelpTemplate::help: help_width={}, spaces={}, avail={}",
            spaces,
            help.display_width(),
            avail_chars
        );
        help.wrap(avail_chars);
        help.indent("", &trailing_indent);
        let help_is_empty = help.is_empty();
        self.writer.extend(help.into_iter());
        if let Some(arg) = arg {
            const DASH_SPACE: usize = "- ".len();
            const COLON_SPACE: usize = ": ".len();
            let possible_vals = arg.get_possible_values();
            if self.use_long
                && !arg.is_hide_possible_values_set()
                && possible_vals.iter().any(PossibleValue::should_show_help)
            {
                debug!(
                    "HelpTemplate::help: Found possible vals...{:?}",
                    possible_vals
                );
                if !help_is_empty {
                    self.none("\n\n");
                    self.spaces(spaces);
                }
                self.none("Possible values:");
                let longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
                    .max()
                    .expect("Only called with possible value");
                let help_longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_help().map(|h| h.display_width()))
                    .max()
                    .expect("Only called with possible value with help");
                // should new line
                let taken = longest + spaces + DASH_SPACE;

                let possible_value_new_line =
                    self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;

                let spaces = spaces + TAB_WIDTH - DASH_SPACE;
                let trailing_indent = if possible_value_new_line {
                    spaces + DASH_SPACE
                } else {
                    spaces + longest + DASH_SPACE + COLON_SPACE
                };
                let trailing_indent = self.get_spaces(trailing_indent);

                for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
                    self.none("\n");
                    self.spaces(spaces);
                    self.none("- ");
                    self.literal(pv.get_name());
                    if let Some(help) = pv.get_help() {
                        debug!("HelpTemplate::help: Possible Value help");

                        if possible_value_new_line {
                            self.none(":\n");
                            self.spaces(trailing_indent.len());
                        } else {
                            self.none(": ");
                            // To align help messages
                            self.spaces(longest - display_width(pv.get_name()));
                        }

                        let avail_chars = if self.term_w > trailing_indent.len() {
                            self.term_w - trailing_indent.len()
                        } else {
                            usize::MAX
                        };

                        let mut help = help.clone();
                        replace_newline_var(&mut help);
                        help.wrap(avail_chars);
                        help.indent("", &trailing_indent);
                        self.writer.extend(help.into_iter());
                    }
                }
            }
        }
    }

Get the help specified for this argument, if any

Examples found in repository?
src/builder/possible_value.rs (line 165)
163
164
165
166
167
168
169
    pub(crate) fn get_visible_help(&self) -> Option<&StyledStr> {
        if !self.hide {
            self.get_help()
        } else {
            None
        }
    }
More examples
Hide additional examples
src/output/help_template.rs (line 646)
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
    fn help(
        &mut self,
        arg: Option<&Arg>,
        about: &StyledStr,
        spec_vals: &str,
        next_line_help: bool,
        longest: usize,
    ) {
        debug!("HelpTemplate::help");

        // Is help on next line, if so then indent
        if next_line_help {
            debug!("HelpTemplate::help: Next Line...{:?}", next_line_help);
            self.none("\n");
            self.none(TAB);
            self.none(NEXT_LINE_INDENT);
        }

        let spaces = if next_line_help {
            TAB.len() + NEXT_LINE_INDENT.len()
        } else if let Some(true) = arg.map(|a| a.is_positional()) {
            longest + TAB_WIDTH * 2
        } else {
            longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
        };
        let trailing_indent = spaces; // Don't indent any further than the first line is indented
        let trailing_indent = self.get_spaces(trailing_indent);

        let mut help = about.clone();
        replace_newline_var(&mut help);
        if !spec_vals.is_empty() {
            if !help.is_empty() {
                let sep = if self.use_long && arg.is_some() {
                    "\n\n"
                } else {
                    " "
                };
                help.none(sep);
            }
            help.none(spec_vals);
        }
        let avail_chars = self.term_w.saturating_sub(spaces);
        debug!(
            "HelpTemplate::help: help_width={}, spaces={}, avail={}",
            spaces,
            help.display_width(),
            avail_chars
        );
        help.wrap(avail_chars);
        help.indent("", &trailing_indent);
        let help_is_empty = help.is_empty();
        self.writer.extend(help.into_iter());
        if let Some(arg) = arg {
            const DASH_SPACE: usize = "- ".len();
            const COLON_SPACE: usize = ": ".len();
            let possible_vals = arg.get_possible_values();
            if self.use_long
                && !arg.is_hide_possible_values_set()
                && possible_vals.iter().any(PossibleValue::should_show_help)
            {
                debug!(
                    "HelpTemplate::help: Found possible vals...{:?}",
                    possible_vals
                );
                if !help_is_empty {
                    self.none("\n\n");
                    self.spaces(spaces);
                }
                self.none("Possible values:");
                let longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
                    .max()
                    .expect("Only called with possible value");
                let help_longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_help().map(|h| h.display_width()))
                    .max()
                    .expect("Only called with possible value with help");
                // should new line
                let taken = longest + spaces + DASH_SPACE;

                let possible_value_new_line =
                    self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;

                let spaces = spaces + TAB_WIDTH - DASH_SPACE;
                let trailing_indent = if possible_value_new_line {
                    spaces + DASH_SPACE
                } else {
                    spaces + longest + DASH_SPACE + COLON_SPACE
                };
                let trailing_indent = self.get_spaces(trailing_indent);

                for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
                    self.none("\n");
                    self.spaces(spaces);
                    self.none("- ");
                    self.literal(pv.get_name());
                    if let Some(help) = pv.get_help() {
                        debug!("HelpTemplate::help: Possible Value help");

                        if possible_value_new_line {
                            self.none(":\n");
                            self.spaces(trailing_indent.len());
                        } else {
                            self.none(": ");
                            // To align help messages
                            self.spaces(longest - display_width(pv.get_name()));
                        }

                        let avail_chars = if self.term_w > trailing_indent.len() {
                            self.term_w - trailing_indent.len()
                        } else {
                            usize::MAX
                        };

                        let mut help = help.clone();
                        replace_newline_var(&mut help);
                        help.wrap(avail_chars);
                        help.indent("", &trailing_indent);
                        self.writer.extend(help.into_iter());
                    }
                }
            }
        }
    }

Report if PossibleValue::hide is set

Examples found in repository?
src/builder/value_parser.rs (line 1050)
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
    fn parse_ref(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, crate::Error> {
        let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false);
        let possible_vals = || {
            E::value_variants()
                .iter()
                .filter_map(|v| v.to_possible_value())
                .filter(|v| !v.is_hide_set())
                .map(|v| v.get_name().to_owned())
                .collect::<Vec<_>>()
        };

        let value = ok!(value.to_str().ok_or_else(|| {
            crate::Error::invalid_value(
                cmd,
                value.to_string_lossy().into_owned(),
                &possible_vals(),
                arg.map(ToString::to_string)
                    .unwrap_or_else(|| "...".to_owned()),
            )
        }));
        let value = ok!(E::value_variants()
            .iter()
            .find(|v| {
                v.to_possible_value()
                    .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value")
                    .matches(value, ignore_case)
            })
            .ok_or_else(|| {
            crate::Error::invalid_value(
                cmd,
                value.to_owned(),
                &possible_vals(),
                arg.map(ToString::to_string)
                    .unwrap_or_else(|| "...".to_owned()),
            )
            }))
            .clone();
        Ok(value)
    }

    fn possible_values(
        &self,
    ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
        Some(Box::new(
            E::value_variants()
                .iter()
                .filter_map(|v| v.to_possible_value()),
        ))
    }
}

impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> Default for EnumValueParser<E> {
    fn default() -> Self {
        Self::new()
    }
}

/// Verify the value is from an enumerated set of [`PossibleValue`][crate::builder::PossibleValue].
///
/// See also:
/// - [`EnumValueParser`] for directly supporting [`ValueEnum`][crate::ValueEnum] types
/// - [`TypedValueParser::map`] for adapting values to a more specialized type, like an external
///   enums that can't implement [`ValueEnum`][crate::ValueEnum]
///
/// # Example
///
/// Usage:
/// ```rust
/// let mut cmd = clap::Command::new("raw")
///     .arg(
///         clap::Arg::new("color")
///             .value_parser(clap::builder::PossibleValuesParser::new(["always", "auto", "never"]))
///             .required(true)
///     );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "always"]).unwrap();
/// let port: &String = m.get_one("color")
///     .expect("required");
/// assert_eq!(port, "always");
/// ```
///
/// Semantics:
/// ```rust
/// # use std::ffi::OsStr;
/// # use clap::builder::TypedValueParser;
/// # let cmd = clap::Command::new("test");
/// # let arg = None;
/// let value_parser = clap::builder::PossibleValuesParser::new(["always", "auto", "never"]);
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("always")).unwrap(), "always");
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("auto")).unwrap(), "auto");
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("never")).unwrap(), "never");
/// ```
#[derive(Clone, Debug)]
pub struct PossibleValuesParser(Vec<super::PossibleValue>);

impl PossibleValuesParser {
    /// Verify the value is from an enumerated set pf [`PossibleValue`][crate::builder::PossibleValue].
    pub fn new(values: impl Into<PossibleValuesParser>) -> Self {
        values.into()
    }
}

impl TypedValueParser for PossibleValuesParser {
    type Value = String;

    fn parse_ref(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, crate::Error> {
        TypedValueParser::parse(self, cmd, arg, value.to_owned())
    }

    fn parse(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        value: std::ffi::OsString,
    ) -> Result<String, crate::Error> {
        let value = ok!(value.into_string().map_err(|_| {
            crate::Error::invalid_utf8(
                cmd,
                crate::output::Usage::new(cmd).create_usage_with_title(&[]),
            )
        }));

        let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false);
        if self.0.iter().any(|v| v.matches(&value, ignore_case)) {
            Ok(value)
        } else {
            let possible_vals = self
                .0
                .iter()
                .filter(|v| !v.is_hide_set())
                .map(|v| v.get_name().to_owned())
                .collect::<Vec<_>>();

            Err(crate::Error::invalid_value(
                cmd,
                value,
                &possible_vals,
                arg.map(ToString::to_string)
                    .unwrap_or_else(|| "...".to_owned()),
            ))
        }
    }
More examples
Hide additional examples
src/parser/parser.rs (line 1318)
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
    fn verify_num_args(&self, arg: &Arg, raw_vals: &[OsString]) -> ClapResult<()> {
        if self.cmd.is_ignore_errors_set() {
            return Ok(());
        }

        let actual = raw_vals.len();
        let expected = arg.get_num_args().expect(INTERNAL_ERROR_MSG);

        if 0 < expected.min_values() && actual == 0 {
            // Issue 665 (https://github.com/clap-rs/clap/issues/665)
            // Issue 1105 (https://github.com/clap-rs/clap/issues/1105)
            return Err(ClapError::empty_value(
                self.cmd,
                &super::get_possible_values_cli(arg)
                    .iter()
                    .filter(|pv| !pv.is_hide_set())
                    .map(|n| n.get_name().to_owned())
                    .collect::<Vec<_>>(),
                arg.to_string(),
            ));
        } else if let Some(expected) = expected.num_values() {
            if expected != actual {
                debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues");
                return Err(ClapError::wrong_number_of_values(
                    self.cmd,
                    arg.to_string(),
                    expected,
                    actual,
                    Usage::new(self.cmd).create_usage_with_title(&[]),
                ));
            }
        } else if actual < expected.min_values() {
            return Err(ClapError::too_few_values(
                self.cmd,
                arg.to_string(),
                expected.min_values(),
                actual,
                Usage::new(self.cmd).create_usage_with_title(&[]),
            ));
        } else if expected.max_values() < actual {
            debug!("Validator::validate_arg_num_vals: Sending error TooManyValues");
            return Err(ClapError::too_many_values(
                self.cmd,
                raw_vals
                    .last()
                    .expect(INTERNAL_ERROR_MSG)
                    .to_string_lossy()
                    .into_owned(),
                arg.to_string(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            ));
        }

        Ok(())
    }
src/parser/validator.rs (line 47)
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    pub(crate) fn validate(
        &mut self,
        parse_state: ParseState,
        matcher: &mut ArgMatcher,
    ) -> ClapResult<()> {
        debug!("Validator::validate");
        let conflicts = Conflicts::with_args(self.cmd, matcher);
        let has_subcmd = matcher.subcommand_name().is_some();

        if let ParseState::Opt(a) = parse_state {
            debug!("Validator::validate: needs_val_of={:?}", a);

            let o = &self.cmd[&a];
            let should_err = if let Some(v) = matcher.args.get(o.get_id()) {
                v.all_val_groups_empty() && o.get_min_vals() != 0
            } else {
                true
            };
            if should_err {
                return Err(Error::empty_value(
                    self.cmd,
                    &get_possible_values_cli(o)
                        .iter()
                        .filter(|pv| !pv.is_hide_set())
                        .map(|n| n.get_name().to_owned())
                        .collect::<Vec<_>>(),
                    o.to_string(),
                ));
            }
        }

        if !has_subcmd && self.cmd.is_arg_required_else_help_set() {
            let num_user_values = matcher
                .args()
                .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent))
                .count();
            if num_user_values == 0 {
                let message = self.cmd.write_help_err(false);
                return Err(Error::display_help_error(self.cmd, message));
            }
        }
        if !has_subcmd && self.cmd.is_subcommand_required_set() {
            let bn = self
                .cmd
                .get_bin_name()
                .unwrap_or_else(|| self.cmd.get_name());
            return Err(Error::missing_subcommand(
                self.cmd,
                bn.to_string(),
                self.cmd
                    .all_subcommand_names()
                    .map(|s| s.to_owned())
                    .collect::<Vec<_>>(),
                Usage::new(self.cmd)
                    .required(&self.required)
                    .create_usage_with_title(&[]),
            ));
        }

        ok!(self.validate_conflicts(matcher, &conflicts));
        if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) {
            ok!(self.validate_required(matcher, &conflicts));
        }

        Ok(())
    }
src/output/help_template.rs (line 641)
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
    fn help(
        &mut self,
        arg: Option<&Arg>,
        about: &StyledStr,
        spec_vals: &str,
        next_line_help: bool,
        longest: usize,
    ) {
        debug!("HelpTemplate::help");

        // Is help on next line, if so then indent
        if next_line_help {
            debug!("HelpTemplate::help: Next Line...{:?}", next_line_help);
            self.none("\n");
            self.none(TAB);
            self.none(NEXT_LINE_INDENT);
        }

        let spaces = if next_line_help {
            TAB.len() + NEXT_LINE_INDENT.len()
        } else if let Some(true) = arg.map(|a| a.is_positional()) {
            longest + TAB_WIDTH * 2
        } else {
            longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
        };
        let trailing_indent = spaces; // Don't indent any further than the first line is indented
        let trailing_indent = self.get_spaces(trailing_indent);

        let mut help = about.clone();
        replace_newline_var(&mut help);
        if !spec_vals.is_empty() {
            if !help.is_empty() {
                let sep = if self.use_long && arg.is_some() {
                    "\n\n"
                } else {
                    " "
                };
                help.none(sep);
            }
            help.none(spec_vals);
        }
        let avail_chars = self.term_w.saturating_sub(spaces);
        debug!(
            "HelpTemplate::help: help_width={}, spaces={}, avail={}",
            spaces,
            help.display_width(),
            avail_chars
        );
        help.wrap(avail_chars);
        help.indent("", &trailing_indent);
        let help_is_empty = help.is_empty();
        self.writer.extend(help.into_iter());
        if let Some(arg) = arg {
            const DASH_SPACE: usize = "- ".len();
            const COLON_SPACE: usize = ": ".len();
            let possible_vals = arg.get_possible_values();
            if self.use_long
                && !arg.is_hide_possible_values_set()
                && possible_vals.iter().any(PossibleValue::should_show_help)
            {
                debug!(
                    "HelpTemplate::help: Found possible vals...{:?}",
                    possible_vals
                );
                if !help_is_empty {
                    self.none("\n\n");
                    self.spaces(spaces);
                }
                self.none("Possible values:");
                let longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
                    .max()
                    .expect("Only called with possible value");
                let help_longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_help().map(|h| h.display_width()))
                    .max()
                    .expect("Only called with possible value with help");
                // should new line
                let taken = longest + spaces + DASH_SPACE;

                let possible_value_new_line =
                    self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;

                let spaces = spaces + TAB_WIDTH - DASH_SPACE;
                let trailing_indent = if possible_value_new_line {
                    spaces + DASH_SPACE
                } else {
                    spaces + longest + DASH_SPACE + COLON_SPACE
                };
                let trailing_indent = self.get_spaces(trailing_indent);

                for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
                    self.none("\n");
                    self.spaces(spaces);
                    self.none("- ");
                    self.literal(pv.get_name());
                    if let Some(help) = pv.get_help() {
                        debug!("HelpTemplate::help: Possible Value help");

                        if possible_value_new_line {
                            self.none(":\n");
                            self.spaces(trailing_indent.len());
                        } else {
                            self.none(": ");
                            // To align help messages
                            self.spaces(longest - display_width(pv.get_name()));
                        }

                        let avail_chars = if self.term_w > trailing_indent.len() {
                            self.term_w - trailing_indent.len()
                        } else {
                            usize::MAX
                        };

                        let mut help = help.clone();
                        replace_newline_var(&mut help);
                        help.wrap(avail_chars);
                        help.indent("", &trailing_indent);
                        self.writer.extend(help.into_iter());
                    }
                }
            }
        }
    }

Returns all valid values of the argument value.

Namely the name and all aliases.

Examples found in repository?
src/builder/possible_value.rs (line 222)
220
221
222
223
224
225
226
227
    pub fn matches(&self, value: &str, ignore_case: bool) -> bool {
        if ignore_case {
            self.get_name_and_aliases()
                .any(|name| eq_ignore_case(name, value))
        } else {
            self.get_name_and_aliases().any(|name| name == value)
        }
    }

Tests if the value is valid for this argument value

The value is valid if it is either the name or one of the aliases.

Examples
let arg_value = PossibleValue::new("fast").alias("not-slow");

assert!(arg_value.matches("fast", false));
assert!(arg_value.matches("not-slow", false));

assert!(arg_value.matches("FAST", true));
assert!(!arg_value.matches("FAST", false));
Examples found in repository?
src/util/color.rs (line 81)
79
80
81
82
83
84
85
86
    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))
    }
More examples
Hide additional examples
src/derive.rs (line 385)
379
380
381
382
383
384
385
386
387
388
389
    fn from_str(input: &str, ignore_case: bool) -> Result<Self, String> {
        Self::value_variants()
            .iter()
            .find(|v| {
                v.to_possible_value()
                    .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value")
                    .matches(input, ignore_case)
            })
            .cloned()
            .ok_or_else(|| format!("Invalid variant: {}", input))
    }
src/builder/value_parser.rs (line 1069)
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
    fn parse_ref(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, crate::Error> {
        let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false);
        let possible_vals = || {
            E::value_variants()
                .iter()
                .filter_map(|v| v.to_possible_value())
                .filter(|v| !v.is_hide_set())
                .map(|v| v.get_name().to_owned())
                .collect::<Vec<_>>()
        };

        let value = ok!(value.to_str().ok_or_else(|| {
            crate::Error::invalid_value(
                cmd,
                value.to_string_lossy().into_owned(),
                &possible_vals(),
                arg.map(ToString::to_string)
                    .unwrap_or_else(|| "...".to_owned()),
            )
        }));
        let value = ok!(E::value_variants()
            .iter()
            .find(|v| {
                v.to_possible_value()
                    .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value")
                    .matches(value, ignore_case)
            })
            .ok_or_else(|| {
            crate::Error::invalid_value(
                cmd,
                value.to_owned(),
                &possible_vals(),
                arg.map(ToString::to_string)
                    .unwrap_or_else(|| "...".to_owned()),
            )
            }))
            .clone();
        Ok(value)
    }

    fn possible_values(
        &self,
    ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
        Some(Box::new(
            E::value_variants()
                .iter()
                .filter_map(|v| v.to_possible_value()),
        ))
    }
}

impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> Default for EnumValueParser<E> {
    fn default() -> Self {
        Self::new()
    }
}

/// Verify the value is from an enumerated set of [`PossibleValue`][crate::builder::PossibleValue].
///
/// See also:
/// - [`EnumValueParser`] for directly supporting [`ValueEnum`][crate::ValueEnum] types
/// - [`TypedValueParser::map`] for adapting values to a more specialized type, like an external
///   enums that can't implement [`ValueEnum`][crate::ValueEnum]
///
/// # Example
///
/// Usage:
/// ```rust
/// let mut cmd = clap::Command::new("raw")
///     .arg(
///         clap::Arg::new("color")
///             .value_parser(clap::builder::PossibleValuesParser::new(["always", "auto", "never"]))
///             .required(true)
///     );
///
/// let m = cmd.try_get_matches_from_mut(["cmd", "always"]).unwrap();
/// let port: &String = m.get_one("color")
///     .expect("required");
/// assert_eq!(port, "always");
/// ```
///
/// Semantics:
/// ```rust
/// # use std::ffi::OsStr;
/// # use clap::builder::TypedValueParser;
/// # let cmd = clap::Command::new("test");
/// # let arg = None;
/// let value_parser = clap::builder::PossibleValuesParser::new(["always", "auto", "never"]);
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("always")).unwrap(), "always");
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("auto")).unwrap(), "auto");
/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("never")).unwrap(), "never");
/// ```
#[derive(Clone, Debug)]
pub struct PossibleValuesParser(Vec<super::PossibleValue>);

impl PossibleValuesParser {
    /// Verify the value is from an enumerated set pf [`PossibleValue`][crate::builder::PossibleValue].
    pub fn new(values: impl Into<PossibleValuesParser>) -> Self {
        values.into()
    }
}

impl TypedValueParser for PossibleValuesParser {
    type Value = String;

    fn parse_ref(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, crate::Error> {
        TypedValueParser::parse(self, cmd, arg, value.to_owned())
    }

    fn parse(
        &self,
        cmd: &crate::Command,
        arg: Option<&crate::Arg>,
        value: std::ffi::OsString,
    ) -> Result<String, crate::Error> {
        let value = ok!(value.into_string().map_err(|_| {
            crate::Error::invalid_utf8(
                cmd,
                crate::output::Usage::new(cmd).create_usage_with_title(&[]),
            )
        }));

        let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false);
        if self.0.iter().any(|v| v.matches(&value, ignore_case)) {
            Ok(value)
        } else {
            let possible_vals = self
                .0
                .iter()
                .filter(|v| !v.is_hide_set())
                .map(|v| v.get_name().to_owned())
                .collect::<Vec<_>>();

            Err(crate::Error::invalid_value(
                cmd,
                value,
                &possible_vals,
                arg.map(ToString::to_string)
                    .unwrap_or_else(|| "...".to_owned()),
            ))
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Converts to this type from the input type.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.