ffmpeg_sidecar/comma_iter.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
//! An internal utility used to parse comma-separated values in FFmpeg logs.
use std::str::Chars;
/// An iterator over comma-separated values, **ignoring commas inside parentheses**.
///
/// ## Examples
///
/// ```rust
/// use ffmpeg_sidecar::comma_iter::CommaIter;
///
/// let string = "foo(bar,baz),quux";
/// let mut iter = CommaIter::new(string);
///
/// assert_eq!(iter.next(), Some("foo(bar,baz)"));
/// assert_eq!(iter.next(), Some("quux"));
/// assert_eq!(iter.next(), None);
/// ```
pub struct CommaIter<'a> {
chars: Chars<'a>,
}
impl<'a> CommaIter<'a> {
pub fn new(string: &'a str) -> Self {
Self {
chars: string.chars(),
}
}
}
impl<'a> Iterator for CommaIter<'a> {
type Item = &'a str;
/// Return the next comma-separated section, not including the comma.
fn next(&mut self) -> Option<Self::Item> {
let chars_clone = self.chars.clone();
let mut i = 0;
while let Some(char) = self.chars.next() {
match char {
'(' => {
// advance until closing paren (only handles one level nesting)
for close_paren in self.chars.by_ref() {
i += 1;
if close_paren == ')' {
break;
}
}
}
',' => break,
_ => {}
}
i += 1;
}
match i {
0 => None,
_ => Some(&chars_clone.as_str()[..i]),
}
}
}