[][src]Struct getopt::Parser

pub struct Parser { /* fields omitted */ }

The core of the getopt crate.

Parser is implemented as an iterator over the options present in the given argument vector.

The method next does the heavy lifting.

Examples

Simplified usage:

use getopt::Opt;

// args = ["program", "-abc", "foo"];
let mut opts = getopt::Parser::new(&args, "ab:c");

assert_eq!(Some(Opt('a', None)), opts.next().transpose()?);
assert_eq!(1, opts.index());
assert_eq!(Some(Opt('b', Some("c".to_string()))), opts.next().transpose()?);
assert_eq!(2, opts.index());
assert_eq!(None, opts.next());
assert_eq!(2, opts.index());
assert_eq!("foo", args[opts.index()]);

A more idiomatic example:

use getopt::Opt;

// args = ["program", "-abc", "-d", "foo", "-e", "bar"];
let mut opts = getopt::Parser::new(&args, "ab:cd:e");

let mut a_flag = false;
let mut b_flag = String::new();
let mut c_flag = false;
let mut d_flag = String::new();
let mut e_flag = false;

loop {
    match opts.next().transpose()? {
        None => break,
        Some(opt) => match opt {
            Opt('a', None) => a_flag = true,
            Opt('b', Some(arg)) => b_flag = arg.clone(),
            Opt('c', None) => c_flag = true,
            Opt('d', Some(arg)) => d_flag = arg.clone(),
            Opt('e', None) => e_flag = true,
            _ => unreachable!(),
        },
    }
}

let new_args = args.split_off(opts.index());

assert_eq!(true, a_flag);
assert_eq!("c", b_flag);
assert_eq!(false, c_flag);
assert_eq!("foo", d_flag);
assert_eq!(true, e_flag);

assert_eq!(1, new_args.len());
assert_eq!("bar", new_args.first().unwrap());

Implementations

impl Parser[src]

pub fn new(args: &[String], optstring: &str) -> Self[src]

Create a new Parser, which will process the arguments in args according to the options specified in optstring.

For compatibility with std::env::args, valid options are expected to begin at the second element of args, and index is initialised to 1. If args is structured differently, be sure to call set_index before the first invocation of next.

optstring is a string of recognised option characters; if a character is followed by a colon (:), that option takes an argument.

Note:

Transforming the OS-specific argument strings into a vector of Strings is the sole responsibility of the calling program, as it involves some level of potential information loss (which this crate does not presume to handle unilaterally) and error handling (which would complicate the interface).

pub fn index(&self) -> usize[src]

Return the current index of the parser.

args[index] will always point to the the next element of args; when the parser is finished with an element, it will increment index.

After the last option has been parsed (and next is returning None), index will point to the first non-option argument.

pub fn set_index(&mut self, value: usize)[src]

Modify the current index of the parser.

pub fn incr_index(&mut self)[src]

Increment the current index of the parser.

This use case is common enough to warrant its own optimised method.

Trait Implementations

impl Debug for Parser[src]

impl Eq for Parser[src]

impl Iterator for Parser[src]

type Item = Result<Opt>

The type of the elements being iterated over.

pub fn next(&mut self) -> Option<Result<Opt>>[src]

Returns the next option, if any.

Returns an Error if an unexpected option is encountered or if an expected argument is not found.

Parsing stops at the first non-hyphenated argument; or at the first argument matching "-"; or after the first argument matching "--".

When no more options are available, next returns None.

Examples

"-"

use getopt::Parser;

// args = ["program", "-", "-a"];
let mut opts = Parser::new(&args, "a");

assert_eq!(None, opts.next());
assert_eq!("-", args[opts.index()]);

"--"

use getopt::Parser;

// args = ["program", "--", "-a"];
let mut opts = Parser::new(&args, "a");

assert_eq!(None, opts.next());
assert_eq!("-a", args[opts.index()]);

Unexpected option:

use getopt::Parser;

// args = ["program", "-b"];
let mut opts = Parser::new(&args, "a");

assert_eq!(
    "unknown option -- 'b'".to_string(),
    opts.next().unwrap().unwrap_err().to_string()
);

Missing argument:

use getopt::Parser;

// args = ["program", "-a"];
let mut opts = Parser::new(&args, "a:");

assert_eq!(
    "option requires an argument -- 'a'".to_string(),
    opts.next().unwrap().unwrap_err().to_string()
);

impl PartialEq<Parser> for Parser[src]

impl StructuralEq for Parser[src]

impl StructuralPartialEq for Parser[src]

Auto Trait Implementations

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<I> IntoIterator for I where
    I: Iterator
[src]

type Item = <I as Iterator>::Item

The type of the elements being iterated over.

type IntoIter = I

Which kind of iterator are we turning this into?

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.