Skip to content

Commit 16df266

Browse files
committed
fix: make End_of_line.Convert.lf_to_crlf compatible with OCaml 4.08
1 parent a732482 commit 16df266

1 file changed

Lines changed: 28 additions & 17 deletions

File tree

src/refmt/end_of_line.ml

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -20,24 +20,35 @@ end
2020

2121
module Convert = struct
2222
let lf_to_crlf =
23-
let crlf = "\r\n" in
24-
let rec loop sz =
25-
match String.index sz '\n' with
26-
| exception Not_found -> sz
27-
| idx ->
28-
let buf = Bytes.create (idx + 2) in
29-
Bytes.unsafe_blit_string ~src:sz ~src_pos:0 ~dst:buf ~dst_pos:0 ~len:idx;
30-
Bytes.unsafe_blit_string
31-
~src:crlf
32-
~src_pos:0
33-
~dst:buf
34-
~dst_pos:idx
35-
~len:2;
36-
let l = Bytes.unsafe_to_string buf in
37-
let length = String.length sz in
38-
l ^ loop (String.sub sz ~pos:(idx + 1) ~len:(length - idx - 1))
23+
let rec loop ~src i j ~dst ~len =
24+
if i >= len
25+
then ()
26+
else
27+
match String.unsafe_get src i with
28+
| '\n' ->
29+
Bytes.unsafe_set dst j '\r';
30+
Bytes.unsafe_set dst (j + 1) '\n';
31+
loop (i + 1) (j + 2) ~src ~dst ~len
32+
| c ->
33+
Bytes.unsafe_set dst j c;
34+
loop (i + 1) (j + 1) ~src ~dst ~len
3935
in
40-
fun s -> loop s
36+
let rec count_newlines ~src ~src_len i acc =
37+
if i >= src_len
38+
then acc
39+
else
40+
match String.index_from src i '\n' with
41+
| exception Not_found -> acc
42+
| j -> count_newlines ~src ~src_len (j + 1) (acc + 1)
43+
in
44+
fun s ->
45+
let len = String.length s in
46+
match count_newlines ~src:s ~src_len:len 0 0 with
47+
| 0 -> s
48+
| nl_count ->
49+
let dst = Bytes.create (len + nl_count) in
50+
loop 0 0 ~src:s ~dst ~len;
51+
Bytes.unsafe_to_string dst
4152

4253
let get_formatter =
4354
let out_string (out_functions : Format.formatter_out_functions) eol =

0 commit comments

Comments
 (0)