19 #define HASH_TABLE_SIZE 10240 /* 10k */
20 #define NAME_LENGTH 17 /* bytes */
22 static struct ohtbl htable
;
24 static inline unsigned int tdb_hash(char *name
)
26 unsigned value
; /* Used to compute the hash value. */
27 unsigned i
; /* Used to cycle through random values. */
29 /* Set the initial value from the key size. */
30 for (value
= 0x238F13AF * strlen(name
), i
=0; name
[i
]; i
++)
31 value
= (value
+ (((unsigned char *)name
)[i
] << (i
*5 % 24)));
33 return (1103515243 * value
+ 12345);
36 static int ohtbl_init(void)
39 const int positions
= HASH_TABLE_SIZE
;
41 htable
.table
= malloc(sizeof(void *) * positions
);
45 for (i
= 0; i
< positions
; i
++)
46 htable
.table
[i
] = NULL
;
48 htable
.positions
= positions
;
49 htable
.gr_collision
= -1;
50 htable
.size
= htable
.nr_collisions
= htable
.no_collisions
= 0;
55 static void ohtbl_destroy(void)
59 for (i
= 0; i
< htable
.positions
; i
++)
61 free(htable
.table
[i
]);
66 static int ohtbl_lookup(char *name
, unsigned int *h
)
71 hash
= tdb_hash(name
) % htable
.positions
;
73 for (i
= 0; i
< htable
.positions
; i
++) {
74 if (htable
.table
[hash
])
75 if (!memcmp(htable
.table
[hash
], name
, NAME_LENGTH
)) {
82 hash
= (hash
+ 1) % htable
.positions
;
89 static int ohtbl_insert(char *name
)
94 ret
= ohtbl_lookup(name
, NULL
);
96 /* key already exists */
100 hash
= tdb_hash(name
) % htable
.positions
;
102 for (i
= 0; i
< htable
.positions
; i
++) {
103 if (!htable
.table
[hash
]) {
104 htable
.table
[hash
] = (void *) name
;
108 htable
.no_collisions
++;
109 else if (i
> htable
.gr_collision
)
110 htable
.gr_collision
= i
;
115 htable
.nr_collisions
++;
116 hash
= (hash
+ 1) % htable
.positions
;
123 static void ohtbl_stats(void)
125 float lfactor
, probes
;
126 struct ohtbl
*p
= &htable
;
128 lfactor
= (float) p
->size
/ p
->positions
;
129 probes
= 1 / (1 - lfactor
);
131 printf("\n-> Hash table statistics\n");
132 printf("Table size: %4d\n", p
->positions
);
133 printf(" o free: %4d\n", p
->positions
- p
->size
);
134 printf(" o in use: %4d\n", p
->size
);
135 printf("Perfect hashing: %4d\n", p
->no_collisions
);
136 printf("Collisions: %4d\n", p
->nr_collisions
);
137 printf(" o nr keys: %4d\n", p
->size
- p
->no_collisions
);
138 printf(" o greater: %4d\n", p
->gr_collision
+ 1);
139 printf("Load factor: %4.2f\n", lfactor
);
140 printf("P. to probe: %4.2f\n\n", probes
);
143 struct module lp_module
= {
144 .mod_name
= "Linear Probing hashing",
145 .mod_init
= ohtbl_init
,
146 .mod_insert
= ohtbl_insert
,
147 .mod_lookup
= ohtbl_lookup
,
148 .mod_destroy
= ohtbl_destroy
,
149 .mod_stats
= ohtbl_stats
,