Skip to content

Commit 24b6645

Browse files
Elly Jonesbrson
authored andcommitted
str: add escape()
Signed-off-by: Elly Jones <[email protected]>
1 parent 7ee8b85 commit 24b6645

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

src/lib/str.rs

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ export eq, lteq, hash, is_empty, is_not_empty, is_whitespace, byte_len,
1313
shift_byte, pop_byte,
1414
unsafe_from_byte, unsafe_from_bytes, from_char, char_range_at,
1515
str_from_cstr, sbuf, as_buf, push_byte, utf8_char_width, safe_slice,
16-
contains, iter_chars, loop_chars, loop_chars_sub;
16+
contains, iter_chars, loop_chars, loop_chars_sub,
17+
escape;
1718

1819
native "cdecl" mod rustrt {
1920
fn rust_str_push(&s: str, ch: u8);
@@ -367,7 +368,7 @@ fn loop_chars(s: str, it: block(char) -> bool) -> bool{
367368
}
368369

369370
/*
370-
Function: loop_chars
371+
Function: loop_chars_sub
371372
372373
Loop through a substring, char by char
373374
@@ -928,3 +929,32 @@ unsafe fn str_from_cstr(cstr: sbuf) -> str {
928929
ret res;
929930
}
930931

932+
/*
933+
Function: escape_char
934+
935+
Escapes a single character.
936+
*/
937+
fn escape_char(c: char) -> str {
938+
alt c {
939+
'"' { "\\\"" }
940+
'\\' { "\\\\" }
941+
// TODO: uncomment these when https://github.com/graydon/rust/issues/1170 is
942+
// fixed.
943+
// '\n' { "\\n" }
944+
// '\t' { "\\t" }
945+
// '\r' { "\\r" }
946+
'\x00' to '\x1f' { #fmt["\\x%02x", c as uint] }
947+
v { from_char(c) }
948+
}
949+
}
950+
951+
/*
952+
Function: escape
953+
954+
Escapes special characters inside the string, making it safe for transfer.
955+
*/
956+
fn escape(s: str) -> str {
957+
let r = "";
958+
loop_chars(s, { |c| r += escape_char(c); true });
959+
r
960+
}

src/test/stdtest/str.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,3 +328,11 @@ fn iter_chars() {
328328
i += 1;
329329
}
330330
}
331+
332+
#[test]
333+
fn escape() {
334+
assert(str::escape("abcdef") == "abcdef");
335+
assert(str::escape("abc\\def") == "abc\\\\def");
336+
assert(str::escape("abc\ndef") == "abc\\x0adef");
337+
assert(str::escape("abc\"def") == "abc\\\"def");
338+
}

0 commit comments

Comments
 (0)