#![doc(html_root_url = "https://docs.rs/miniarg/0.5.0")]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
use alloc::string::{String, ToString};
use core::fmt;
use core::iter::Skip;
#[cfg(feature = "std")]
use std::error::Error;
use cfg_if::cfg_if;
mod parse;
pub mod split_args;
use split_args::SplitArgs;
#[cfg(not(feature = "alloc"))]
pub trait ToString {
fn to_string(&self) -> &str;
}
#[cfg(not(feature = "alloc"))]
impl<'b> ToString for &str {
fn to_string(&self) -> &str {
self
}
}
#[cfg(not(feature = "std"))]
trait Error {}
pub fn parse<'a, 'b, T>(
cmdline: &'a str,
options: &'b [T],
) -> ArgumentIterator<'a, 'b, T, SplitArgs<'a>>
where
T: ToString,
{
let args = SplitArgs::new(cmdline);
ArgumentIterator::<'a, 'b, T, SplitArgs>::new(args, options)
}
pub fn parse_from_iter<'a, 'b, T, S>(args: S, options: &'b [T]) -> ArgumentIterator<'a, 'b, T, S>
where
T: ToString,
S: Iterator<Item = &'a str>,
{
ArgumentIterator::<'a, 'b, T, S>::new(args, options)
}
pub struct ArgumentIterator<'a, 'b, T, S>
where
T: ToString,
S: Iterator<Item = &'a str>,
{
args: Skip<S>,
options: &'b [T],
last: Option<&'b T>,
}
impl<'a, 'b, T, S> ArgumentIterator<'a, 'b, T, S>
where
T: ToString,
S: Iterator<Item = &'a str>,
{
fn new(args: S, options: &'b [T]) -> Self {
ArgumentIterator {
args: args.skip(1),
options,
last: None,
}
}
}
impl<'a, 'b, T, S> Iterator for ArgumentIterator<'a, 'b, T, S>
where
T: ToString,
S: Iterator<Item = &'a str>,
{
type Item = Result<(&'b T, &'a str), ParseError<'a>>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let Some(arg) = self.args.next() else {
return match self.last {
Some(l) => {
self.last = None;
Some(Ok((l, "")))
}
None => None,
};
};
if let Some(l) = self.last {
self.last = None;
return Some(Ok((l, arg)));
}
if let Some(a) = arg.strip_prefix("-") {
self.last = self.options.iter().find(|o| {
cfg_if! {
if #[cfg(any(feature = "alloc", feature = "std"))] {
first_lower(&o.to_string())
} else {
o.to_string()
}
}
} == a);
if self.last.is_none() {
return Some(Err(ParseError::UnknownKey(a)));
}
} else {
return Some(Err(ParseError::NotAKey(arg)));
}
}
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[non_exhaustive]
pub enum ParseError<'a> {
NotAKey(&'a str),
UnknownKey(&'a str),
_Unknown,
}
impl fmt::Display for ParseError<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
Self::NotAKey(s) => write!(f, "expected '{s}' to start with a dash"),
Self::UnknownKey(s) => write!(f, "'{s}' is not a known key"),
_ => write!(f, "unknown parse error"),
}
}
}
impl Error for ParseError<'_> {}
#[cfg(all(feature = "derive", not(feature = "alloc")))]
compile_error!("at least the `alloc` feature is currently required to get the derive feature");
#[cfg(feature = "derive")]
pub trait Key {
fn parse(cmdline: &str) -> ArgumentIterator<Self, SplitArgs>
where
Self: ToString + Sized;
fn help_text() -> &'static str;
}
#[cfg(feature = "derive")]
pub use miniarg_derive::Key;
#[cfg(feature = "alloc")]
fn first_lower(input: &str) -> String {
let mut c = input.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_lowercase().collect::<String>() + c.as_str(),
}
}