Skip to content
This repository
tag: v948
Fetching contributors…

Cannot retrieve contributors at this time

file 81 lines (62 sloc) 1.941 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
(*
Copyright © 2011 MLstate

This file is part of OPA.

OPA is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.

OPA is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.

You should have received a copy of the GNU Affero General Public License
along with OPA. If not, see <http://www.gnu.org/licenses/>.
*)
(* http://remi.vanicat.free.fr/ocaml/hweak/ *)
(* Perhaps we can replace this module by (modified?) above hweak
implementation... ? *)

module type WeakedType = sig
  type t
  val compare : t -> t -> int
  val hash : t -> int
end

module Make (HK : Hashtbl.HashedType)(HD : WeakedType) = struct
  module WS = Weak.Make
    (struct
       include HD
       let equal a b = HD.compare a b = 0
     end)

  module HT = Hashtbl.Make(HK)

  type key = HK.t

  module S = Set.Make(HD)

  type t = {
    htbl : HD.t HT.t;
    wset : WS.t;
    mutable strong : S.t;
  }

  let create i = {
    htbl = HT.create i;
    wset = WS.create i;
    strong = S.empty;
  }

  let remove t k =
    try
      let v = HT.find t.htbl k in
      WS.remove t.wset v;
      HT.remove t.htbl k;
      t.strong <- S.remove v t.strong
    with Not_found -> ()

  let add t k v =
    let vcopy = Obj.obj (Obj.dup (Obj.repr v)) in
    HT.add t.htbl k vcopy;
    WS.add t.wset v;
    Gc.finalise (fun _ -> HT.remove t.htbl (k:HK.t)) v

  let mem t k = (HT.mem t.htbl k)

  let find t k = WS.find t.wset (HT.find t.htbl k)

  let strong t k v =
    if not (mem t k) then add t k v;
    t.strong <- S.add v t.strong

  let relax t k =
    t.strong <- S.remove (find t k) t.strong

  let size t =
    HT.length t.htbl

end
Something went wrong with that request. Please try again.