Created
July 17, 2021 11:18
-
-
Save blyxxyz/06b45c82c4a4f1030a89e0289adebf09 to your computer and use it in GitHub Desktop.
Keeping track of argument position in lexopt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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