p2p, ring: Cleanup PeerId table

This commit is contained in:
Pietro 2018-03-12 13:32:29 +01:00 committed by Grégoire Henry
parent b3df4e63c8
commit 511b47148c
2 changed files with 15 additions and 24 deletions

View File

@ -84,10 +84,10 @@ module type TABLE = sig
type t
type v
val create : int -> t
val clear : t -> unit
val add : t -> v -> unit
val mem : t -> v -> bool
val remove : t -> v -> unit
val clear : t -> unit
val elements : t -> v list
end
@ -99,44 +99,35 @@ module MakeTable (V: Hashtbl.HashedType) = struct
type raw = {
size : int ;
mutable capacity : int ;
ring : V.t Ring.t ;
table : unit Table.t ;
}
type t = raw ref
type v = V.t
let create size = ref {
size;
capacity = 0;
ring = Ring.create size;
table = Table.create size }
let add ({contents = t } as tt) v =
assert (t.capacity <= t.size);
if t.capacity = t.size then begin
try Table.remove t.table (Ring.last_exn t.ring) with Ring.Empty -> assert false
end;
Ring.add t.ring v;
Table.replace t.table v ();
let capacity = if t.capacity = t.size then t.capacity else t.capacity + 1 in
tt := { ring = t.ring ; table = t.table; size = t.size ; capacity = capacity }
let add {contents = t } v =
Table.add t.table v ();
Option.iter
(Ring.add_and_return_erased t.ring v)
~f:(Table.remove t.table)
let mem t v = Table.mem !t.table v
let mem {contents = t} v = Table.mem t.table v
let remove ({contents = t } as tt) v =
Table.remove t.table v;
let capacity = if t.capacity = 0 then t.capacity else t.capacity - 1 in
tt := { ring = t.ring ; table = t.table; size = t.size ; capacity = capacity }
let remove {contents = t} v =
Table.remove t.table v
let clear ({contents = t } as tt) =
let clear ({contents = t} as tt) =
tt := { t with
capacity = 0;
ring = Ring.create t.size;
table = Table.create t.size
}
let elements t = Ring.elements !t.ring
let elements {contents = t} =
Table.fold (fun k _ acc -> k::acc) t.table []
end

View File

@ -52,9 +52,6 @@ module type TABLE = sig
(** [create size] inizialize an empty ring *)
val create : int -> t
(** [retest t] remore all bindings from the current ring *)
val clear : t -> unit
(** [add t v] add a value to the ring. If the ring already contains size elements,
the first element is removed and [v] is added. *)
val add : t -> v -> unit
@ -65,6 +62,9 @@ module type TABLE = sig
(** [remove t v] remove one element from the table *)
val remove : t -> v -> unit
(** [retest t] remore all bindings from the current ring *)
val clear : t -> unit
(** [elements t] return the list of elements currently in the ring *)
val elements : t -> v list