1use std::any::Any;
3use std::ffi::{OsStr, OsString};
4use std::fmt::Debug;
5use std::iter::{Cloned, Flatten, Map};
6use std::slice::Iter;
7
8use crate::INTERNAL_ERROR_MSG;
10#[cfg(debug_assertions)]
11use crate::builder::Str;
12use crate::parser::MatchedArg;
13use crate::parser::MatchesError;
14use crate::parser::ValueSource;
15use crate::util::AnyValue;
16use crate::util::AnyValueId;
17use crate::util::FlatMap;
18use crate::util::Id;
19
20#[derive(#[automatically_derived]impl ::core::fmt::Debug for ArgMatches {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"ArgMatches valid_args valid_subcommands args subcommand",
&self.valid_args, &self.valid_subcommands, &self.args,
&&self.subcommand)
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for ArgMatches {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
ArgMatches {
valid_args: ::core::clone::Clone::clone(&self.valid_args),
valid_subcommands: ::core::clone::Clone::clone(&self.valid_subcommands),
args: ::core::clone::Clone::clone(&self.args),
subcommand: ::core::clone::Clone::clone(&self.subcommand),
}
}
}Clone, #[automatically_derived]impl ::core::default::Default for ArgMatches {
#[inline]
fn default() -> Self {
ArgMatches {
valid_args: ::core::default::Default::default(),
valid_subcommands: ::core::default::Default::default(),
args: ::core::default::Default::default(),
subcommand: ::core::default::Default::default(),
}
}
}Default, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ArgMatches {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ArgMatches {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.valid_args == other.valid_args &&
self.valid_subcommands == other.valid_subcommands &&
self.args == other.args && self.subcommand == other.subcommand
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ArgMatches {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Vec<Id>>;
let _: ::core::cmp::AssertParamIsEq<Vec<Str>>;
let _: ::core::cmp::AssertParamIsEq<FlatMap<Id, MatchedArg>>;
let _: ::core::cmp::AssertParamIsEq<Option<Box<SubCommand>>>;
}
}Eq)]
67pub struct ArgMatches {
68 #[cfg(debug_assertions)]
69 pub(crate) valid_args: Vec<Id>,
70 #[cfg(debug_assertions)]
71 pub(crate) valid_subcommands: Vec<Str>,
72 pub(crate) args: FlatMap<Id, MatchedArg>,
73 pub(crate) subcommand: Option<Box<SubCommand>>,
74}
75
76impl ArgMatches {
78 #[cfg_attr(debug_assertions, track_caller)]
118 pub fn get_one<T: Any + Clone + Send + Sync + 'static>(&self, id: &str) -> Option<&T> {
119 MatchesError::unwrap(id, self.try_get_one(id))
120 }
121
122 #[cfg_attr(debug_assertions, track_caller)]
148 pub fn get_count(&self, id: &str) -> u8 {
149 *self.get_one::<u8>(id).unwrap_or_else(|| {
150 {
::core::panicking::panic_fmt(format_args!("arg `{0}`\'s `ArgAction` should be `Count` which should provide a default",
id));
}panic!("arg `{id}`'s `ArgAction` should be `Count` which should provide a default")
151 })
152 }
153
154 #[cfg_attr(debug_assertions, track_caller)]
181 pub fn get_flag(&self, id: &str) -> bool {
182 *self
183 .get_one::<bool>(id)
184 .unwrap_or_else(|| {
185 {
::core::panicking::panic_fmt(format_args!("arg `{0}`\'s `ArgAction` should be one of `SetTrue`, `SetFalse` which should provide a default",
id));
}panic!(
186 "arg `{id}`'s `ArgAction` should be one of `SetTrue`, `SetFalse` which should provide a default"
187 )
188 })
189 }
190
191 #[cfg_attr(debug_assertions, track_caller)]
225 pub fn get_many<T: Any + Clone + Send + Sync + 'static>(
226 &self,
227 id: &str,
228 ) -> Option<ValuesRef<'_, T>> {
229 MatchesError::unwrap(id, self.try_get_many(id))
230 }
231
232 #[cfg_attr(debug_assertions, track_caller)]
263 pub fn get_occurrences<T: Any + Clone + Send + Sync + 'static>(
264 &self,
265 id: &str,
266 ) -> Option<OccurrencesRef<'_, T>> {
267 MatchesError::unwrap(id, self.try_get_occurrences(id))
268 }
269
270 #[cfg_attr(debug_assertions, track_caller)]
313 pub fn get_raw(&self, id: &str) -> Option<RawValues<'_>> {
314 MatchesError::unwrap(id, self.try_get_raw(id))
315 }
316
317 #[cfg_attr(debug_assertions, track_caller)]
367 pub fn get_raw_occurrences(&self, id: &str) -> Option<RawOccurrences<'_>> {
368 MatchesError::unwrap(id, self.try_get_raw_occurrences(id))
369 }
370
371 #[cfg_attr(debug_assertions, track_caller)]
410 pub fn remove_one<T: Any + Clone + Send + Sync + 'static>(&mut self, id: &str) -> Option<T> {
411 MatchesError::unwrap(id, self.try_remove_one(id))
412 }
413
414 #[cfg_attr(debug_assertions, track_caller)]
446 pub fn remove_many<T: Any + Clone + Send + Sync + 'static>(
447 &mut self,
448 id: &str,
449 ) -> Option<Values<T>> {
450 MatchesError::unwrap(id, self.try_remove_many(id))
451 }
452
453 #[cfg_attr(debug_assertions, track_caller)]
485 pub fn remove_occurrences<T: Any + Clone + Send + Sync + 'static>(
486 &mut self,
487 id: &str,
488 ) -> Option<Occurrences<T>> {
489 MatchesError::unwrap(id, self.try_remove_occurrences(id))
490 }
491
492 pub fn contains_id(&self, id: &str) -> bool {
524 MatchesError::unwrap(id, self.try_contains_id(id))
525 }
526
527 pub fn ids(&self) -> IdsRef<'_> {
550 IdsRef {
551 iter: self.args.keys(),
552 }
553 }
554
555 pub fn args_present(&self) -> bool {
579 self.args
580 .values()
581 .any(|v| v.source().map(|s| s.is_explicit()).unwrap_or(false))
582 }
583
584 #[cfg_attr(debug_assertions, track_caller)]
609 pub fn value_source(&self, id: &str) -> Option<ValueSource> {
610 let value = self.get_arg(id);
611
612 value.and_then(MatchedArg::source)
613 }
614
615 #[cfg_attr(debug_assertions, track_caller)]
767 pub fn index_of(&self, id: &str) -> Option<usize> {
768 let arg = match self.get_arg(id) { Some(val) => val, None => { return None; } }some!(self.get_arg(id));
769 let i = match arg.get_index(0) { Some(val) => val, None => { return None; } }some!(arg.get_index(0));
770 Some(i)
771 }
772
773 #[cfg_attr(debug_assertions, track_caller)]
855 pub fn indices_of(&self, id: &str) -> Option<Indices<'_>> {
856 let arg = match self.get_arg(id) { Some(val) => val, None => { return None; } }some!(self.get_arg(id));
857 let i = Indices {
858 iter: arg.indices(),
859 len: arg.num_vals(),
860 };
861 Some(i)
862 }
863}
864
865impl ArgMatches {
867 #[inline]
922 pub fn subcommand(&self) -> Option<(&str, &Self)> {
923 self.subcommand.as_ref().map(|sc| (&*sc.name, &sc.matches))
924 }
925
926 pub fn remove_subcommand(&mut self) -> Option<(String, Self)> {
983 self.subcommand.take().map(|sc| (sc.name, sc.matches))
984 }
985
986 pub fn subcommand_matches(&self, name: &str) -> Option<&Self> {
1027 self.get_subcommand(name).map(|sc| &sc.matches)
1028 }
1029
1030 #[inline]
1055 pub fn subcommand_name(&self) -> Option<&str> {
1056 self.subcommand.as_ref().map(|sc| &*sc.name)
1057 }
1058
1059 #[inline]
1065 #[doc(hidden)]
1066 pub fn is_valid_subcommand(&self, _name: &str) -> bool {
1067 #[cfg(debug_assertions)]
1068 {
1069 _name.is_empty() || self.valid_subcommands.iter().any(|s| *s == _name)
1070 }
1071 #[cfg(not(debug_assertions))]
1072 {
1073 true
1074 }
1075 }
1076}
1077
1078impl ArgMatches {
1080 pub fn try_get_one<T: Any + Clone + Send + Sync + 'static>(
1082 &self,
1083 id: &str,
1084 ) -> Result<Option<&T>, MatchesError> {
1085 let arg = match self.try_get_arg_t::<T>(id) {
Ok(val) => val,
Err(err) => { return Err(err); }
}ok!(self.try_get_arg_t::<T>(id));
1086 let value = match arg.and_then(|a| a.first()) {
1087 Some(value) => value,
1088 None => {
1089 return Ok(None);
1090 }
1091 };
1092 Ok(value
1093 .downcast_ref::<T>()
1094 .map(Some)
1095 .expect(INTERNAL_ERROR_MSG)) }
1097
1098 pub fn try_get_many<T: Any + Clone + Send + Sync + 'static>(
1100 &self,
1101 id: &str,
1102 ) -> Result<Option<ValuesRef<'_, T>>, MatchesError> {
1103 let arg = match match self.try_get_arg_t::<T>(id) {
Ok(val) => val,
Err(err) => { return Err(err); }
}ok!(self.try_get_arg_t::<T>(id)) {
1104 Some(arg) => arg,
1105 None => return Ok(None),
1106 };
1107 let len = arg.num_vals();
1108 let values = arg.vals_flatten();
1109 let values = ValuesRef {
1110 iter: values.map(unwrap_downcast_ref),
1112 len,
1113 };
1114 Ok(Some(values))
1115 }
1116
1117 pub fn try_get_occurrences<T: Any + Clone + Send + Sync + 'static>(
1119 &self,
1120 id: &str,
1121 ) -> Result<Option<OccurrencesRef<'_, T>>, MatchesError> {
1122 let arg = match match self.try_get_arg_t::<T>(id) {
Ok(val) => val,
Err(err) => { return Err(err); }
}ok!(self.try_get_arg_t::<T>(id)) {
1123 Some(arg) => arg,
1124 None => return Ok(None),
1125 };
1126 let values = arg.vals();
1127 Ok(Some(OccurrencesRef {
1128 iter: values.map(|g| OccurrenceValuesRef {
1129 iter: g.iter().map(unwrap_downcast_ref),
1130 }),
1131 }))
1132 }
1133
1134 pub fn try_get_raw(&self, id: &str) -> Result<Option<RawValues<'_>>, MatchesError> {
1136 let arg = match match self.try_get_arg(id) {
Ok(val) => val,
Err(err) => { return Err(err); }
}ok!(self.try_get_arg(id)) {
1137 Some(arg) => arg,
1138 None => return Ok(None),
1139 };
1140 let len = arg.num_vals();
1141 let values = arg.raw_vals_flatten();
1142 let values = RawValues {
1143 iter: values.map(OsString::as_os_str),
1144 len,
1145 };
1146 Ok(Some(values))
1147 }
1148
1149 pub fn try_get_raw_occurrences(
1151 &self,
1152 id: &str,
1153 ) -> Result<Option<RawOccurrences<'_>>, MatchesError> {
1154 let arg = match match self.try_get_arg(id) {
Ok(val) => val,
Err(err) => { return Err(err); }
}ok!(self.try_get_arg(id)) {
1155 Some(arg) => arg,
1156 None => return Ok(None),
1157 };
1158 let values = arg.raw_vals();
1159 let occurrences = RawOccurrences {
1160 iter: values.map(|g| RawOccurrenceValues {
1161 iter: g.iter().map(OsString::as_os_str),
1162 }),
1163 };
1164 Ok(Some(occurrences))
1165 }
1166
1167 pub fn try_remove_one<T: Any + Clone + Send + Sync + 'static>(
1169 &mut self,
1170 id: &str,
1171 ) -> Result<Option<T>, MatchesError> {
1172 match match self.try_remove_arg_t::<T>(id) {
Ok(val) => val,
Err(err) => { return Err(err); }
}ok!(self.try_remove_arg_t::<T>(id)) {
1173 Some(values) => Ok(values
1174 .into_vals_flatten()
1175 .map(unwrap_downcast_into)
1177 .next()),
1178 None => Ok(None),
1179 }
1180 }
1181
1182 pub fn try_remove_many<T: Any + Clone + Send + Sync + 'static>(
1184 &mut self,
1185 id: &str,
1186 ) -> Result<Option<Values<T>>, MatchesError> {
1187 let arg = match match self.try_remove_arg_t::<T>(id) {
Ok(val) => val,
Err(err) => { return Err(err); }
}ok!(self.try_remove_arg_t::<T>(id)) {
1188 Some(arg) => arg,
1189 None => return Ok(None),
1190 };
1191 let len = arg.num_vals();
1192 let values = arg.into_vals_flatten();
1193 let values = Values {
1194 iter: values.map(unwrap_downcast_into),
1196 len,
1197 };
1198 Ok(Some(values))
1199 }
1200
1201 pub fn try_remove_occurrences<T: Any + Clone + Send + Sync + 'static>(
1203 &mut self,
1204 id: &str,
1205 ) -> Result<Option<Occurrences<T>>, MatchesError> {
1206 let arg = match match self.try_remove_arg_t::<T>(id) {
Ok(val) => val,
Err(err) => { return Err(err); }
}ok!(self.try_remove_arg_t::<T>(id)) {
1207 Some(arg) => arg,
1208 None => return Ok(None),
1209 };
1210 let values = arg.into_vals();
1211 let occurrences = Occurrences {
1212 iter: values.into_iter().map(|g| OccurrenceValues {
1213 iter: g.into_iter().map(unwrap_downcast_into),
1214 }),
1215 };
1216 Ok(Some(occurrences))
1217 }
1218
1219 pub fn try_contains_id(&self, id: &str) -> Result<bool, MatchesError> {
1221 match self.verify_arg(id) {
Ok(val) => val,
Err(err) => { return Err(err); }
};ok!(self.verify_arg(id));
1222
1223 let presence = self.args.contains_key(id);
1224 Ok(presence)
1225 }
1226
1227 pub fn try_clear_id(&mut self, id: &str) -> Result<bool, MatchesError> {
1235 match self.verify_arg(id) {
Ok(val) => val,
Err(err) => { return Err(err); }
};ok!(self.verify_arg(id));
1236 Ok(self.args.remove_entry(id).is_some())
1237 }
1238}
1239
1240impl ArgMatches {
1242 #[inline]
1243 fn try_get_arg(&self, arg: &str) -> Result<Option<&MatchedArg>, MatchesError> {
1244 match self.verify_arg(arg) {
Ok(val) => val,
Err(err) => { return Err(err); }
};ok!(self.verify_arg(arg));
1245 Ok(self.args.get(arg))
1246 }
1247
1248 #[inline]
1249 fn try_get_arg_t<T: Any + Send + Sync + 'static>(
1250 &self,
1251 arg: &str,
1252 ) -> Result<Option<&MatchedArg>, MatchesError> {
1253 let arg = match match self.try_get_arg(arg) {
Ok(val) => val,
Err(err) => { return Err(err); }
}ok!(self.try_get_arg(arg)) {
1254 Some(arg) => arg,
1255 None => {
1256 return Ok(None);
1257 }
1258 };
1259 match self.verify_arg_t::<T>(arg) {
Ok(val) => val,
Err(err) => { return Err(err); }
};ok!(self.verify_arg_t::<T>(arg));
1260 Ok(Some(arg))
1261 }
1262
1263 #[inline]
1264 fn try_remove_arg_t<T: Any + Send + Sync + 'static>(
1265 &mut self,
1266 arg: &str,
1267 ) -> Result<Option<MatchedArg>, MatchesError> {
1268 match self.verify_arg(arg) {
Ok(val) => val,
Err(err) => { return Err(err); }
};ok!(self.verify_arg(arg));
1269 let (id, matched) = match self.args.remove_entry(arg) {
1270 Some((id, matched)) => (id, matched),
1271 None => {
1272 return Ok(None);
1273 }
1274 };
1275
1276 let expected = AnyValueId::of::<T>();
1277 let actual = matched.infer_type_id(expected);
1278 if actual == expected {
1279 Ok(Some(matched))
1280 } else {
1281 self.args.insert(id, matched);
1282 Err(MatchesError::Downcast { actual, expected })
1283 }
1284 }
1285
1286 fn verify_arg_t<T: Any + Send + Sync + 'static>(
1287 &self,
1288 arg: &MatchedArg,
1289 ) -> Result<(), MatchesError> {
1290 let expected = AnyValueId::of::<T>();
1291 let actual = arg.infer_type_id(expected);
1292 if expected == actual {
1293 Ok(())
1294 } else {
1295 Err(MatchesError::Downcast { actual, expected })
1296 }
1297 }
1298
1299 #[inline]
1300 fn verify_arg(&self, _arg: &str) -> Result<(), MatchesError> {
1301 #[cfg(debug_assertions)]
1302 {
1303 if _arg == Id::EXTERNAL || self.valid_args.iter().any(|s| *s == _arg) {
1304 } else {
1305 debug!(
1306 "`{:?}` is not an id of an argument or a group.\n\
1307 Make sure you're using the name of the argument itself \
1308 and not the name of short or long flags.",
1309 _arg
1310 );
1311 return Err(MatchesError::UnknownArgument {});
1312 }
1313 }
1314 Ok(())
1315 }
1316
1317 #[inline]
1318 #[cfg_attr(debug_assertions, track_caller)]
1319 fn get_arg<'s>(&'s self, arg: &str) -> Option<&'s MatchedArg> {
1320 #[cfg(debug_assertions)]
1321 {
1322 if arg == Id::EXTERNAL || self.valid_args.iter().any(|s| *s == arg) {
1323 } else {
1324 {
::core::panicking::panic_fmt(format_args!("`{0:?}` is not an id of an argument or a group.\nMake sure you\'re using the name of the argument itself and not the name of short or long flags.",
arg));
};panic!(
1325 "`{arg:?}` is not an id of an argument or a group.\n\
1326 Make sure you're using the name of the argument itself \
1327 and not the name of short or long flags."
1328 );
1329 }
1330 }
1331
1332 self.args.get(arg)
1333 }
1334
1335 #[inline]
1336 #[cfg_attr(debug_assertions, track_caller)]
1337 fn get_subcommand(&self, name: &str) -> Option<&SubCommand> {
1338 #[cfg(debug_assertions)]
1339 {
1340 if name.is_empty() || self.valid_subcommands.iter().any(|s| *s == name) {
1341 } else {
1342 {
::core::panicking::panic_fmt(format_args!("`{0}` is not a name of a subcommand.",
name));
};panic!("`{name}` is not a name of a subcommand.");
1343 }
1344 }
1345
1346 if let Some(ref sc) = self.subcommand {
1347 if sc.name == name {
1348 return Some(sc);
1349 }
1350 }
1351
1352 None
1353 }
1354}
1355
1356#[derive(#[automatically_derived]impl ::core::fmt::Debug for SubCommand {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SubCommand name matches", &self.name, &&self.matches)
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for SubCommand {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
SubCommand {
name: ::core::clone::Clone::clone(&self.name),
matches: ::core::clone::Clone::clone(&self.matches),
}
}
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
SubCommand {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SubCommand {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.matches == other.matches
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for SubCommand {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<String>;
let _: ::core::cmp::AssertParamIsEq<ArgMatches>;
}
}Eq)]
1357pub(crate) struct SubCommand {
1358 pub(crate) name: String,
1359 pub(crate) matches: ArgMatches,
1360}
1361
1362#[derive(#[automatically_derived]impl<'a> ::core::clone::Clone for IdsRef<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
IdsRef { iter: ::core::clone::Clone::clone(&self.iter) }
}
}Clone, #[automatically_derived]impl<'a> ::core::fmt::Debug for IdsRef<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "IdsRef iter",
&&self.iter)
}
}Debug)]
1384pub struct IdsRef<'a> {
1385 iter: Iter<'a, Id>,
1386}
1387
1388impl<'a> Iterator for IdsRef<'a> {
1389 type Item = &'a Id;
1390
1391 fn next(&mut self) -> Option<&'a Id> {
1392 self.iter.next()
1393 }
1394 fn size_hint(&self) -> (usize, Option<usize>) {
1395 self.iter.size_hint()
1396 }
1397}
1398
1399impl<'a> DoubleEndedIterator for IdsRef<'a> {
1400 fn next_back(&mut self) -> Option<&'a Id> {
1401 self.iter.next_back()
1402 }
1403}
1404
1405impl ExactSizeIterator for IdsRef<'_> {}
1406
1407#[derive(#[automatically_derived]impl<T: ::core::clone::Clone> ::core::clone::Clone for
Values<T> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
Values {
iter: ::core::clone::Clone::clone(&self.iter),
len: ::core::clone::Clone::clone(&self.len),
}
}
}Clone, #[automatically_derived]impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
Values<T> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Values iter len", &self.iter, &&self.len)
}
}Debug)]
1428pub struct Values<T> {
1429 #[allow(clippy::type_complexity)]
1430 iter: Map<Flatten<std::vec::IntoIter<Vec<AnyValue>>>, fn(AnyValue) -> T>,
1431 len: usize,
1432}
1433
1434impl<T> Iterator for Values<T> {
1435 type Item = T;
1436
1437 fn next(&mut self) -> Option<Self::Item> {
1438 if let Some(next) = self.iter.next() {
1439 self.len -= 1;
1440 Some(next)
1441 } else {
1442 None
1443 }
1444 }
1445 fn size_hint(&self) -> (usize, Option<usize>) {
1446 (self.len, Some(self.len))
1447 }
1448}
1449
1450impl<T> DoubleEndedIterator for Values<T> {
1451 fn next_back(&mut self) -> Option<Self::Item> {
1452 if let Some(next) = self.iter.next_back() {
1453 self.len -= 1;
1454 Some(next)
1455 } else {
1456 None
1457 }
1458 }
1459}
1460
1461impl<T> ExactSizeIterator for Values<T> {}
1462
1463impl<T> Default for Values<T> {
1465 fn default() -> Self {
1466 let empty: Vec<Vec<AnyValue>> = Default::default();
1467 Self {
1468 iter: empty.into_iter().flatten().map(|_| ::core::panicking::unreachable_default_msg()unreachable!()),
1469 len: 0,
1470 }
1471 }
1472}
1473
1474#[derive(#[automatically_derived]impl<'a, T: ::core::clone::Clone> ::core::clone::Clone
for ValuesRef<'a, T> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
ValuesRef {
iter: ::core::clone::Clone::clone(&self.iter),
len: ::core::clone::Clone::clone(&self.len),
}
}
}Clone, #[automatically_derived]impl<'a, T: ::core::fmt::Debug> ::core::fmt::Debug for
ValuesRef<'a, T> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ValuesRef iter len", &self.iter, &&self.len)
}
}Debug)]
1496pub struct ValuesRef<'a, T> {
1497 #[allow(clippy::type_complexity)]
1498 iter: Map<Flatten<Iter<'a, Vec<AnyValue>>>, fn(&AnyValue) -> &T>,
1499 len: usize,
1500}
1501
1502impl<'a, T: 'a> Iterator for ValuesRef<'a, T> {
1503 type Item = &'a T;
1504
1505 fn next(&mut self) -> Option<Self::Item> {
1506 if let Some(next) = self.iter.next() {
1507 self.len -= 1;
1508 Some(next)
1509 } else {
1510 None
1511 }
1512 }
1513 fn size_hint(&self) -> (usize, Option<usize>) {
1514 (self.len, Some(self.len))
1515 }
1516}
1517
1518impl<'a, T: 'a> DoubleEndedIterator for ValuesRef<'a, T> {
1519 fn next_back(&mut self) -> Option<Self::Item> {
1520 if let Some(next) = self.iter.next_back() {
1521 self.len -= 1;
1522 Some(next)
1523 } else {
1524 None
1525 }
1526 }
1527}
1528
1529impl<'a, T: 'a> ExactSizeIterator for ValuesRef<'a, T> {}
1530
1531impl<'a, T: 'a> Default for ValuesRef<'a, T> {
1533 fn default() -> Self {
1534 static EMPTY: [Vec<AnyValue>; 0] = [];
1535 ValuesRef {
1536 iter: EMPTY[..].iter().flatten().map(|_| ::core::panicking::unreachable_default_msg()unreachable!()),
1537 len: 0,
1538 }
1539 }
1540}
1541
1542#[derive(#[automatically_derived]impl<'a> ::core::clone::Clone for RawValues<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
RawValues {
iter: ::core::clone::Clone::clone(&self.iter),
len: ::core::clone::Clone::clone(&self.len),
}
}
}Clone, #[automatically_derived]impl<'a> ::core::fmt::Debug for RawValues<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"RawValues iter len", &self.iter, &&self.len)
}
}Debug)]
1569pub struct RawValues<'a> {
1570 #[allow(clippy::type_complexity)]
1571 iter: Map<Flatten<Iter<'a, Vec<OsString>>>, fn(&OsString) -> &OsStr>,
1572 len: usize,
1573}
1574
1575impl<'a> Iterator for RawValues<'a> {
1576 type Item = &'a OsStr;
1577
1578 fn next(&mut self) -> Option<&'a OsStr> {
1579 if let Some(next) = self.iter.next() {
1580 self.len -= 1;
1581 Some(next)
1582 } else {
1583 None
1584 }
1585 }
1586 fn size_hint(&self) -> (usize, Option<usize>) {
1587 (self.len, Some(self.len))
1588 }
1589}
1590
1591impl<'a> DoubleEndedIterator for RawValues<'a> {
1592 fn next_back(&mut self) -> Option<&'a OsStr> {
1593 if let Some(next) = self.iter.next_back() {
1594 self.len -= 1;
1595 Some(next)
1596 } else {
1597 None
1598 }
1599 }
1600}
1601
1602impl ExactSizeIterator for RawValues<'_> {}
1603
1604impl Default for RawValues<'_> {
1606 fn default() -> Self {
1607 static EMPTY: [Vec<OsString>; 0] = [];
1608 RawValues {
1609 iter: EMPTY[..].iter().flatten().map(|_| ::core::panicking::unreachable_default_msg()unreachable!()),
1610 len: 0,
1611 }
1612 }
1613}
1614
1615#[derive(#[automatically_derived]impl<T: ::core::clone::Clone> ::core::clone::Clone for
Occurrences<T> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
Occurrences { iter: ::core::clone::Clone::clone(&self.iter) }
}
}Clone, #[automatically_derived]impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
Occurrences<T> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Occurrences iter", &&self.iter)
}
}Debug)]
1621pub struct Occurrences<T> {
1622 #[allow(clippy::type_complexity)]
1623 iter: Map<std::vec::IntoIter<Vec<AnyValue>>, fn(Vec<AnyValue>) -> OccurrenceValues<T>>,
1624}
1625
1626impl<T> Iterator for Occurrences<T> {
1627 type Item = OccurrenceValues<T>;
1628
1629 fn next(&mut self) -> Option<Self::Item> {
1630 self.iter.next()
1631 }
1632
1633 fn size_hint(&self) -> (usize, Option<usize>) {
1634 self.iter.size_hint()
1635 }
1636}
1637
1638impl<T> DoubleEndedIterator for Occurrences<T> {
1639 fn next_back(&mut self) -> Option<Self::Item> {
1640 self.iter.next_back()
1641 }
1642}
1643
1644impl<T> ExactSizeIterator for Occurrences<T> {}
1645
1646impl<T> Default for Occurrences<T> {
1647 fn default() -> Self {
1648 let empty: Vec<Vec<AnyValue>> = Default::default();
1649 Self {
1650 iter: empty.into_iter().map(|_| ::core::panicking::unreachable_default_msg()unreachable!()),
1651 }
1652 }
1653}
1654
1655#[derive(#[automatically_derived]impl<T: ::core::clone::Clone> ::core::clone::Clone for
OccurrenceValues<T> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
OccurrenceValues { iter: ::core::clone::Clone::clone(&self.iter) }
}
}Clone, #[automatically_derived]impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
OccurrenceValues<T> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"OccurrenceValues iter", &&self.iter)
}
}Debug)]
1656pub struct OccurrenceValues<T> {
1657 #[allow(clippy::type_complexity)]
1658 iter: Map<std::vec::IntoIter<AnyValue>, fn(AnyValue) -> T>,
1659}
1660
1661impl<T> Iterator for OccurrenceValues<T> {
1662 type Item = T;
1663
1664 fn next(&mut self) -> Option<Self::Item> {
1665 self.iter.next()
1666 }
1667
1668 fn size_hint(&self) -> (usize, Option<usize>) {
1669 self.iter.size_hint()
1670 }
1671}
1672
1673impl<T> DoubleEndedIterator for OccurrenceValues<T> {
1674 fn next_back(&mut self) -> Option<Self::Item> {
1675 self.iter.next_back()
1676 }
1677}
1678
1679impl<T> ExactSizeIterator for OccurrenceValues<T> {}
1680
1681#[derive(#[automatically_derived]impl<'a, T: ::core::clone::Clone> ::core::clone::Clone
for OccurrencesRef<'a, T> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
OccurrencesRef { iter: ::core::clone::Clone::clone(&self.iter) }
}
}Clone, #[automatically_derived]impl<'a, T: ::core::fmt::Debug> ::core::fmt::Debug for
OccurrencesRef<'a, T> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"OccurrencesRef iter", &&self.iter)
}
}Debug)]
1682pub struct OccurrencesRef<'a, T> {
1683 #[allow(clippy::type_complexity)]
1684 iter: Map<Iter<'a, Vec<AnyValue>>, fn(&Vec<AnyValue>) -> OccurrenceValuesRef<'_, T>>,
1685}
1686
1687impl<'a, T> Iterator for OccurrencesRef<'a, T>
1688where
1689 Self: 'a,
1690{
1691 type Item = OccurrenceValuesRef<'a, T>;
1692
1693 fn next(&mut self) -> Option<Self::Item> {
1694 self.iter.next()
1695 }
1696
1697 fn size_hint(&self) -> (usize, Option<usize>) {
1698 self.iter.size_hint()
1699 }
1700}
1701
1702impl<'a, T> DoubleEndedIterator for OccurrencesRef<'a, T>
1703where
1704 Self: 'a,
1705{
1706 fn next_back(&mut self) -> Option<Self::Item> {
1707 self.iter.next_back()
1708 }
1709}
1710
1711impl<'a, T> ExactSizeIterator for OccurrencesRef<'a, T> where Self: 'a {}
1712impl<T> Default for OccurrencesRef<'_, T> {
1713 fn default() -> Self {
1714 static EMPTY: [Vec<AnyValue>; 0] = [];
1715 OccurrencesRef {
1716 iter: EMPTY[..].iter().map(|_| ::core::panicking::unreachable_default_msg()unreachable!()),
1717 }
1718 }
1719}
1720
1721#[derive(#[automatically_derived]impl<'a, T: ::core::clone::Clone> ::core::clone::Clone
for OccurrenceValuesRef<'a, T> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
OccurrenceValuesRef { iter: ::core::clone::Clone::clone(&self.iter) }
}
}Clone, #[automatically_derived]impl<'a, T: ::core::fmt::Debug> ::core::fmt::Debug for
OccurrenceValuesRef<'a, T> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"OccurrenceValuesRef iter", &&self.iter)
}
}Debug)]
1722pub struct OccurrenceValuesRef<'a, T> {
1723 #[allow(clippy::type_complexity)]
1724 iter: Map<Iter<'a, AnyValue>, fn(&AnyValue) -> &T>,
1725}
1726
1727impl<'a, T> Iterator for OccurrenceValuesRef<'a, T>
1728where
1729 Self: 'a,
1730{
1731 type Item = &'a T;
1732
1733 fn next(&mut self) -> Option<Self::Item> {
1734 self.iter.next()
1735 }
1736
1737 fn size_hint(&self) -> (usize, Option<usize>) {
1738 self.iter.size_hint()
1739 }
1740}
1741
1742impl<'a, T> DoubleEndedIterator for OccurrenceValuesRef<'a, T>
1743where
1744 Self: 'a,
1745{
1746 fn next_back(&mut self) -> Option<Self::Item> {
1747 self.iter.next_back()
1748 }
1749}
1750
1751impl<'a, T> ExactSizeIterator for OccurrenceValuesRef<'a, T> where Self: 'a {}
1752
1753#[derive(#[automatically_derived]impl<'a> ::core::clone::Clone for RawOccurrences<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
RawOccurrences { iter: ::core::clone::Clone::clone(&self.iter) }
}
}Clone, #[automatically_derived]impl<'a> ::core::fmt::Debug for RawOccurrences<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"RawOccurrences iter", &&self.iter)
}
}Debug)]
1754pub struct RawOccurrences<'a> {
1755 #[allow(clippy::type_complexity)]
1756 iter: Map<Iter<'a, Vec<OsString>>, fn(&Vec<OsString>) -> RawOccurrenceValues<'_>>,
1757}
1758
1759impl<'a> Iterator for RawOccurrences<'a> {
1760 type Item = RawOccurrenceValues<'a>;
1761
1762 fn next(&mut self) -> Option<Self::Item> {
1763 self.iter.next()
1764 }
1765
1766 fn size_hint(&self) -> (usize, Option<usize>) {
1767 self.iter.size_hint()
1768 }
1769}
1770
1771impl DoubleEndedIterator for RawOccurrences<'_> {
1772 fn next_back(&mut self) -> Option<Self::Item> {
1773 self.iter.next_back()
1774 }
1775}
1776
1777impl ExactSizeIterator for RawOccurrences<'_> {}
1778
1779impl Default for RawOccurrences<'_> {
1780 fn default() -> Self {
1781 static EMPTY: [Vec<OsString>; 0] = [];
1782 RawOccurrences {
1783 iter: EMPTY[..].iter().map(|_| ::core::panicking::unreachable_default_msg()unreachable!()),
1784 }
1785 }
1786}
1787
1788#[derive(#[automatically_derived]impl<'a> ::core::clone::Clone for
RawOccurrenceValues<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
RawOccurrenceValues { iter: ::core::clone::Clone::clone(&self.iter) }
}
}Clone, #[automatically_derived]impl<'a> ::core::fmt::Debug for
RawOccurrenceValues<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"RawOccurrenceValues iter", &&self.iter)
}
}Debug)]
1789pub struct RawOccurrenceValues<'a> {
1790 #[allow(clippy::type_complexity)]
1791 iter: Map<Iter<'a, OsString>, fn(&OsString) -> &OsStr>,
1792}
1793
1794impl<'a> Iterator for RawOccurrenceValues<'a>
1795where
1796 Self: 'a,
1797{
1798 type Item = &'a OsStr;
1799
1800 fn next(&mut self) -> Option<Self::Item> {
1801 self.iter.next()
1802 }
1803
1804 fn size_hint(&self) -> (usize, Option<usize>) {
1805 self.iter.size_hint()
1806 }
1807}
1808
1809impl<'a> DoubleEndedIterator for RawOccurrenceValues<'a>
1810where
1811 Self: 'a,
1812{
1813 fn next_back(&mut self) -> Option<Self::Item> {
1814 self.iter.next_back()
1815 }
1816}
1817
1818impl ExactSizeIterator for RawOccurrenceValues<'_> {}
1819
1820#[derive(#[automatically_derived]impl<'a> ::core::clone::Clone for Indices<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
Indices {
iter: ::core::clone::Clone::clone(&self.iter),
len: ::core::clone::Clone::clone(&self.len),
}
}
}Clone, #[automatically_derived]impl<'a> ::core::fmt::Debug for Indices<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Indices iter len", &self.iter, &&self.len)
}
}Debug)]
1842pub struct Indices<'a> {
1843 iter: Cloned<Iter<'a, usize>>,
1844 len: usize,
1845}
1846
1847impl Iterator for Indices<'_> {
1848 type Item = usize;
1849
1850 fn next(&mut self) -> Option<usize> {
1851 if let Some(next) = self.iter.next() {
1852 self.len -= 1;
1853 Some(next)
1854 } else {
1855 None
1856 }
1857 }
1858 fn size_hint(&self) -> (usize, Option<usize>) {
1859 (self.len, Some(self.len))
1860 }
1861}
1862
1863impl DoubleEndedIterator for Indices<'_> {
1864 fn next_back(&mut self) -> Option<usize> {
1865 if let Some(next) = self.iter.next_back() {
1866 self.len -= 1;
1867 Some(next)
1868 } else {
1869 None
1870 }
1871 }
1872}
1873
1874impl ExactSizeIterator for Indices<'_> {}
1875
1876impl Default for Indices<'_> {
1878 fn default() -> Self {
1879 static EMPTY: [usize; 0] = [];
1880 Indices {
1882 iter: EMPTY[..].iter().cloned(),
1883 len: 0,
1884 }
1885 }
1886}
1887
1888#[track_caller]
1889fn unwrap_downcast_ref<T: Any + Clone + Send + Sync + 'static>(value: &AnyValue) -> &T {
1890 value.downcast_ref().expect(INTERNAL_ERROR_MSG)
1891}
1892
1893#[track_caller]
1894fn unwrap_downcast_into<T: Any + Clone + Send + Sync + 'static>(value: AnyValue) -> T {
1895 value.downcast_into().expect(INTERNAL_ERROR_MSG)
1896}
1897
1898#[cfg(test)]
1899mod tests {
1900 use super::*;
1901
1902 use crate::ArgAction;
1903
1904 #[test]
1905 fn check_auto_traits() {
1906 static_assertions::assert_impl_all!(ArgMatches: Send, Sync, Unpin);
1907 }
1908
1909 #[test]
1910 fn test_default_raw_values() {
1911 let mut values: RawValues<'_> = Default::default();
1912 assert_eq!(values.next(), None);
1913 }
1914
1915 #[test]
1916 fn test_default_indices() {
1917 let mut indices: Indices<'_> = Indices::default();
1918 assert_eq!(indices.next(), None);
1919 }
1920
1921 #[test]
1922 fn test_default_indices_with_shorter_lifetime() {
1923 let matches = ArgMatches::default();
1924 let mut indices = matches.indices_of("").unwrap_or_default();
1925 assert_eq!(indices.next(), None);
1926 }
1927
1928 #[test]
1929 fn values_exact_size() {
1930 let l = crate::Command::new("test")
1931 .arg(
1932 crate::Arg::new("POTATO")
1933 .action(ArgAction::Set)
1934 .num_args(1..)
1935 .required(true),
1936 )
1937 .try_get_matches_from(["test", "one"])
1938 .unwrap()
1939 .get_many::<String>("POTATO")
1940 .expect("present")
1941 .count();
1942 assert_eq!(l, 1);
1943 }
1944
1945 #[test]
1946 fn os_values_exact_size() {
1947 let l = crate::Command::new("test")
1948 .arg(
1949 crate::Arg::new("POTATO")
1950 .action(ArgAction::Set)
1951 .num_args(1..)
1952 .value_parser(crate::builder::ValueParser::os_string())
1953 .required(true),
1954 )
1955 .try_get_matches_from(["test", "one"])
1956 .unwrap()
1957 .get_many::<OsString>("POTATO")
1958 .expect("present")
1959 .count();
1960 assert_eq!(l, 1);
1961 }
1962
1963 #[test]
1964 fn indices_exact_size() {
1965 let l = crate::Command::new("test")
1966 .arg(
1967 crate::Arg::new("POTATO")
1968 .action(ArgAction::Set)
1969 .num_args(1..)
1970 .required(true),
1971 )
1972 .try_get_matches_from(["test", "one"])
1973 .unwrap()
1974 .indices_of("POTATO")
1975 .expect("present")
1976 .len();
1977 assert_eq!(l, 1);
1978 }
1979
1980 #[test]
1981 fn rev_iter() {
1982 let mut matches = crate::Command::new("myprog")
1983 .arg(crate::Arg::new("a").short('a').action(ArgAction::Append))
1984 .arg(crate::Arg::new("b").short('b').action(ArgAction::Append))
1985 .try_get_matches_from(vec!["myprog", "-a1", "-b1", "-b3"])
1986 .unwrap();
1987
1988 let a_index = matches
1989 .indices_of("a")
1990 .expect("missing aopt indices")
1991 .collect::<Vec<_>>();
1992 dbg!(&a_index);
1993 let a_value = matches
1994 .remove_many::<String>("a")
1995 .expect("missing aopt values");
1996 dbg!(&a_value);
1997 let a = a_index.into_iter().zip(a_value).rev().collect::<Vec<_>>();
1998 dbg!(a);
1999
2000 let b_index = matches
2001 .indices_of("b")
2002 .expect("missing aopt indices")
2003 .collect::<Vec<_>>();
2004 dbg!(&b_index);
2005 let b_value = matches
2006 .remove_many::<String>("b")
2007 .expect("missing aopt values");
2008 dbg!(&b_value);
2009 let b = b_index.into_iter().zip(b_value).rev().collect::<Vec<_>>();
2010 dbg!(b);
2011 }
2012
2013 #[test]
2014 fn delete_id_without_returning() {
2015 let mut matches = crate::Command::new("myprog")
2016 .arg(crate::Arg::new("a").short('a').action(ArgAction::Append))
2017 .arg(crate::Arg::new("b").short('b').action(ArgAction::Append))
2018 .arg(crate::Arg::new("c").short('c').action(ArgAction::Append))
2019 .try_get_matches_from(vec!["myprog", "-b1", "-a1", "-b2"])
2020 .unwrap();
2021 let matches_ids_count = matches.ids().count();
2022 assert_eq!(matches_ids_count, 2);
2023
2024 let _ = matches
2025 .try_clear_id("d")
2026 .expect_err("should fail due to there is no arg 'd'");
2027
2028 let c_was_presented = matches
2029 .try_clear_id("c")
2030 .expect("doesn't fail because there is no matches for 'c' argument");
2031 assert!(!c_was_presented);
2032 let matches_ids_count = matches.ids().count();
2033 assert_eq!(matches_ids_count, 2);
2034
2035 let b_was_presented = matches.try_clear_id("b").unwrap();
2036 assert!(b_was_presented);
2037 let matches_ids_count = matches.ids().count();
2038 assert_eq!(matches_ids_count, 1);
2039
2040 let a_was_presented = matches.try_clear_id("a").unwrap();
2041 assert!(a_was_presented);
2042 let matches_ids_count = matches.ids().count();
2043 assert_eq!(matches_ids_count, 0);
2044 }
2045}