Skip to content

Instantly share code, notes, and snippets.

@dcormier
Last active July 29, 2024 02:38
Show Gist options
  • Save dcormier/3ec7f4bfd08dcd7a2bdd57192bb8826b to your computer and use it in GitHub Desktop.
Save dcormier/3ec7f4bfd08dcd7a2bdd57192bb8826b to your computer and use it in GitHub Desktop.
Enclose a string written by a closure in opening and closing chars, or a specified number of parentheses.
/// Encloses the string written by `enclosed` in the opening an closing
/// characters provided.
fn enclose<F>(s: &mut String, open: char, close: char, enclosed: F)
where
F: FnOnce(&mut String),
{
s.push(open);
enclosed(s);
s.push(close);
}
/// The string written by the `enclosed` function will be enclosed in
/// `parens_count` pairs of parentheses. A count of `0` is allowed.
fn parenthesize<F>(s: &mut String, parens_count: usize, enclosed: F)
where
F: FnOnce(&mut String),
{
match parens_count {
0 => {
enclosed(s);
return;
}
1 => {
enclose(s, '(', ')', enclosed);
return;
}
_ => {}
}
let mut enclosed: Box<dyn FnOnce(&mut String)> = Box::new(enclosed);
for _ in 0..parens_count {
enclosed = Box::new(|s| enclose(s, '(', ')', enclosed));
}
enclosed(s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment