summaryrefslogtreecommitdiff
path: root/hash.c
blob: e4bd7c286d55ad2d4f449fb19245d39fc6c594b1 (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
#include "internal.h"

//
// hash functions (djb2)
// (see http://aras-p.info/blog/2016/08/02/Hash-Functions-all-the-way-down/)
//

uint32_t
fhp_hash_init(void) {
  return 5381;
}

uint32_t
fhp_hash_push(uint32_t hash, uint8_t * const buf, size_t len) {
  for (size_t i = 0; i < len; i++)
    hash = ((hash << 5) + hash) + buf[i];

  return hash;
}

uint32_t
fhp_hash_string(char * const str) {
  uint32_t r = fhp_hash_init();
  return fhp_hash_push(r, (uint8_t*) str, strlen(str));
}

uint32_t
fhp_lc_hash_push(
  uint32_t hash,
  uint8_t * const buf,
  size_t len
) {
  for (size_t i = 0; i < len; i++) {
    uint8_t c = buf[i];

    if ((c >= 'A') && (c <= 'Z'))
      c = (c - 'A') + 'a';

    hash = ((hash << 5) + hash) + c;
  }

  return hash;
}

uint32_t
fhp_lc_hash_string(char * const str) {
  uint32_t r = fhp_hash_init();
  return fhp_lc_hash_push(r, (uint8_t*) str, strlen(str));
}