support for unbounded ring buffer

This commit is contained in:
carm 2015-02-13 19:21:46 -05:00
parent 4a994cff38
commit 2cf485ebee
2 changed files with 14 additions and 8 deletions

View file

@ -26,16 +26,16 @@ type 'a t = {
mutable start : int; mutable start : int;
mutable stop : int; (* excluded *) mutable stop : int; (* excluded *)
mutable buf : 'a array; mutable buf : 'a array;
size: int max_capacity: int
} }
exception Empty exception Empty
let create size = let create ?(max_capacity=max_int) () =
{ start=0; { start=0;
stop=0; stop=0;
size; max_capacity;
buf = Array.of_list []; buf = Array.of_list []
} }
let copy b = let copy b =
@ -44,6 +44,8 @@ let copy b =
let capacity b = Array.length b.buf let capacity b = Array.length b.buf
let max_capacity b = b.max_capacity
let length b = let length b =
if b.stop >= b.start if b.stop >= b.start
then b.stop - b.start then b.stop - b.start
@ -73,7 +75,7 @@ let blit_from b from_buf o len =
let cap = capacity b - length b in let cap = capacity b - length b in
(* resize if needed, with a constant to amortize *) (* resize if needed, with a constant to amortize *)
if cap < len then if cap < len then
resize b (min (b.size+1) (Array.length b.buf + len + 24)) from_buf.(0); resize b (min (b.max_capacity+1) (Array.length b.buf + len + 24)) from_buf.(0);
let sub = Array.sub from_buf o len in let sub = Array.sub from_buf o len in
let iter x = let iter x =
if b.start = 0 then b.start <- capacity b - 1 else b.start <- b.start - 1; if b.start = 0 then b.start <- capacity b - 1 else b.start <- b.start - 1;

View file

@ -24,13 +24,14 @@ type 'a t = private {
mutable start : int; mutable start : int;
mutable stop : int; (* excluded *) mutable stop : int; (* excluded *)
mutable buf : 'a array; mutable buf : 'a array;
size : int max_capacity : int
} }
exception Empty exception Empty
val create : int -> 'a t val create : ?max_capacity:int -> unit -> 'a t
(** [create size] creates a new buffer with given size *) (** [create ~max_capacity ()] creates a new buffer with given maximum capacity.
Defaults to unbounded. *)
val copy : 'a t ->'a t val copy : 'a t ->'a t
(** fresh copy of the buffer *) (** fresh copy of the buffer *)
@ -38,6 +39,9 @@ val copy : 'a t ->'a t
val capacity : 'a t -> int val capacity : 'a t -> int
(** length of the inner buffer *) (** length of the inner buffer *)
val max_capacity : 'a t -> int
(** maximum length of the inner buffer *)
val length : 'a t -> int val length : 'a t -> int
(** number of elements currently stored in the buffer *) (** number of elements currently stored in the buffer *)