]> git.proxmox.com Git - rustc.git/blob - src/vendor/clap/src/args/arg_matches.rs
New upstream version 1.21.0+dfsg1
[rustc.git] / src / vendor / clap / src / args / arg_matches.rs
1 // Std
2 use std::borrow::Cow;
3 use std::collections::HashMap;
4 use std::ffi::{OsStr, OsString};
5 use std::iter::Map;
6 use std::slice::Iter;
7
8 // Internal
9 use INVALID_UTF8;
10 use args::MatchedArg;
11 use args::SubCommand;
12
13 /// Used to get information about the arguments that where supplied to the program at runtime by
14 /// the user. New instances of this struct are obtained by using the [`App::get_matches`] family of
15 /// methods.
16 ///
17 /// # Examples
18 ///
19 /// ```no_run
20 /// # use clap::{App, Arg};
21 /// let matches = App::new("MyApp")
22 /// .arg(Arg::with_name("out")
23 /// .long("output")
24 /// .required(true)
25 /// .takes_value(true))
26 /// .arg(Arg::with_name("debug")
27 /// .short("d")
28 /// .multiple(true))
29 /// .arg(Arg::with_name("cfg")
30 /// .short("c")
31 /// .takes_value(true))
32 /// .get_matches(); // builds the instance of ArgMatches
33 ///
34 /// // to get information about the "cfg" argument we created, such as the value supplied we use
35 /// // various ArgMatches methods, such as ArgMatches::value_of
36 /// if let Some(c) = matches.value_of("cfg") {
37 /// println!("Value for -c: {}", c);
38 /// }
39 ///
40 /// // The ArgMatches::value_of method returns an Option because the user may not have supplied
41 /// // that argument at runtime. But if we specified that the argument was "required" as we did
42 /// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually
43 /// // used at runtime.
44 /// println!("Value for --output: {}", matches.value_of("out").unwrap());
45 ///
46 /// // You can check the presence of an argument
47 /// if matches.is_present("out") {
48 /// // Another way to check if an argument was present, or if it occurred multiple times is to
49 /// // use occurrences_of() which returns 0 if an argument isn't found at runtime, or the
50 /// // number of times that it occurred, if it was. To allow an argument to appear more than
51 /// // once, you must use the .multiple(true) method, otherwise it will only return 1 or 0.
52 /// if matches.occurrences_of("debug") > 2 {
53 /// println!("Debug mode is REALLY on, don't be crazy");
54 /// } else {
55 /// println!("Debug mode kind of on");
56 /// }
57 /// }
58 /// ```
59 /// [`App::get_matches`]: ./struct.App.html#method.get_matches
60 #[derive(Debug, Clone)]
61 pub struct ArgMatches<'a> {
62 #[doc(hidden)]
63 pub args: HashMap<&'a str, MatchedArg>,
64 #[doc(hidden)]
65 pub subcommand: Option<Box<SubCommand<'a>>>,
66 #[doc(hidden)]
67 pub usage: Option<String>,
68 }
69
70 impl<'a> Default for ArgMatches<'a> {
71 fn default() -> Self {
72 ArgMatches {
73 args: HashMap::new(),
74 subcommand: None,
75 usage: None,
76 }
77 }
78 }
79
80 impl<'a> ArgMatches<'a> {
81 #[doc(hidden)]
82 pub fn new() -> Self { ArgMatches { ..Default::default() } }
83
84 /// Gets the value of a specific [option] or [positional] argument (i.e. an argument that takes
85 /// an additional value at runtime). If the option wasn't present at runtime
86 /// it returns `None`.
87 ///
88 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
89 /// prefer [`ArgMatches::values_of`] as `ArgMatches::value_of` will only return the *first*
90 /// value.
91 ///
92 /// # Panics
93 ///
94 /// This method will [`panic!`] if the value contains invalid UTF-8 code points.
95 ///
96 /// # Examples
97 ///
98 /// ```rust
99 /// # use clap::{App, Arg};
100 /// let m = App::new("myapp")
101 /// .arg(Arg::with_name("output")
102 /// .takes_value(true))
103 /// .get_matches_from(vec!["myapp", "something"]);
104 ///
105 /// assert_eq!(m.value_of("output"), Some("something"));
106 /// ```
107 /// [option]: ./struct.Arg.html#method.takes_value
108 /// [positional]: ./struct.Arg.html#method.index
109 /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
110 /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
111 pub fn value_of<S: AsRef<str>>(&self, name: S) -> Option<&str> {
112 if let Some(arg) = self.args.get(name.as_ref()) {
113 if let Some(v) = arg.vals.get(0) {
114 return Some(v.to_str().expect(INVALID_UTF8));
115 }
116 }
117 None
118 }
119
120 /// Gets the lossy value of a specific argument. If the argument wasn't present at runtime
121 /// it returns `None`. A lossy value is one which contains invalid UTF-8 code points, those
122 /// invalid points will be replaced with `\u{FFFD}`
123 ///
124 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
125 /// prefer [`Arg::values_of_lossy`] as `value_of_lossy()` will only return the *first* value.
126 ///
127 /// # Examples
128 ///
129 #[cfg_attr(not(unix), doc=" ```ignore")]
130 #[cfg_attr( unix , doc=" ```")]
131 /// # use clap::{App, Arg};
132 /// use std::ffi::OsString;
133 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
134 ///
135 /// let m = App::new("utf8")
136 /// .arg(Arg::from_usage("<arg> 'some arg'"))
137 /// .get_matches_from(vec![OsString::from("myprog"),
138 /// // "Hi {0xe9}!"
139 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
140 /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!");
141 /// ```
142 /// [`Arg::values_of_lossy`]: ./struct.ArgMatches.html#method.values_of_lossy
143 pub fn value_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Cow<'a, str>> {
144 if let Some(arg) = self.args.get(name.as_ref()) {
145 if let Some(v) = arg.vals.get(0) {
146 return Some(v.to_string_lossy());
147 }
148 }
149 None
150 }
151
152 /// Gets the OS version of a string value of a specific argument. If the option wasn't present
153 /// at runtime it returns `None`. An OS value on Unix-like systems is any series of bytes,
154 /// regardless of whether or not they contain valid UTF-8 code points. Since [`String`]s in
155 /// Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument
156 /// value may contain invalid UTF-8 code points.
157 ///
158 /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
159 /// prefer [`ArgMatches::values_of_os`] as `Arg::value_of_os` will only return the *first*
160 /// value.
161 ///
162 /// # Examples
163 ///
164 #[cfg_attr(not(unix), doc=" ```ignore")]
165 #[cfg_attr( unix , doc=" ```")]
166 /// # use clap::{App, Arg};
167 /// use std::ffi::OsString;
168 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
169 ///
170 /// let m = App::new("utf8")
171 /// .arg(Arg::from_usage("<arg> 'some arg'"))
172 /// .get_matches_from(vec![OsString::from("myprog"),
173 /// // "Hi {0xe9}!"
174 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
175 /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
176 /// ```
177 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
178 /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
179 pub fn value_of_os<S: AsRef<str>>(&self, name: S) -> Option<&OsStr> {
180 self.args
181 .get(name.as_ref())
182 .map_or(None, |arg| arg.vals.get(0).map(|v| v.as_os_str()))
183 }
184
185 /// Gets a [`Values`] struct which implements [`Iterator`] for values of a specific argument
186 /// (i.e. an argument that takes multiple values at runtime). If the option wasn't present at
187 /// runtime it returns `None`
188 ///
189 /// # Panics
190 ///
191 /// This method will panic if any of the values contain invalid UTF-8 code points.
192 ///
193 /// # Examples
194 ///
195 /// ```rust
196 /// # use clap::{App, Arg};
197 /// let m = App::new("myprog")
198 /// .arg(Arg::with_name("output")
199 /// .multiple(true)
200 /// .short("o")
201 /// .takes_value(true))
202 /// .get_matches_from(vec![
203 /// "myprog", "-o", "val1", "val2", "val3"
204 /// ]);
205 /// let vals: Vec<&str> = m.values_of("output").unwrap().collect();
206 /// assert_eq!(vals, ["val1", "val2", "val3"]);
207 /// ```
208 /// [`Values`]: ./struct.Values.html
209 /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
210 pub fn values_of<S: AsRef<str>>(&'a self, name: S) -> Option<Values<'a>> {
211 if let Some(arg) = self.args.get(name.as_ref()) {
212 fn to_str_slice(o: &OsString) -> &str { o.to_str().expect(INVALID_UTF8) }
213 let to_str_slice: fn(&OsString) -> &str = to_str_slice; // coerce to fn pointer
214 return Some(Values { iter: arg.vals.iter().map(to_str_slice) });
215 }
216 None
217 }
218
219 /// Gets the lossy values of a specific argument. If the option wasn't present at runtime
220 /// it returns `None`. A lossy value is one where if it contains invalid UTF-8 code points,
221 /// those invalid points will be replaced with `\u{FFFD}`
222 ///
223 /// # Examples
224 ///
225 #[cfg_attr(not(unix), doc=" ```ignore")]
226 #[cfg_attr( unix , doc=" ```")]
227 /// # use clap::{App, Arg};
228 /// use std::ffi::OsString;
229 /// use std::os::unix::ffi::OsStringExt;
230 ///
231 /// let m = App::new("utf8")
232 /// .arg(Arg::from_usage("<arg>... 'some arg'"))
233 /// .get_matches_from(vec![OsString::from("myprog"),
234 /// // "Hi"
235 /// OsString::from_vec(vec![b'H', b'i']),
236 /// // "{0xe9}!"
237 /// OsString::from_vec(vec![0xe9, b'!'])]);
238 /// let mut itr = m.values_of_lossy("arg").unwrap().into_iter();
239 /// assert_eq!(&itr.next().unwrap()[..], "Hi");
240 /// assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!");
241 /// assert_eq!(itr.next(), None);
242 /// ```
243 pub fn values_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Vec<String>> {
244 if let Some(arg) = self.args.get(name.as_ref()) {
245 return Some(arg.vals
246 .iter()
247 .map(|v| v.to_string_lossy().into_owned())
248 .collect());
249 }
250 None
251 }
252
253 /// Gets a [`OsValues`] struct which is implements [`Iterator`] for [`OsString`] values of a
254 /// specific argument. If the option wasn't present at runtime it returns `None`. An OS value
255 /// on Unix-like systems is any series of bytes, regardless of whether or not they contain
256 /// valid UTF-8 code points. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid
257 /// filename as an argument value on Linux (for example) may contain invalid UTF-8 code points.
258 ///
259 /// # Examples
260 ///
261 #[cfg_attr(not(unix), doc=" ```ignore")]
262 #[cfg_attr( unix , doc=" ```")]
263 /// # use clap::{App, Arg};
264 /// use std::ffi::{OsStr,OsString};
265 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
266 ///
267 /// let m = App::new("utf8")
268 /// .arg(Arg::from_usage("<arg>... 'some arg'"))
269 /// .get_matches_from(vec![OsString::from("myprog"),
270 /// // "Hi"
271 /// OsString::from_vec(vec![b'H', b'i']),
272 /// // "{0xe9}!"
273 /// OsString::from_vec(vec![0xe9, b'!'])]);
274 ///
275 /// let mut itr = m.values_of_os("arg").unwrap().into_iter();
276 /// assert_eq!(itr.next(), Some(OsStr::new("Hi")));
277 /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!'])));
278 /// assert_eq!(itr.next(), None);
279 /// ```
280 /// [`OsValues`]: ./struct.OsValues.html
281 /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
282 /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html
283 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
284 pub fn values_of_os<S: AsRef<str>>(&'a self, name: S) -> Option<OsValues<'a>> {
285 fn to_str_slice(o: &OsString) -> &OsStr { &*o }
286 let to_str_slice: fn(&'a OsString) -> &'a OsStr = to_str_slice; // coerce to fn pointer
287 if let Some(arg) = self.args.get(name.as_ref()) {
288 return Some(OsValues { iter: arg.vals.iter().map(to_str_slice) });
289 }
290 None
291 }
292
293 /// Returns `true` if an argument was present at runtime, otherwise `false`.
294 ///
295 /// # Examples
296 ///
297 /// ```rust
298 /// # use clap::{App, Arg};
299 /// let m = App::new("myprog")
300 /// .arg(Arg::with_name("debug")
301 /// .short("d"))
302 /// .get_matches_from(vec![
303 /// "myprog", "-d"
304 /// ]);
305 ///
306 /// assert!(m.is_present("debug"));
307 /// ```
308 pub fn is_present<S: AsRef<str>>(&self, name: S) -> bool {
309 if let Some(ref sc) = self.subcommand {
310 if sc.name == name.as_ref() {
311 return true;
312 }
313 }
314 self.args.contains_key(name.as_ref())
315 }
316
317 /// Returns the number of times an argument was used at runtime. If an argument isn't present
318 /// it will return `0`.
319 ///
320 /// **NOTE:** This returns the number of times the argument was used, *not* the number of
321 /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4
322 /// values).
323 ///
324 /// # Examples
325 ///
326 /// ```rust
327 /// # use clap::{App, Arg};
328 /// let m = App::new("myprog")
329 /// .arg(Arg::with_name("debug")
330 /// .short("d")
331 /// .multiple(true))
332 /// .get_matches_from(vec![
333 /// "myprog", "-d", "-d", "-d"
334 /// ]);
335 ///
336 /// assert_eq!(m.occurrences_of("debug"), 3);
337 /// ```
338 ///
339 /// This next example shows that counts actual uses of the argument, not just `-`'s
340 ///
341 /// ```rust
342 /// # use clap::{App, Arg};
343 /// let m = App::new("myprog")
344 /// .arg(Arg::with_name("debug")
345 /// .short("d")
346 /// .multiple(true))
347 /// .arg(Arg::with_name("flag")
348 /// .short("f"))
349 /// .get_matches_from(vec![
350 /// "myprog", "-ddfd"
351 /// ]);
352 ///
353 /// assert_eq!(m.occurrences_of("debug"), 3);
354 /// assert_eq!(m.occurrences_of("flag"), 1);
355 /// ```
356 pub fn occurrences_of<S: AsRef<str>>(&self, name: S) -> u64 {
357 self.args.get(name.as_ref()).map_or(0, |a| a.occurs)
358 }
359
360 /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
361 /// as well. This method returns the [`ArgMatches`] for a particular subcommand or `None` if
362 /// the subcommand wasn't present at runtime.
363 ///
364 /// # Examples
365 ///
366 /// ```rust
367 /// # use clap::{App, Arg, SubCommand};
368 /// let app_m = App::new("myprog")
369 /// .arg(Arg::with_name("debug")
370 /// .short("d"))
371 /// .subcommand(SubCommand::with_name("test")
372 /// .arg(Arg::with_name("opt")
373 /// .long("option")
374 /// .takes_value(true)))
375 /// .get_matches_from(vec![
376 /// "myprog", "-d", "test", "--option", "val"
377 /// ]);
378 ///
379 /// // Both parent commands, and child subcommands can have arguments present at the same times
380 /// assert!(app_m.is_present("debug"));
381 ///
382 /// // Get the subcommand's ArgMatches instance
383 /// if let Some(sub_m) = app_m.subcommand_matches("test") {
384 /// // Use the struct like normal
385 /// assert_eq!(sub_m.value_of("opt"), Some("val"));
386 /// }
387 /// ```
388 /// [`Subcommand`]: ./struct.SubCommand.html
389 /// [`App`]: ./struct.App.html
390 /// [`ArgMatches`]: ./struct.ArgMatches.html
391 pub fn subcommand_matches<S: AsRef<str>>(&self, name: S) -> Option<&ArgMatches<'a>> {
392 if let Some(ref s) = self.subcommand {
393 if s.name == name.as_ref() {
394 return Some(&s.matches);
395 }
396 }
397 None
398 }
399
400 /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
401 /// as well.But simply getting the sub-[`ArgMatches`] doesn't help much if we don't also know
402 /// which subcommand was actually used. This method returns the name of the subcommand that was
403 /// used at runtime, or `None` if one wasn't.
404 ///
405 /// *NOTE*: Subcommands form a hierarchy, where multiple subcommands can be used at runtime,
406 /// but only a single subcommand from any group of sibling commands may used at once.
407 ///
408 /// An ASCII art depiction may help explain this better...Using a fictional version of `git` as
409 /// the demo subject. Imagine the following are all subcommands of `git` (note, the author is
410 /// aware these aren't actually all subcommands in the real `git` interface, but it makes
411 /// explanation easier)
412 ///
413 /// ```notrust
414 /// Top Level App (git) TOP
415 /// |
416 /// -----------------------------------------
417 /// / | \ \
418 /// clone push add commit LEVEL 1
419 /// | / \ / \ |
420 /// url origin remote ref name message LEVEL 2
421 /// / /\
422 /// path remote local LEVEL 3
423 /// ```
424 ///
425 /// Given the above fictional subcommand hierarchy, valid runtime uses would be (not an all
426 /// inclusive list, and not including argument options per command for brevity and clarity):
427 ///
428 /// ```sh
429 /// $ git clone url
430 /// $ git push origin path
431 /// $ git add ref local
432 /// $ git commit message
433 /// ```
434 ///
435 /// Notice only one command per "level" may be used. You could not, for example, do `$ git
436 /// clone url push origin path`
437 ///
438 /// # Examples
439 ///
440 /// ```no_run
441 /// # use clap::{App, Arg, SubCommand};
442 /// let app_m = App::new("git")
443 /// .subcommand(SubCommand::with_name("clone"))
444 /// .subcommand(SubCommand::with_name("push"))
445 /// .subcommand(SubCommand::with_name("commit"))
446 /// .get_matches();
447 ///
448 /// match app_m.subcommand_name() {
449 /// Some("clone") => {}, // clone was used
450 /// Some("push") => {}, // push was used
451 /// Some("commit") => {}, // commit was used
452 /// _ => {}, // Either no subcommand or one not tested for...
453 /// }
454 /// ```
455 /// [`Subcommand`]: ./struct.SubCommand.html
456 /// [`App`]: ./struct.App.html
457 /// [`ArgMatches`]: ./struct.ArgMatches.html
458 pub fn subcommand_name(&self) -> Option<&str> {
459 self.subcommand.as_ref().map(|sc| &sc.name[..])
460 }
461
462 /// This brings together [`ArgMatches::subcommand_matches`] and [`ArgMatches::subcommand_name`]
463 /// by returning a tuple with both pieces of information.
464 ///
465 /// # Examples
466 ///
467 /// ```no_run
468 /// # use clap::{App, Arg, SubCommand};
469 /// let app_m = App::new("git")
470 /// .subcommand(SubCommand::with_name("clone"))
471 /// .subcommand(SubCommand::with_name("push"))
472 /// .subcommand(SubCommand::with_name("commit"))
473 /// .get_matches();
474 ///
475 /// match app_m.subcommand() {
476 /// ("clone", Some(sub_m)) => {}, // clone was used
477 /// ("push", Some(sub_m)) => {}, // push was used
478 /// ("commit", Some(sub_m)) => {}, // commit was used
479 /// _ => {}, // Either no subcommand or one not tested for...
480 /// }
481 /// ```
482 ///
483 /// Another useful scenario is when you want to support third party, or external, subcommands.
484 /// In these cases you can't know the subcommand name ahead of time, so use a variable instead
485 /// with pattern matching!
486 ///
487 /// ```rust
488 /// # use clap::{App, AppSettings};
489 /// // Assume there is an external subcommand named "subcmd"
490 /// let app_m = App::new("myprog")
491 /// .setting(AppSettings::AllowExternalSubcommands)
492 /// .get_matches_from(vec![
493 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
494 /// ]);
495 ///
496 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
497 /// // string argument name
498 /// match app_m.subcommand() {
499 /// (external, Some(sub_m)) => {
500 /// let ext_args: Vec<&str> = sub_m.values_of("").unwrap().collect();
501 /// assert_eq!(external, "subcmd");
502 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
503 /// },
504 /// _ => {},
505 /// }
506 /// ```
507 /// [`ArgMatches::subcommand_matches`]: ./struct.ArgMatches.html#method.subcommand_matches
508 /// [`ArgMatches::subcommand_name`]: ./struct.ArgMatches.html#method.subcommand_name
509 pub fn subcommand(&self) -> (&str, Option<&ArgMatches<'a>>) {
510 self.subcommand.as_ref().map_or(("", None), |sc| (&sc.name[..], Some(&sc.matches)))
511 }
512
513 /// Returns a string slice of the usage statement for the [`App`] or [`SubCommand`]
514 ///
515 /// # Examples
516 ///
517 /// ```no_run
518 /// # use clap::{App, Arg, SubCommand};
519 /// let app_m = App::new("myprog")
520 /// .subcommand(SubCommand::with_name("test"))
521 /// .get_matches();
522 ///
523 /// println!("{}", app_m.usage());
524 /// ```
525 /// [`Subcommand`]: ./struct.SubCommand.html
526 /// [`App`]: ./struct.App.html
527 pub fn usage(&self) -> &str { self.usage.as_ref().map_or("", |u| &u[..]) }
528 }
529
530
531 // The following were taken and adapated from vec_map source
532 // repo: https://github.com/contain-rs/vec-map
533 // commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33
534 // license: MIT - Copyright (c) 2015 The Rust Project Developers
535
536 /// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of`]
537 /// method.
538 ///
539 /// # Examples
540 ///
541 /// ```rust
542 /// # use clap::{App, Arg};
543 /// let m = App::new("myapp")
544 /// .arg(Arg::with_name("output")
545 /// .takes_value(true))
546 /// .get_matches_from(vec!["myapp", "something"]);
547 ///
548 /// assert_eq!(m.value_of("output"), Some("something"));
549 /// ```
550 /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
551 #[derive(Clone)]
552 #[allow(missing_debug_implementations)]
553 pub struct Values<'a> {
554 iter: Map<Iter<'a, OsString>, fn(&'a OsString) -> &'a str>,
555 }
556
557 impl<'a> Iterator for Values<'a> {
558 type Item = &'a str;
559
560 fn next(&mut self) -> Option<&'a str> { self.iter.next() }
561 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
562 }
563
564 impl<'a> DoubleEndedIterator for Values<'a> {
565 fn next_back(&mut self) -> Option<&'a str> { self.iter.next_back() }
566 }
567
568 impl<'a> ExactSizeIterator for Values<'a> {}
569
570 /// Creates an empty iterator.
571 impl<'a> Default for Values<'a> {
572 fn default() -> Self {
573 static EMPTY: [OsString; 0] = [];
574 // This is never called because the iterator is empty:
575 fn to_str_slice(_: &OsString) -> &str { unreachable!() };
576 Values { iter: EMPTY[..].iter().map(to_str_slice) }
577 }
578 }
579
580 #[test]
581 fn test_default_values() {
582 let mut values: Values = Values::default();
583 assert_eq!(values.next(), None);
584 }
585
586 #[test]
587 fn test_default_values_with_shorter_lifetime() {
588 let matches = ArgMatches::new();
589 let mut values = matches.values_of("").unwrap_or_default();
590 assert_eq!(values.next(), None);
591 }
592
593 /// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of_os`]
594 /// method. Usage of this iterator allows values which contain invalid UTF-8 code points unlike
595 /// [`Values`].
596 ///
597 /// # Examples
598 ///
599 #[cfg_attr(not(unix), doc=" ```ignore")]
600 #[cfg_attr( unix , doc=" ```")]
601 /// # use clap::{App, Arg};
602 /// use std::ffi::OsString;
603 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
604 ///
605 /// let m = App::new("utf8")
606 /// .arg(Arg::from_usage("<arg> 'some arg'"))
607 /// .get_matches_from(vec![OsString::from("myprog"),
608 /// // "Hi {0xe9}!"
609 /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
610 /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
611 /// ```
612 /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
613 /// [`Values`]: ./struct.Values.html
614 #[derive(Clone)]
615 #[allow(missing_debug_implementations)]
616 pub struct OsValues<'a> {
617 iter: Map<Iter<'a, OsString>, fn(&'a OsString) -> &'a OsStr>,
618 }
619
620 impl<'a> Iterator for OsValues<'a> {
621 type Item = &'a OsStr;
622
623 fn next(&mut self) -> Option<&'a OsStr> { self.iter.next() }
624 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
625 }
626
627 impl<'a> DoubleEndedIterator for OsValues<'a> {
628 fn next_back(&mut self) -> Option<&'a OsStr> { self.iter.next_back() }
629 }
630
631 /// Creates an empty iterator.
632 impl<'a> Default for OsValues<'a> {
633 fn default() -> Self {
634 static EMPTY: [OsString; 0] = [];
635 // This is never called because the iterator is empty:
636 fn to_str_slice(_: &OsString) -> &OsStr { unreachable!() };
637 OsValues { iter: EMPTY[..].iter().map(to_str_slice) }
638 }
639 }
640
641 #[test]
642 fn test_default_osvalues() {
643 let mut values: OsValues = OsValues::default();
644 assert_eq!(values.next(), None);
645 }
646
647 #[test]
648 fn test_default_osvalues_with_shorter_lifetime() {
649 let matches = ArgMatches::new();
650 let mut values = matches.values_of_os("").unwrap_or_default();
651 assert_eq!(values.next(), None);
652 }