Skip to content

Instantly share code, notes, and snippets.

@blyxxyz
Created July 17, 2021 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blyxxyz/06b45c82c4a4f1030a89e0289adebf09 to your computer and use it in GitHub Desktop.
Save blyxxyz/06b45c82c4a4f1030a89e0289adebf09 to your computer and use it in GitHub Desktop.
Keeping track of argument position in lexopt
use std::cell::RefCell;
use std::rc::Rc;
struct TrackingIterator<T>(Rc<RefCell<(u64, T)>>);
impl<T> TrackingIterator<T> {
fn new(inner: T) -> Self {
Self(Rc::new(RefCell::new((0, inner))))
}
fn position(&self) -> u64 {
self.0.borrow().0
}
}
impl<T> Clone for TrackingIterator<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T> Iterator for TrackingIterator<T>
where
T: Iterator,
{
type Item = T::Item;
fn next(&mut self) -> Option<T::Item> {
let mut inner = self.0.borrow_mut();
inner.0 += 1;
inner.1.next()
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args_os();
args.next();
let args = TrackingIterator::new(args);
let mut parser = lexopt::Parser::from_args(args.clone());
while let Some(arg) = parser.next()? {
println!("{:?} at pos {}", arg, args.position());
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment