Args

Struct Args 

Source
pub struct Args { /* private fields */ }
Expand description

Arguments iterator.

This provides an additional utility layer on top of std::env::Args. It does not aim to be a fully feature argument parser, clap is great for this, at the cost of a much heavier crate.

This struct is meant to provide an iterator-like interface layering on parsing and error handling.

The two most common functions are req and opt, which will parse the current argument position and advance to the next position.

To create an Args, use the args function.

Implementations§

Source§

impl Args

Source

pub fn req<T>(&mut self, desc: impl AsRef<str>) -> Result<T>
where T: FromStr, T::Err: Error + Send + Sync + 'static,

Parse current argument, requiring it exist, and advance the argument position.

desc describes the argument in case of failure.

§Example
let mut args = Args::from(vec!["fst.txt", "24h"]);

let fst = args.req::<PathBuf>("filepath").unwrap();
// humantime::Duration can parse nicely
let dur = args.req::<Duration>("delay length").unwrap();

let err = args.req::<String>("output").unwrap_err().to_string();
assert_eq!(&err, "expecting an argument at position 3");
Source

pub fn opt<T>(&mut self, desc: impl AsRef<str>) -> Result<Option<T>>
where T: FromStr, T::Err: Error + Send + Sync + 'static,

Parse current argument, returning None if it does not exist. If it does exist (and parses), advances the argument position.

T should implement FromStr with FromStr::Err implementing [IntoDiagnostic]. desc describes the argument in case of failure.

§Example
let mut args = Args::from(vec!["fst.txt"]);

let fst = args.opt::<String>("filepath").unwrap();
assert_eq!(fst, Some("fst.txt".to_string()));
let dur = args.opt::<Duration>("delay").unwrap();
assert!(dur.is_none());

// parsing error
let mut args = Args::from(vec!["text"]);
let err = args.opt::<f64>("a number").unwrap_err();
assert_eq!(&err.to_string(), "failed to parse `text` as f64");
Source

pub fn has<P>(&mut self, pred: P) -> bool
where P: FnMut(&str) -> bool,

Test if there is an argument satifying the predicate.

This tests from the current argument position, supplying the argument text to the predicate closure.

If the argument satisfies the predicate, true is returned and that argument is excluded from future queries (including req and opt).

This is useful to test for flags.

§Example
let mut args = Args::from(vec!["fst.txt", "-c", "24h"]);

let cut = args.has(|x| x == "-c" || x == "--cut");
assert!(cut);

// skips '-c' argument when advancing
assert_eq!(&args.req::<String>("").unwrap(), "fst.txt");
assert_eq!(&args.req::<String>("").unwrap(), "24h");
Source

pub fn finish(&mut self) -> Result<()>

Assert that no more arguments should be present.

§Example
let mut args = Args::from(vec!["fst.txt", "-c", "24h"]);

args.req::<String>("").unwrap();

let err = args.finish().unwrap_err().to_string();
assert_eq!(&err, "unconsumed arguments provided");
Source

pub fn peek<T>(&mut self) -> Result<Option<T>>
where T: FromStr, T::Err: Error + Send + Sync + 'static,

Parse the current argument without advancing the argument position.

T should implement FromStr with FromStr::Err implementing [IntoDiagnostic].

§Example
let mut args = Args::from(vec!["24h"]);

let d = args.peek::<Duration>().unwrap().unwrap();
assert_eq!(d, Duration::from_str("24h").unwrap());

assert!(args.finish().is_err()); // position not advanced
Source

pub fn peek_str(&mut self) -> Option<&str>

Retrieve the current argument as a string without advancing the argument position.

§Example
let mut args = Args::from(vec!["fst.txt", "24h"]);

assert_eq!(args.peek_str(), Some("fst.txt"));
assert_eq!(&args.req::<String>("filepath").unwrap(), "fst.txt");
assert_eq!(args.peek_str(), Some("24h"));
Source

pub fn move_back(&mut self)

Retreat the argument position back one.

Skips over excluded arguments.

§Example
let mut args = Args::from(vec!["fst.txt", "-c", "24h"]);

args.has(|x| x == "-c"); // exclude -c flag
args.req::<String>("").ok();
args.req::<String>("").ok(); // at end now

args.move_back();
assert_eq!(args.peek_str(), Some("24h"));

args.move_back();
// skips the excluded
assert_eq!(args.peek_str(), Some("fst.txt"));
Source

pub fn move_front(&mut self)

Move to the front of the arguments.

Skips over excluded arguments.

§Example
let mut args = Args::from(vec!["-c", "fst.txt", "24h"]);

args.has(|x| x == "-c"); // exclude -c flag
args.req::<String>("").ok();
args.req::<String>("").ok(); // at end now

args.move_front();
assert_eq!(args.peek_str(), Some("fst.txt"));

Trait Implementations§

Source§

impl From<Vec<&'static str>> for Args

Source§

fn from(value: Vec<&'static str>) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<String>> for Args

Source§

fn from(value: Vec<String>) -> Self

Converts to this type from the input type.
Source§

impl IntoIterator for Args

Consume the remaining arguments as an iterator over the raw strings.

Note that this starts from the argument position and skips any excluded arguments.

§Example

let mut args = Args::from(vec!["fst.txt", "-c", "24h", "output"]);
args.req::<String>("").unwrap();
args.has(|x| x== "-c");

let rem = args.into_iter().collect::<Vec<_>>();
assert_eq!(&rem, &[
   "24h".to_string(),
   "output".to_string(),
]);
Source§

type Item = String

The type of the elements being iterated over.
Source§

type IntoIter = Box<dyn Iterator<Item = String>>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl Freeze for Args

§

impl !RefUnwindSafe for Args

§

impl !Send for Args

§

impl !Sync for Args

§

impl Unpin for Args

§

impl !UnwindSafe for Args

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

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

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.