summaryrefslogtreecommitdiffstats
path: root/hivex/tools/counter.ml
blob: 2e44c6532194b9425afc0025823e9296af1c1c04 (plain)
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
82
83
84
85
86
(* Basic counting module.

   Copyright (C) 2006 Merjis Ltd.

   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 2 of the License, or (at your option) any later version.

   This library 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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)

type 'a t = ('a, int ref) Hashtbl.t

let create () =
  Hashtbl.create 13

let get_ref counter thing =
  try
    Hashtbl.find counter thing
  with
    Not_found ->
      let r = ref 0 in
      Hashtbl.add counter thing r;
      r

let incr counter thing =
  let r = get_ref counter thing in
  incr r

let decr counter thing =
  let r = get_ref counter thing in
  decr r

let add counter thing n =
  let r = get_ref counter thing in
  r := !r + n

let sub counter thing n =
  let r = get_ref counter thing in
  r := !r - n

let set counter thing n =
  let r = get_ref counter thing in
  r := n

(* Don't use get_ref, to avoid unnecessarily creating 'ref 0's. *)
let get counter thing =
  try
    !(Hashtbl.find counter thing)
  with
    Not_found -> 0

(* This is a common pair of operations, worth optimising. *)
let incr_get counter thing =
  let r = get_ref counter thing in
  Pervasives.incr r;
  !r

let zero = Hashtbl.remove

let read counter =
  let counts =
    Hashtbl.fold (
      fun thing r xs ->
	let r = !r in
	if r <> 0 then (r, thing) :: xs
	else xs
    ) counter [] in
  List.sort (fun (a, _) (b, _) -> compare (b : int) (a : int)) counts

let length = Hashtbl.length

let total counter =
  let total = ref 0 in
  Hashtbl.iter (fun _ r -> total := !total + !r) counter;
  !total

let clear = Hashtbl.clear