strings.ml 2.49 KB
Newer Older
1 2 3
(********************************************************************)
(*                                                                  *)
(*  The Why3 Verification Platform   /   The Why3 Development Team  *)
4
(*  Copyright 2010-2015   --   INRIA - CNRS - Paris-Sud University  *)
5 6 7 8
(*                                                                  *)
(*  This software is distributed under the terms of the GNU Lesser  *)
(*  General Public License version 2.1, with the special exception  *)
(*  on linking described in file LICENSE.                           *)
9
(*                                                                  *)
10 11
(********************************************************************)

12 13 14 15 16 17

let create = String.create
let copy = String.copy
let set = String.set


18
let rev_split c s =
19 20 21
  let rec aux acc i =
    try
      let j = String.index_from s i c in
22
      aux (String.sub s i (j-i) :: acc) (j + 1)
23 24 25 26
    with Not_found -> (String.sub s i (String.length s - i))::acc
      | Invalid_argument _ -> ""::acc in
  aux [] 0

27
let split c s = List.rev (rev_split c s)
28

29 30
let rev_bounded_split c s n =
  let rec aux acc i n =
31 32
    let get_rest_of_s i = (String.sub s i (String.length s - i)) in
    if n = 1 then get_rest_of_s i :: acc else
33 34
    try
      let j = String.index_from s i c in
35 36
      aux (String.sub s i (j-i) :: acc) (j+1) (n-1)
    with Not_found -> get_rest_of_s i :: acc
37 38 39 40 41
      | Invalid_argument _ -> ""::acc in
  aux [] 0 n

let bounded_split c s n = List.rev (rev_bounded_split c s n)

42 43 44 45 46 47
let rec join sep l =
  match l with
  | [] -> ""
  | [x] -> x
  | x :: rest -> x ^ sep ^ join sep rest

48 49 50 51 52 53 54 55 56 57 58
let ends_with s suf =
  let rec aux s suf suflen offset i =
    i >= suflen || (s.[i + offset] = suf.[i]
                   && aux s suf suflen offset (i+1)) in
  let slen = String.length s in
  let suflen = String.length suf in
  slen >= suflen && aux s suf suflen (slen - suflen) 0

let pad_right c s i =
  let sl = String.length s in
  if sl < i then
59
    let p = create i in
60 61 62 63 64 65
    String.blit s 0 p 0 sl;
    String.fill p sl (i-sl) c;
    p
  else if sl > i
  then String.sub s 0 i
  else s
66 67 68 69 70 71 72 73 74 75 76 77 78 79

let has_prefix pref s =
  let l = String.length pref in
  if String.length s < l then false else
    try
      for i = 0 to l - 1 do if s.[i] <> pref.[i] then raise Exit done;
      true
    with Exit -> false

let remove_prefix pref s =
  let l = String.length pref in
  if String.length s < l then raise Not_found else
  for i = 0 to l - 1 do if s.[i] <> pref.[i] then raise Not_found done;
  String.sub s l (String.length s - l)