-
Notifications
You must be signed in to change notification settings - Fork 1
/
Encoder.re
34 lines (32 loc) · 965 Bytes
/
Encoder.re
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
let isControlChar = code =>
code <= 31
&& code != 9
&& code != 10
&& code != 13
|| code >= 127
&& code <= 159
|| code
land 0xFFFF == 0xFFFE
|| code
land 0xFFFF == 0xFFFF;
let encodeChar = (buffer, ch) =>
switch (ch) {
| `Uchar(u) =>
switch (Uchar.to_int(u)) {
| 38 => Buffer.add_string(buffer, "&")
| 60 => Buffer.add_string(buffer, "<")
| 62 => Buffer.add_string(buffer, ">")
| 34 => Buffer.add_string(buffer, """)
| 39 => Buffer.add_string(buffer, "'")
| 47 => Buffer.add_string(buffer, "/")
| code when isControlChar(code) =>
Buffer.add_utf_8_uchar(buffer, Uutf.u_rep)
| _ => Buffer.add_utf_8_uchar(buffer, u)
}
| `Malformed(_) => Buffer.add_utf_8_uchar(buffer, Uutf.u_rep)
};
let encodeHtml = text => {
let buffer = Buffer.create @@ String.length(text);
Uutf.String.fold_utf_8((_, _, ch) => encodeChar(buffer, ch), (), text);
Buffer.contents(buffer);
};