(**************************************************************************)
(*                                                                        *)
(*  Copyright (C) 2012 Pietro Abate <pietro.abate@pps.jussieu.fr>         *)
(*                                                                        *)
(*  This library is free software: you can redistribute it and/or modify  *)
(*  it under the terms of the GNU Lesser General Public License as        *)
(*  published by the Free Software Foundation, either version 3 of the    *)
(*  License, or (at your option) any later version.  A special linking    *)
(*  exception to the GNU Lesser General Public License applies to this    *)
(*  library, see the COPYING file for more information.                   *)
(**************************************************************************)

module type UniqueType = sig
  type t
  type v
  val create : v -> t
  val value : t -> v
  val uid : t -> int
end

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

(* This module gives to each value a single id *)
module Make ( S : OrderedType ) : UniqueType with type v = S.t = struct

  module VMap = Map.Make(S)

  type v = S.t
  type t = Hash of (v * int)

  let gentag =
    let r = ref 0 in
    fun () -> incr r; !r

  let cons = ref VMap.empty

  let create v =
    try Hash(v,VMap.find v !cons) with
    Not_found -> begin
      let i = gentag () in
      cons := VMap.add v i !cons;
      Hash (v,i)
    end

  let value = function Hash (v,_) -> v
  let uid = function Hash (_,i) -> i

end
