async_ffmpeg_sidecar/
comma_iter.rs

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