From 351741b820691ba2fc5ee29e8bac6c3fc695383a Mon Sep 17 00:00:00 2001 From: Thibaut Mattio Date: Fri, 23 Jun 2023 15:09:05 +0200 Subject: [PATCH] Check Zed.next_error index value is within the string length (#442) This fixes Zed.Out_of_bound errors Co-authored-by: Etienne Millon --- src/lib/uTop.ml | 42 ++++++++++++++++++++++++------------------ test/test_lib.ml | 1 + 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/src/lib/uTop.ml b/src/lib/uTop.ml index 1afc1c2..589f2f1 100644 --- a/src/lib/uTop.ml +++ b/src/lib/uTop.ml @@ -849,23 +849,29 @@ let prompt_comment = ref (S.const [| |]) module Private = struct let fix_string str = let len = String.length str in - let ofs, _, _ = Zed_utf8.next_error str 0 in - if ofs = len then + if len = 0 then str - else begin - let buf = Buffer.create (len + 128) in - if ofs > 0 then Buffer.add_substring buf str 0 ofs; - let rec loop ofs = - Zed_utf8.add buf (Uchar.of_char str.[ofs]); - let ofs1 = ofs + 1 in - let ofs2, _, _ = Zed_utf8.next_error str ofs1 in - if ofs1 < ofs2 then - Buffer.add_substring buf str ofs1 (ofs2 - ofs1); - if ofs2 < len then - loop ofs2 - else - Buffer.contents buf - in - loop ofs - end + else + let ofs, _, _ = Zed_utf8.next_error str 0 in + if ofs = len then + str + else begin + let buf = Buffer.create (len + 128) in + if ofs > 0 then Buffer.add_substring buf str 0 ofs; + let rec loop ofs = + Zed_utf8.add buf (Uchar.of_char str.[ofs]); + let ofs1 = ofs + 1 in + if ofs1 < len then + let ofs2, _, _ = Zed_utf8.next_error str ofs1 in + if ofs1 < ofs2 then + Buffer.add_substring buf str ofs1 (ofs2 - ofs1); + if ofs2 < len then + loop ofs2 + else + Buffer.contents buf + else + Buffer.contents buf + in + loop ofs + end end diff --git a/test/test_lib.ml b/test/test_lib.ml index 8f6bbe2..a940a58 100644 --- a/test/test_lib.ml +++ b/test/test_lib.ml @@ -7,6 +7,7 @@ let test_fix_string = in ( "fix_string" , [ test ~name:"small" "x" ~expected:"x" + ; test ~name:"empty" "" ~expected:"" ] )