From 4c998bf57ad1cb4ee5a7eb247f3aa1672b7418fe Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Fri, 20 May 2016 11:32:27 +0200 Subject: [PATCH] add `CCArray.get_safe` (close #70) --- src/core/CCArray.ml | 37 +++++++++++++++++++++++++++++++++++++ src/core/CCArray.mli | 4 ++++ 2 files changed, 41 insertions(+) diff --git a/src/core/CCArray.ml b/src/core/CCArray.ml index 848952a6..a5496aef 100644 --- a/src/core/CCArray.ml +++ b/src/core/CCArray.ml @@ -22,6 +22,10 @@ module type S = sig val get : 'a t -> int -> 'a + val get_safe : 'a t -> int -> 'a option + (** [get_safe a i] returns [Some a.(i)] if [i] is a valid index + @since NEXT_RELEASE *) + val set : 'a t -> int -> 'a -> unit val length : _ t -> int @@ -291,6 +295,21 @@ let length = Array.length let get = Array.get +let get_safe a i = + if i>=0 && i=a.j then invalid_arg "Array.Sub.get"; a.arr.(j) + let get_safe a i = + try Some (get a i) + with Invalid_argument _ -> None + + (*$inject + let sub_a = Sub.make [|1;2;3;4;5|] 1 ~len:3 + *) + + (*$= + (Some 2) (Sub.get_safe sub_a 0) + (Some 3) (Sub.get_safe sub_a 1) + (Some 4) (Sub.get_safe sub_a 2) + None (Sub.get_safe sub_a 4) + None (Sub.get_safe sub_a max_int) + None (Sub.get_safe sub_a ~-1) + None (Sub.get_safe sub_a ~-42) + *) + let set a i x = let j = a.i + i in if i<0 || j>=a.j then invalid_arg "Array.Sub.set"; diff --git a/src/core/CCArray.mli b/src/core/CCArray.mli index 29157eb7..b8b83b84 100644 --- a/src/core/CCArray.mli +++ b/src/core/CCArray.mli @@ -24,6 +24,10 @@ module type S = sig val get : 'a t -> int -> 'a + val get_safe : 'a t -> int -> 'a option + (** [get_safe a i] returns [Some a.(i)] if [i] is a valid index + @since NEXT_RELEASE *) + val set : 'a t -> int -> 'a -> unit val length : _ t -> int