7df27ae1fc6ebe672b5c531abf28177a55156a64
[gnulib.git] / lib / hash-pjw.c
1 /* hash-pjw.c -- compute a hash value from a NUL-terminated string.
2
3    Copyright (C) 2001, 2003, 2006, 2009-2011 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 #include <config.h>
19
20 #include "hash-pjw.h"
21
22 #include <limits.h>
23
24 #define SIZE_BITS (sizeof (size_t) * CHAR_BIT)
25
26 /* The attribute __pure__ was added in gcc 2.96.  */
27 #undef _GL_ATTRIBUTE_PURE
28 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
29 # define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
30 #else
31 # define _GL_ATTRIBUTE_PURE /* empty */
32 #endif
33
34 /* A hash function for NUL-terminated char* strings using
35    the method described by Bruno Haible.
36    See http://www.haible.de/bruno/hashfunc.html.  */
37
38 size_t _GL_ATTRIBUTE_PURE
39 hash_pjw (const void *x, size_t tablesize)
40 {
41   const char *s;
42   size_t h = 0;
43
44   for (s = x; *s; s++)
45     h = *s + ((h << 9) | (h >> (SIZE_BITS - 9)));
46
47   return h % tablesize;
48 }