murmurhash.c revision 1.3
11.3Srmind/*	$NetBSD: murmurhash.c,v 1.3 2012/07/09 21:25:46 rmind Exp $	*/
21.1Srmind
31.1Srmind/*
41.1Srmind * MurmurHash2 -- from the original code:
51.1Srmind *
61.1Srmind * "MurmurHash2 was written by Austin Appleby, and is placed in the public
71.1Srmind * domain. The author hereby disclaims copyright to this source code."
81.1Srmind *
91.1Srmind * References:
101.1Srmind *	http://code.google.com/p/smhasher/
111.1Srmind *	https://sites.google.com/site/murmurhash/
121.1Srmind */
131.1Srmind
141.1Srmind#include <sys/cdefs.h>
151.3Srmind
161.3Srmind#if defined(_KERNEL) || defined(_STANDALONE)
171.3Srmind__KERNEL_RCSID(0, "$NetBSD: murmurhash.c,v 1.3 2012/07/09 21:25:46 rmind Exp $");
181.3Srmind#else
191.3Srmind__RCSID("$NetBSD: murmurhash.c,v 1.3 2012/07/09 21:25:46 rmind Exp $");
201.3Srmind#endif
211.3Srmind
221.3Srmind#include "namespace.h"
231.1Srmind#include <sys/types.h>
241.1Srmind#include <sys/hash.h>
251.1Srmind
261.3Srmind#ifdef __weak_alias
271.3Srmind__weak_alias(murmurhash2,_murmurhash2)
281.1Srmind#endif
291.1Srmind
301.1Srminduint32_t
311.1Srmindmurmurhash2(const void *key, size_t len, uint32_t seed)
321.1Srmind{
331.1Srmind	/*
341.1Srmind	 * Note: 'm' and 'r' are mixing constants generated offline.
351.1Srmind	 * They're not really 'magic', they just happen to work well.
361.1Srmind	 * Initialize the hash to a 'random' value.
371.1Srmind	 */
381.1Srmind	const uint32_t m = 0x5bd1e995;
391.1Srmind	const int r = 24;
401.1Srmind
411.1Srmind	const uint8_t *data = (const uint8_t *)key;
421.2Srmind	uint32_t h = seed ^ (uint32_t)len;
431.1Srmind
441.1Srmind	while (len >= sizeof(uint32_t)) {
451.1Srmind		uint32_t k;
461.1Srmind
471.1Srmind		k  = data[0];
481.1Srmind		k |= data[1] << 8;
491.1Srmind		k |= data[2] << 16;
501.1Srmind		k |= data[3] << 24;
511.1Srmind
521.1Srmind		k *= m;
531.1Srmind		k ^= k >> r;
541.1Srmind		k *= m;
551.1Srmind
561.1Srmind		h *= m;
571.1Srmind		h ^= k;
581.1Srmind
591.1Srmind		data += sizeof(uint32_t);
601.1Srmind		len -= sizeof(uint32_t);
611.1Srmind	}
621.1Srmind
631.1Srmind	/* Handle the last few bytes of the input array. */
641.1Srmind	switch (len) {
651.1Srmind	case 3:
661.1Srmind		h ^= data[2] << 16;
671.2Srmind		/* FALLTHROUGH */
681.1Srmind	case 2:
691.1Srmind		h ^= data[1] << 8;
701.2Srmind		/* FALLTHROUGH */
711.1Srmind	case 1:
721.1Srmind		h ^= data[0];
731.1Srmind		h *= m;
741.1Srmind	}
751.1Srmind
761.1Srmind	/*
771.1Srmind	 * Do a few final mixes of the hash to ensure the last few
781.1Srmind	 * bytes are well-incorporated.
791.1Srmind	 */
801.1Srmind	h ^= h >> 13;
811.1Srmind	h *= m;
821.1Srmind	h ^= h >> 15;
831.1Srmind
841.1Srmind	return h;
851.1Srmind}
86