Skip to content

Commit

Permalink
IH-553: Sexpr.escape should be a noop when nothing to escape
Browse files Browse the repository at this point in the history
Optimistically check for the presence of escape characters before escaping.
This avoids rebuilding the string when escapable characters are not present (the common case).

Signed-off-by: Edwin Török <[email protected]>
  • Loading branch information
edwintorok committed Apr 19, 2024
1 parent a4cedc2 commit c1b5231
Showing 1 changed file with 20 additions and 15 deletions.
35 changes: 20 additions & 15 deletions ocaml/libs/sexpr/sExpr.ml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ let unescape_buf buf s =
if Astring.String.fold_left aux false s then
Buffer.add_char buf '\\'

let is_escape_char = function '\\' | '"' | '\'' -> true | _ -> false

(* XXX: This escapes "'c'" and "\'c\'" to "\\'c\\'".
* They are both unescaped as "'c'". They have been ported
* to make sure that this corner case is left unchanged.
Expand All @@ -36,21 +38,24 @@ let unescape_buf buf s =
* that have guaranteed invariants and optimised performances *)
let escape s =
let open Astring in
let escaped = Buffer.create (String.length s + 10) in
String.iter
(fun c ->
match c with
| '\\' ->
Buffer.add_string escaped "\\\\"
| '"' ->
Buffer.add_string escaped "\\\""
| '\'' ->
Buffer.add_string escaped "\\\'"
| _ ->
Buffer.add_char escaped c
)
s ;
Buffer.contents escaped
if String.exists is_escape_char s then (
let escaped = Buffer.create (String.length s + 10) in
String.iter
(fun c ->
match c with
| '\\' ->
Buffer.add_string escaped "\\\\"
| '"' ->
Buffer.add_string escaped "\\\""
| '\'' ->
Buffer.add_string escaped "\\\'"
| _ ->
Buffer.add_char escaped c
)
s ;
Buffer.contents escaped
) else
s

let unescape s =
let buf = Buffer.create (String.length s) in
Expand Down

0 comments on commit c1b5231

Please sign in to comment.