Skip to content

Instantly share code, notes, and snippets.

@lights0123
Created March 27, 2021 15:27
Show Gist options
  • Save lights0123/d0ca064a6ece2eefdd8820a88ac0fa58 to your computer and use it in GitHub Desktop.
Save lights0123/d0ca064a6ece2eefdd8820a88ac0fa58 to your computer and use it in GitHub Desktop.
fn escape_str<W: fmt::Write>(mut f: W, mut s: &str, replacements: &[(u8, &str)]) -> fmt::Result {
while !s.is_empty() {
let (idx, replacement) = s
.as_bytes()
.iter()
.enumerate()
.find_map(|(i, c)| {
replacements
.iter()
.find(|(r, _)| c == r)
.map(|(_, replacement)| (i, *replacement))
})
.unwrap_or((s.len(), ""));
write!(f, "{}{}", &s[..idx], replacement)?;
s = &s[s.len().min(idx + 1)..];
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment