refactor a bit
[platform/upstream/libsolv.git] / src / hash.h
1 /*
2  * Copyright (c) 2007, Novell Inc.
3  *
4  * This program is licensed under the BSD license, read LICENSE.BSD
5  * for further information
6  */
7
8 /*
9  * hash.h
10  * generic hash functions
11  */
12
13 #ifndef LIBSOLV_HASH_H
14 #define LIBSOLV_HASH_H
15
16 #include "pooltypes.h"
17
18 #ifdef __cplusplus
19 extern "C" {
20 #endif
21
22 /* value of a hash */
23 typedef unsigned int Hashval;
24 /* mask for hash, used as modulo operator to ensure 'wrapping' of hash
25    values -> hash table */
26 typedef unsigned int Hashmask;
27
28 /* inside the hash table, Ids are stored. Hash maps: string -> hash -> Id */
29 typedef Id *Hashtable;
30
31 /* hash chain */
32 #define HASHCHAIN_START 7
33 #define HASHCHAIN_NEXT(h, hh, mask) (((h) + (hh)++) & (mask))
34
35 /* very simple hash function
36  * string -> hash
37  */
38 static inline Hashval
39 strhash(const char *str)
40 {
41   Hashval r = 0;
42   unsigned int c;
43   while ((c = *(const unsigned char *)str++) != 0)
44     r += (r << 3) + c;
45   return r;
46 }
47
48 static inline Hashval
49 strnhash(const char *str, unsigned len)
50 {
51   Hashval r = 0;
52   unsigned int c;
53   while (len-- && (c = *(const unsigned char *)str++) != 0)
54     r += (r << 3) + c;
55   return r;
56 }
57
58 static inline Hashval
59 strhash_cont(const char *str, Hashval r)
60 {
61   unsigned int c;
62   while ((c = *(const unsigned char *)str++) != 0)
63     r += (r << 3) + c;
64   return r;
65 }
66
67
68 /* hash for rel
69  * rel -> hash
70  */
71 static inline Hashval
72 relhash(Id name, Id evr, int flags)
73 {
74   return name + 7 * evr + 13 * flags;
75 }
76
77
78 /* compute bitmask for value
79  * returns smallest (2^n-1) > 2 * num
80  * 
81  * used for Hashtable 'modulo' operation
82  */ 
83 static inline Hashmask
84 mkmask(unsigned int num)
85 {
86   num *= 2;
87   while (num & (num - 1))
88     num &= num - 1;
89   return num * 2 - 1;
90 }
91
92 #ifdef __cplusplus
93 }
94 #endif
95
96 #endif /* LIBSOLV_HASH_H */