From fb3ffa1bb59133a0bf62f5e981d19857fc777828 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Wed, 21 Oct 2015 14:44:20 +0200 Subject: [PATCH] add `CCVector.ensure_with` --- src/core/CCVector.ml | 21 +++++++++++++++------ src/core/CCVector.mli | 9 ++++++++- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/core/CCVector.ml b/src/core/CCVector.ml index 7159faca..3fc6eacf 100644 --- a/src/core/CCVector.ml +++ b/src/core/CCVector.ml @@ -117,13 +117,12 @@ let _grow v x = _resize v size ) -(* resize so that capacity is at least size. Use a doubling-size - strategy so that calling many times [ensure] will +(* v is not empty; ensure it has at least [size] slots. + + Use a doubling-size strategy so that calling many times [ensure] will behave well *) -let ensure v size = - if Array.length v.vec = 0 - then () - else if size > Sys.max_array_length +let ensure_not_empty_ v size = + if size > Sys.max_array_length then failwith "vec.ensure: size too big" else ( let n = ref (max 16 (Array.length v.vec)) in @@ -131,6 +130,16 @@ let ensure v size = _resize v !n ) +let ensure_with ~init v size = + if Array.length v.vec = 0 + then v.vec <- Array.make size init + else ensure_not_empty_ v size + +let ensure v size = + if Array.length v.vec = 0 + then () + else ensure_not_empty_ v size + let clear v = v.size <- 0 diff --git a/src/core/CCVector.mli b/src/core/CCVector.mli index 5febb003..cee9ad08 100644 --- a/src/core/CCVector.mli +++ b/src/core/CCVector.mli @@ -72,9 +72,16 @@ val init : int -> (int -> 'a) -> ('a, 'mut) t val clear : ('a, rw) t -> unit (** clear the content of the vector *) +val ensure_with : init:'a -> ('a, rw) t -> int -> unit +(** Hint to the vector that it should have at least the given capacity. + @param init if [capacity v = 0], used as a filler + element for the underlying array (see {!create_with}) + @since NEXT_RELEASE *) + val ensure : ('a, rw) t -> int -> unit (** Hint to the vector that it should have at least the given capacity. - Just a hint, will not be enforced if the vector is empty. *) + Just a hint, will not be enforced if the vector is empty and [init] + is not provided. *) val is_empty : ('a, _) t -> bool (** is the vector empty? *)