FreeNOS
HashFunction.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2015 Niek Linnenbank
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include "Assert.h"
19 #include "HashFunction.h"
20 
21 Size hash(const String & key, Size mod)
22 {
23  Size ret = FNV_INIT;
24  Size size = key.length();
25 
26  assert(mod > 0);
27 
28  for (Size i = 0; i < size; i++)
29  {
30  ret *= FNV_PRIME;
31  ret ^= key[i];
32  }
33  return (ret % mod);
34 }
35 
36 Size hash(int key, Size mod)
37 {
38  Size ret = FNV_INIT;
39 
40  assert(mod > 0);
41 
42  for (Size i = 0; i < 4; i++)
43  {
44  ret *= FNV_PRIME;
45  ret ^= (((uint) key) >> (i*8)) & 0xff;
46  }
47  return (ret % mod);
48 }
HashFunction.h
String::length
Size length() const
Same as count().
Definition: String.cpp:105
hash
Size hash(const String &key, Size mod)
Compute a hash using the FNV algorithm.
Definition: HashFunction.cpp:21
String
Abstraction of strings.
Definition: String.h:41
Assert.h
FNV_PRIME
#define FNV_PRIME
Prime number used by FNV hashing.
Definition: HashFunction.h:33
uint
unsigned int uint
Unsigned integer number.
Definition: Types.h:44
Size
unsigned int Size
Any sane size indicator cannot go negative.
Definition: Types.h:128
FNV_INIT
#define FNV_INIT
Initial value of the FNV internal state.
Definition: HashFunction.h:36
assert
#define assert(exp)
Insert program diagnostics.
Definition: assert.h:60