impl RawArgs { //// Create an argument list to parse /// /// **NOTE:** The argument returned will be the current binary. /// /// # Example /// /// ```rust,no_run /// # use std::path::PathBuf; /// let raw = clap_lex::RawArgs::from_args(); /// let mut cursor = raw.cursor(); /// let _bin = raw.next_os(&mut cursor); /// /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::<Vec<_>>(); /// println!("{paths:?}"); /// ``` pubfn from_args() -> Self { Self::new(std::env::args_os())
}
//// Create an argument list to parse /// /// # Example /// /// ```rust,no_run /// # use std::path::PathBuf; /// let raw = clap_lex::RawArgs::new(["bin", "foo.txt"]); /// let mut cursor = raw.cursor(); /// let _bin = raw.next_os(&mut cursor); /// /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::<Vec<_>>(); /// println!("{paths:?}"); /// ``` pubfn new(iter: impl IntoIterator<Item = impl Into<OsString>>) -> Self { let iter = iter.into_iter(); Self::from(iter)
}
/// Create a cursor for walking the arguments /// /// # Example /// /// ```rust,no_run /// # use std::path::PathBuf; /// let raw = clap_lex::RawArgs::new(["bin", "foo.txt"]); /// let mut cursor = raw.cursor(); /// let _bin = raw.next_os(&mut cursor); /// /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::<Vec<_>>(); /// println!("{paths:?}"); /// ``` pubfn cursor(&self) -> ArgCursor {
ArgCursor::new()
}
/// Advance the cursor, returning the next [`ParsedArg`] pubfn next(&self, cursor: &mut ArgCursor) -> Option<ParsedArg<'_>> { self.next_os(cursor).map(ParsedArg::new)
}
/// Advance the cursor, returning a raw argument value. pubfn next_os(&self, cursor: &mut ArgCursor) -> Option<&OsStr> { let next = self.items.get(cursor.cursor).map(|s| s.as_os_str());
cursor.cursor = cursor.cursor.saturating_add(1);
next
}
/// Return the next [`ParsedArg`] pubfn peek(&self, cursor: &ArgCursor) -> Option<ParsedArg<'_>> { self.peek_os(cursor).map(ParsedArg::new)
}
/// Return a raw argument value. pubfn peek_os(&self, cursor: &ArgCursor) -> Option<&OsStr> { self.items.get(cursor.cursor).map(|s| s.as_os_str())
}
/// Return all remaining raw arguments, advancing the cursor to the end /// /// # Example /// /// ```rust,no_run /// # use std::path::PathBuf; /// let raw = clap_lex::RawArgs::new(["bin", "foo.txt"]); /// let mut cursor = raw.cursor(); /// let _bin = raw.next_os(&mut cursor); /// /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::<Vec<_>>(); /// println!("{paths:?}"); /// ``` pubfn remaining(&self, cursor: &mut ArgCursor) -> impl Iterator<Item = &OsStr> { let remaining = self.items[cursor.cursor..].iter().map(|s| s.as_os_str());
cursor.cursor = self.items.len();
remaining
}
/// Adjust the cursor's position pubfn seek(&self, cursor: &mut ArgCursor, pos: SeekFrom) { let pos = match pos {
SeekFrom::Start(pos) => pos,
SeekFrom::End(pos) => (self.items.len() as i64).saturating_add(pos).max(0) as u64,
SeekFrom::Current(pos) => (cursor.cursor as i64).saturating_add(pos).max(0) as u64,
}; let pos = (pos as usize).min(self.items.len());
cursor.cursor = pos;
}
/// Argument is length of 0 pubfn is_empty(&self) -> bool { self.inner.is_empty()
}
/// Does the argument look like a stdio argument (`-`) pubfn is_stdio(&self) -> bool { self.inner == "-"
}
/// Does the argument look like an argument escape (`--`) pubfn is_escape(&self) -> bool { self.inner == "--"
}
/// Does the argument look like a negative number? /// /// This won't parse the number in full but attempts to see if this looks /// like something along the lines of `-3`, `-0.3`, or `-33.03` pubfn is_negative_number(&self) -> bool { self.to_value()
.ok()
.and_then(|s| Some(is_number(s.strip_prefix('-')?)))
.unwrap_or_default()
}
/// Treat as a long-flag pubfn to_long(&self) -> Option<(Result<&str, &OsStr>, Option<&OsStr>)> { let raw = self.inner; let remainder = raw.strip_prefix("--")?; if remainder.is_empty() {
debug_assert!(self.is_escape()); return None;
}
let (flag, value) = iflet Some((p0, p1)) = remainder.split_once("=") {
(p0, Some(p1))
} else {
(remainder, None)
}; let flag = flag.to_str().ok_or(flag);
Some((flag, value))
}
/// Can treat as a long-flag pubfn is_long(&self) -> bool { self.inner.starts_with("--") && !self.is_escape()
}
/// Can treat as a short-flag pubfn is_short(&self) -> bool { self.inner.starts_with("-") && !self.is_stdio() && !self.inner.starts_with("--")
}
/// Treat as a value /// /// **NOTE:** May return a flag or an escape. pubfn to_value_os(&self) -> &OsStr { self.inner
}
/// Treat as a value /// /// **NOTE:** May return a flag or an escape. pubfn to_value(&self) -> Result<&str, &OsStr> { self.inner.to_str().ok_or(self.inner)
}
/// Safely print an argument that may contain non-UTF8 content /// /// This may perform lossy conversion, depending on the platform. If you would like an implementation which escapes the path please use Debug instead. pubfn display(&self) -> impl std::fmt::Display + '_ { self.inner.to_string_lossy()
}
}
/// Walk through short flags within a [`ParsedArg`] #[derive(Clone, Debug)] pubstruct ShortFlags<'s> {
inner: &'s OsStr,
utf8_prefix: std::str::CharIndices<'s>,
invalid_suffix: Option<&'s OsStr>,
}
/// Move the iterator forward by `n` short flags pubfn advance_by(&mutself, n: usize) -> Result<(), usize> { for i in0..n { self.next().ok_or(i)?.map_err(|_| i)?;
}
Ok(())
}
/// No short flags left pubfn is_empty(&self) -> bool { self.invalid_suffix.is_none() && self.utf8_prefix.as_str().is_empty()
}
/// Does the short flag look like a number /// /// Ideally call this before doing any iterator pubfn is_negative_number(&self) -> bool { self.invalid_suffix.is_none() && is_number(self.utf8_prefix.as_str())
}
/// Advance the iterator, returning the next short flag on success /// /// On error, returns the invalid-UTF8 value pubfn next_flag(&mutself) -> Option<Result<char, &'s OsStr>> { iflet Some((_, flag)) = self.utf8_prefix.next() { return Some(Ok(flag));
}
fn split_nonutf8_once(b: &OsStr) -> (&str, Option<&OsStr>) { match b.try_str() {
Ok(s) => (s, None),
Err(err) => { // SAFETY: `err.valid_up_to()`, which came from str::from_utf8(), is guaranteed // to be a valid UTF8 boundary let (valid, after_valid) = unsafe { ext::split_at(b, err.valid_up_to()) }; let valid = valid.try_str().unwrap();
(valid, Some(after_valid))
}
}
}
fn is_number(arg: &str) -> bool { // Return true if this looks like an integer or a float where it's all // digits plus an optional single dot after some digits. // // For floats allow forms such as `1.`, `1.2`, `1.2e10`, etc. letmut seen_dot = false; letmut position_of_e = None; for (i, c) in arg.as_bytes().iter().enumerate() { match c { // Digits are always valid
b'0'..=b'9' => {}
// Allow a `.`, but only one, only if it comes before an // optional exponent, and only if it's not the first character.
b'.'if !seen_dot && position_of_e.is_none() && i > 0 => seen_dot = true,
// Allow an exponent `e` but only at most one after the first // character.
b'e'if position_of_e.is_none() && i > 0 => position_of_e = Some(i),
_ => returnfalse,
}
}
// Disallow `-1e` which isn't a valid float since it doesn't actually have // an exponent. match position_of_e {
Some(i) => i != arg.len() - 1,
None => true,
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.