浏览代码

better s_escape (handle < 32 and utf8 correctly)

Nicolas Cannasse 12 年之前
父节点
当前提交
e1f5459f7f
共有 1 个文件被更改,包括 10 次插入2 次删除
  1. 10 2
      ast.ml

+ 10 - 2
ast.ml

@@ -456,14 +456,22 @@ let parse_path s =
 
 let s_escape s =
 	let b = Buffer.create (String.length s) in
+	let utf8 = ref false in
 	for i = 0 to (String.length s) - 1 do
-		match s.[i] with
+		if !utf8 then begin
+			let c = s.[i] in
+			Buffer.add_char b c;
+			utf8 := int_of_char c >= 128;
+		end else match s.[i] with
 		| '\n' -> Buffer.add_string b "\\n"
 		| '\t' -> Buffer.add_string b "\\t"
 		| '\r' -> Buffer.add_string b "\\r"
 		| '"' -> Buffer.add_string b "\\\""
 		| '\\' -> Buffer.add_string b "\\\\"
-		| c -> Buffer.add_char b c
+		| c when int_of_char c < 32 -> Buffer.add_string b (Printf.sprintf "\\x%.2X" (int_of_char c))
+		| c ->
+			if int_of_char c >= 128 then utf8 := true;
+			Buffer.add_char b c
 	done;
 	Buffer.contents b