add CCVector.return; refactoring

This commit is contained in:
Simon Cruanes 2015-10-21 14:43:13 +02:00
parent 799089659a
commit 2c39b63945
2 changed files with 18 additions and 4 deletions

View file

@ -68,6 +68,16 @@ let create_with ?(capacity=128) x = {
(create_with ~capacity:200 1 |> capacity) >= 200 (create_with ~capacity:200 1 |> capacity) >= 200
*) *)
let return x = {
size=1;
vec= [| x |];
}
(*$T
return 42 |> to_list = [42]
return 42 |> length = 1
*)
let make n x = { let make n x = {
size=n; size=n;
vec=Array.make n x; vec=Array.make n x;
@ -134,14 +144,14 @@ let clear v =
let is_empty v = v.size = 0 let is_empty v = v.size = 0
let push_unsafe v x = let push_unsafe_ v x =
Array.unsafe_set v.vec v.size x; Array.unsafe_set v.vec v.size x;
v.size <- v.size + 1 v.size <- v.size + 1
let push v x = let push v x =
if v.size = Array.length v.vec if v.size = Array.length v.vec
then _grow v x; then _grow v x;
push_unsafe v x push_unsafe_ v x
(** add all elements of b to a *) (** add all elements of b to a *)
let append a b = let append a b =
@ -410,7 +420,7 @@ let filter p v =
else ( else (
let v' = create_with ~capacity:v.size v.vec.(0) in let v' = create_with ~capacity:v.size v.vec.(0) in
Array.iter Array.iter
(fun x -> if p x then push_unsafe v' x) (fun x -> if p x then push_unsafe_ v' x)
v.vec; v.vec;
v' v'
) )
@ -598,7 +608,7 @@ let of_list l = match l with
| [] -> create() | [] -> create()
| x::_ -> | x::_ ->
let v = create_with ~capacity:(List.length l + 5) x in let v = create_with ~capacity:(List.length l + 5) x in
List.iter (push_unsafe v) l; List.iter (push_unsafe_ v) l;
v v
(*$T (*$T

View file

@ -59,6 +59,10 @@ val create_with : ?capacity:int -> 'a -> ('a, rw) t
@param capacity the size of the underlying array @param capacity the size of the underlying array
{b caution}: the value will likely not be GC'd before the vector is. *) {b caution}: the value will likely not be GC'd before the vector is. *)
val return : 'a -> ('a, 'mut) t
(** Singleton vector
@since NEXT_RELEASE *)
val make : int -> 'a -> ('a, 'mut) t val make : int -> 'a -> ('a, 'mut) t
(** [make n x] makes a vector of size [n], filled with [x] *) (** [make n x] makes a vector of size [n], filled with [x] *)