Skip to content

Commit 268a2a4

Browse files
Elly Jonesbrson
authored andcommitted
---
yaml --- r: 6248 b: refs/heads/master c: 24b6645 h: refs/heads/master v: v3
1 parent b3e7326 commit 268a2a4

File tree

3 files changed

+41
-3
lines changed

3 files changed

+41
-3
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
---
2-
refs/heads/master: 7ee8b852fd9eb1b4acb4ee48714487c6b3b35e98
2+
refs/heads/master: 24b66451568769236202e90e29a3540b802e1373

trunk/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+
}

trunk/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)