option_parser: Simplify code for splitting on commas

The parsing is now O(1) as we only consider each character in the input
once and further it removes the need for allocating memory for
reassembling the option parameter.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
This commit is contained in:
Rob Bradford 2022-08-08 13:47:38 +01:00
parent 9990439829
commit 46b790b582

View File

@ -40,26 +40,38 @@ type OptionParserResult<T> = std::result::Result<T, OptionParserError>;
fn split_commas_outside_brackets(s: &str) -> OptionParserResult<Vec<String>> { fn split_commas_outside_brackets(s: &str) -> OptionParserResult<Vec<String>> {
let mut list: Vec<String> = Vec::new(); let mut list: Vec<String> = Vec::new();
let mut opened_brackets: usize = 0; let mut opened_brackets = 0;
for element in s.trim().split(',') { let mut current = String::new();
if opened_brackets > 0 {
if let Some(last) = list.last_mut() {
*last = format!("{},{}", last, element);
} else {
return Err(OptionParserError::InvalidSyntax(s.to_owned()));
}
} else {
list.push(element.to_string());
}
opened_brackets += element.matches('[').count(); for c in s.trim().chars() {
let closing_brackets = element.matches(']').count(); match c {
if closing_brackets > opened_brackets { '[' => {
return Err(OptionParserError::InvalidSyntax(s.to_owned())); opened_brackets += 1;
} else { current.push('[');
opened_brackets -= closing_brackets; }
']' => {
opened_brackets -= 1;
if opened_brackets < 0 {
return Err(OptionParserError::InvalidSyntax(s.to_owned()));
}
current.push(']');
}
',' => {
if opened_brackets > 0 {
current.push(',')
} else {
list.push(current);
current = String::new();
}
}
c => current.push(c),
} }
} }
list.push(current);
if opened_brackets != 0 {
return Err(OptionParserError::InvalidSyntax(s.to_owned()));
}
Ok(list) Ok(list)
} }