Commit 834caddc authored by POTTIER Francois's avatar POTTIER Francois

Added the module [ResizableArray]. Untested. For now, in the attic.

parent e2177ee0
(* This module implements resizable arrays, that is, arrays that can
grow upon explicit request. *)
type 'a t = {
(* The default element is used to fill empty slots. *)
default: 'a;
(* The logical size of this array. *)
mutable size: int;
(* The physical array, whose length is at least [size]. *)
mutable table: 'a array
}
let make capacity default =
(* [capacity] must be nonzero, so that doubling it actually
enlarges the array. *)
assert (capacity >= 0);
let capacity = if capacity = 0 then 1 else capacity in
let table = Array.make capacity default in
{ default; size = 0; table }
let length a =
a.size
let get a i =
assert (0 <= i && i < a.size);
a.table.(i)
let set a i x =
assert (0 <= i && i < a.size);
a.table.(i) <- x
let resize a s =
assert (s >= 0);
if s < a.size then begin
(* The logical size of the array decreases. *)
Array.fill a.table s (a.size - s) a.default;
a.size <- s
end
else if s > a.size then begin
(* The logical size of the array increases. *)
let n = Array.length a.table in
if s > n then begin
(* The physical size of the array must increase. The new size is at
least double of the previous size, and larger if requested. *)
let table = Array.make (max (2 * n) s) a.default in
Array.blit a.table 0 table 0 n;
a.table <- table
end;
a.size <- s
end
(* This module implements resizable arrays, that is, arrays that can
grow upon explicit request. *)
type 'a t
(* [make capacity x] creates a resizable array of logical length 0, whose
physical length is initially [capacity], and whose default element is [x].
The default element is used to fill empty slots in the physical array. *)
val make: int -> 'a -> 'a t
(* [length a] returns the current logical length of the array [a]. *)
val length: 'a t -> int
(* [resize a n] changes the logical length of the array [a] to [n]. If the
length decreases, any excess elements are lost. The capacity of the
underlying physical array remains the same. If the length increases, the
new positions are filled with the array's default element, as initially
supplied to [make]. The capacity of the underlying physical array grows
by at least a factor of two. *)
val resize: 'a t -> int -> unit
(* [get a i] returns the element contained at offset [i] in the array [a].
Slots are numbered 0 and up. [i] must be strictly less than the array's
current logical length. *)
val get: 'a t -> int -> 'a
(* [set a i x] sets the element contained at offset [i] in the array [a]
to [x]. Slots are numbered 0 and up. [i] must be strictly less than
the array's current logical length. *)
val set: 'a t -> int -> 'a -> unit
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment