Skip to content

Commit

Permalink
Encode HTML more efficiently
Browse files Browse the repository at this point in the history
  • Loading branch information
davesnx committed Aug 29, 2023
1 parent f46fa4b commit d671a46
Showing 1 changed file with 10 additions and 36 deletions.
46 changes: 10 additions & 36 deletions packages/html/html.ml
Original file line number Diff line number Diff line change
@@ -1,42 +1,16 @@
(* Based on https://github.com/facebook/react/blob/97d75c9c8bcddb0daed1ed062101c7f5e9b825f4/packages/react-dom-bindings/src/server/escapeTextForBrowser.js#L51-L98 *)
(* https://discuss.ocaml.org/t/html-encoding-of-string/4289/4 *)
let encode s =
let add = Buffer.add_string in
let len = String.length s in
let buff = Buffer.create len in
let max_idx = len - 1 in
let flush buff start i =
if start < len then Buffer.add_substring buff s start (i - start)
in
let rec escape_inner start i =
if i > max_idx then flush buff start i
else
let next = i + 1 in
match String.get s i with
| '&' ->
flush buff start i;
add buff "&amp;";
escape_inner next next
| '<' ->
flush buff start i;
add buff "&lt;";
escape_inner next next
| '>' ->
flush buff start i;
add buff "&gt;";
escape_inner next next
| '\'' ->
flush buff start i;
add buff "&#x27;";
escape_inner next next
| '\"' ->
flush buff start i;
add buff "&quot;";
escape_inner next next
| _ -> escape_inner start next
in
escape_inner 0 0 |> ignore;
Buffer.contents buff
let buffer = Buffer.create (String.length s * 2) in
s
|> String.iter (function
| '&' -> Buffer.add_string buffer "&amp;"
| '<' -> Buffer.add_string buffer "&lt;"
| '>' -> Buffer.add_string buffer "&gt;"
| '"' -> Buffer.add_string buffer "&quot;"
| '\'' -> Buffer.add_string buffer "&#x27;"
| c -> Buffer.add_char buffer c);
Buffer.contents buffer

let is_self_closing_tag = function
(* https://github.com/facebook/react/blob/97d75c9c8bcddb0daed1ed062101c7f5e9b825f4/packages/react-dom-bindings/src/shared/omittedCloseTags.js *)
Expand Down

0 comments on commit d671a46

Please sign in to comment.