From 47abc78a519bad7abdd3d64d15a23f964e0b4e04 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Wed, 29 Mar 2017 17:26:31 +0200 Subject: [PATCH] add `CCString.Sub.get` --- src/core/CCString.cppo.ml | 4 ++++ src/core/CCString.mli | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/core/CCString.cppo.ml b/src/core/CCString.cppo.ml index cbf78bc5..1f88b308 100644 --- a/src/core/CCString.cppo.ml +++ b/src/core/CCString.cppo.ml @@ -748,6 +748,10 @@ module Sub = struct let length (_,_,l) = l + let get (s,i,l) j = + if j<0 || j>= l then invalid_arg "CCString.Sub.get"; + String.unsafe_get s (i+j) + let blit (a1,i1,len1) o1 a2 o2 len = if o1+len>len1 then invalid_arg "CCString.Sub.blit"; blit a1 (i1+o1) a2 o2 len diff --git a/src/core/CCString.mli b/src/core/CCString.mli index 184862cf..137e6b10 100644 --- a/src/core/CCString.mli +++ b/src/core/CCString.mli @@ -574,6 +574,11 @@ module Sub : sig val sub : t -> int -> int -> t (** Sub-slice *) + val get : t -> int -> char + (** [get s i] gets the [i]-th element, or fails + @raise Invalid_argument if the index is not within [0... length -1] + @since NEXT_RELEASE *) + include S with type t := t (*$T @@ -587,4 +592,23 @@ module Sub : sig let sub = Sub.make " abc " 1 ~len:3 in \ "\"abc\"" = (CCFormat.to_string Sub.print sub) *) + + (*$= & ~printer:(String.make 1) + 'b' Sub.(get (make "abc" 1 ~len:2) 0) + 'c' Sub.(get (make "abc" 1 ~len:2) 1) + *) + + (*$QR + Q.(printable_string_of_size Gen.(3--10)) (fun s -> + let open Sequence.Infix in + begin + (0 -- (length s-2) + >|= fun i -> i, Sub.make s i ~len:(length s-i)) + >>= fun (i,sub) -> + (0 -- (Sub.length sub-1) >|= fun j -> i,j,sub) + end + |> Sequence.for_all + (fun (i,j,sub) -> Sub.get sub j = s.[i+j])) + *) + end