Skip to content

Commit

Permalink
Use efficient String.starts_with implementation
Browse files Browse the repository at this point in the history
The existing implementation for `Compat.String.starts_with` needlessly
makes a copy of the prefix. This patch instead uses the implementation
of `String.starts_with` from recent versions of the OCaml standard
library, which avoids the copy.
  • Loading branch information
bclement-ocp committed Oct 19, 2023
1 parent bfd698d commit 5aed0fb
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/lib/util/compat.ml
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
(* Locally restore the default polymorphic operators of the Stdlib, to make it
easier to copy code from there without modifications. *)
open Stdlib

module String = struct
open Stdlib.String

let starts_with ~prefix s =
length s >= length prefix &&
equal (sub s 0 (length prefix)) prefix
(* Copied from stdlib/string.ml in OCaml 5.0 *)
let len_s = length s
and len_pre = length prefix in
let rec aux i =
if i = len_pre then true
else if unsafe_get s i <> unsafe_get prefix i then false
else aux (i + 1)
in len_s >= len_pre && aux 0

let fold_left f x a =
(* Copied from stdlib/bytes.ml in OCaml 5.0 *)
let r = ref x in
for i = 0 to length a - 1 do
r := f !r (unsafe_get a i)
Expand Down

0 comments on commit 5aed0fb

Please sign in to comment.