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