Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize String.escaped #1637

Merged
merged 8 commits into from Feb 28, 2018
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 10 additions & 8 deletions stdlib/string.ml
Expand Up @@ -100,15 +100,17 @@ let trim s =
then bts (B.trim (bos s))
else s

let escaped s =
let rec needs_escape i =
if i >= length s then false else
match unsafe_get s i with
| '\"' | '\\' | '\n' | '\t' | '\r' | '\b' -> true
| ' ' .. '~' -> needs_escape (i+1)
| _ -> true
let needs_escape s =
let rec aux s n i =
if i >= n then false else
match String.unsafe_get s i with
| '\"' | '\\' | '\000'..'\031' | '\127'.. '\255' -> true
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Side note: it is "tempting" to drop the check on the length altogether (also avoiding the need to compute the length), relying on the fact that String.unsafe_get s (String.length s) returns \000. The trouble, in addition to stressing @xavierleroy, is that this doesn't work with js_of_ocaml (and presumably Bucklescript).

| _ -> aux s n (i+1)
in
if needs_escape 0 then
aux s (String.length s) 0

let escaped s =
if needs_escape s then
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On second thought (sorry), the code could be simplified by directly calling from escaped the recursive function (with the three arguments). It probably improves even a bit the generated bytecode.

bts (B.escaped (bos s))
else
s
Expand Down