Skip to content

Commit

Permalink
Add proper escaping for String::escape_to
Browse files Browse the repository at this point in the history
  • Loading branch information
lynzrand authored and bobzhang committed Mar 22, 2024
1 parent 1468035 commit c737fd2
Showing 1 changed file with 28 additions and 9 deletions.
37 changes: 28 additions & 9 deletions string/string.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,38 @@
/// This method only escapes characters below 0x20 and the following characters:
/// `"`, `'`, `\`.
pub fn escape_to(self : String, buf : Buffer) -> Unit {
fn write_escaped_ch(ch : Char) -> Unit {
buf.write_char('\\')
buf.write_char(ch)
}

fn to_hex_digit(i : Int) -> Char {
if i < 10 {
Char::from_int('0'.to_int() + i)
} else {
Char::from_int('a'.to_int() + (i - 10))
}
}

let mut ix = 0
while ix < self.length() {
let ch = self[ix]
match ch {
'"' | '\'' | '\\' => {
buf.write_char('\\')
buf.write_char(ch)
}
'\n' => {
buf.write_char('\\')
buf.write_char('n')
}
_ => buf.write_char(ch)
'"' | '\'' | '\\' => write_escaped_ch(ch)
'\n' => write_escaped_ch('n')
'\r' => write_escaped_ch('r')
'\b' => write_escaped_ch('b')
'\t' => write_escaped_ch('t')
_ =>
if ch.to_int() < 0x20 {
buf.write_char('\\')
buf.write_char('x')
let ich = ch.to_int()
buf.write_char(to_hex_digit(ich / 16))
buf.write_char(to_hex_digit(ich % 16))
} else {
buf.write_char(ch)
}
}
ix += 1
}
Expand Down

0 comments on commit c737fd2

Please sign in to comment.