@@ -13,7 +13,8 @@ export eq, lteq, hash, is_empty, is_not_empty, is_whitespace, byte_len,
13
13
shift_byte, pop_byte,
14
14
unsafe_from_byte, unsafe_from_bytes, from_char, char_range_at,
15
15
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;
17
18
18
19
native "cdecl" mod rustrt {
19
20
fn rust_str_push ( & s: str , ch : u8 ) ;
@@ -367,7 +368,7 @@ fn loop_chars(s: str, it: block(char) -> bool) -> bool{
367
368
}
368
369
369
370
/*
370
- Function: loop_chars
371
+ Function: loop_chars_sub
371
372
372
373
Loop through a substring, char by char
373
374
@@ -928,3 +929,32 @@ unsafe fn str_from_cstr(cstr: sbuf) -> str {
928
929
ret res;
929
930
}
930
931
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
+ }
0 commit comments