faster CCString.{prefix,suffix}

see https://github.com/ocaml-batteries-team/batteries-included/issues/792
for some discussion
This commit is contained in:
Simon Cruanes 2017-09-12 10:28:00 +02:00
parent 56928a1a15
commit a323809aa0

View file

@ -490,22 +490,28 @@ let repeat s n =
assert(len > 0); assert(len > 0);
init (len * n) (fun i -> s.[i mod len]) init (len * n) (fun i -> s.[i mod len])
exception Exit_false
let prefix ~pre s = let prefix ~pre s =
String.length pre <= String.length s && String.length pre <= String.length s &&
begin try
let i = ref 0 in for i=0 to String.length pre-1 do
while !i < String.length pre && s.[!i] = pre.[!i] do incr i done; if String.unsafe_get s i != String.unsafe_get pre i
!i = String.length pre then raise Exit_false
end done;
true
with Exit_false -> false
let suffix ~suf s = let suffix ~suf s =
String.length suf <= String.length s && String.length suf <= String.length s &&
begin try
let off = String.length s - String.length suf in let off = String.length s - String.length suf in
let i = ref 0 in for i=0 to String.length suf-1 do
while !i < String.length suf && s.[off + !i] = suf.[!i] do incr i done; if String.unsafe_get s (off+i) != String.unsafe_get suf i
!i = String.length suf then raise Exit_false
end done;
true
with Exit_false -> false
let take n s = let take n s =
if n < String.length s if n < String.length s