let parts: Vec<&str> = trimmed.split(';').collect();
let mut entries = Vec::with_capacity(parts.len());
for part in parts {
let seg = part.trim();
if seg.is_empty() {
return Err(EntryParseError::Key);
}
code
if let Some(eq_pos) = seg.find('=') {
let key = &seg[..eq_pos].trim();
let val = &seg[eq_pos + 1..].trim();
if key.is_empty() {
return Err(EntryParseError::Key);
}
if val.is_empty() {
return Err(EntryParseError::Value);
}
entries.push(Entry::Pair(key.to_string(), val.to_string()));
} else {
entries.push(Entry::Single(seg.to_string()));
}
The refactoring extracts the common parsing logic into a generic parse_semicolon_separated function that:
Handles the input normalization (replacing newlines with spaces)
Trims whitespace and checks for empty input
Splits on semicolons and processes each segment
Uses a closure to handle the specific parsing logic for each segment type
This eliminates the code duplication while maintaining the same functionality and error handling behavior. The generic function takes the error to return for empty input and a mapper function that defines how to process each segment.