Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

String hash function

  • Loading branch information...
commit 01803d6568fabab04778e92bd6bb3f2591902dee 1 parent 97de032
Ryan Tenney authored May 01, 2010

Showing 1 changed file with 40 additions and 0 deletions. Show diff stats Hide diff stats

  1. 40  string_hash.c
40  string_hash.c
... ...
@@ -0,0 +1,40 @@
  1
+/* http://www.cse.yorku.ca/~oz/hash.html */
  2
+
  3
+#include <string.h>
  4
+#include <stdlib.h>
  5
+#include <stdio.h>
  6
+
  7
+#define PER_LOOP (8)
  8
+
  9
+// macro HASH_SDBM is the equivalent of
  10
+//   hash(i) = hash(i - 1) * 65599 + str[i];
  11
+#define HASH_INIT (0)
  12
+#define HASH_SDBM(h) (h << 6) + (h << 16) - h
  13
+
  14
+// macro HASH_DJB2M is the equivalent of
  15
+//   hash(i) = hash(i - 1) * 33 + str[i];
  16
+//#define HASH_INIT (5381)
  17
+//#define HASH_DJB2(h) ((h << 5) + h)
  18
+
  19
+#define HASH_STEP(h, s) h = *s++ + HASH_SDBM(h);
  20
+
  21
+// loop unwound version using a duff device
  22
+extern unsigned long string_hash(register unsigned char *s, const size_t l)
  23
+{
  24
+	register unsigned long h = HASH_INIT;                    // hash
  25
+	register unsigned int n = (l + PER_LOOP - 1) / PER_LOOP; // n
  26
+
  27
+	switch (l % PER_LOOP) {
  28
+		case 0: do { HASH_STEP(h, s)
  29
+		case 7:      HASH_STEP(h, s)
  30
+		case 6:      HASH_STEP(h, s)
  31
+		case 5:      HASH_STEP(h, s)
  32
+		case 4:      HASH_STEP(h, s)
  33
+		case 3:      HASH_STEP(h, s)
  34
+		case 2:      HASH_STEP(h, s)
  35
+		case 1:      HASH_STEP(h, s)
  36
+				} while (--n);
  37
+	}
  38
+
  39
+	return h;
  40
+}

0 notes on commit 01803d6

Please sign in to comment.
Something went wrong with that request. Please try again.