murmurhash.c revision 1.4
11.4Schristos/*	$NetBSD: murmurhash.c,v 1.4 2012/07/10 17:05:38 christos 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.4Schristos__KERNEL_RCSID(0, "$NetBSD: murmurhash.c,v 1.4 2012/07/10 17:05:38 christos Exp $");
181.4Schristos
191.3Srmind#else
201.4Schristos
211.4Schristos#if defined(LIBC_SCCS) && !defined(lint)
221.4Schristos__RCSID("$NetBSD: murmurhash.c,v 1.4 2012/07/10 17:05:38 christos Exp $");
231.4Schristos#endif /* LIBC_SCCS and not lint */
241.4Schristos
251.4Schristos#include "namespace.h"
261.3Srmind#endif
271.3Srmind
281.1Srmind#include <sys/types.h>
291.1Srmind#include <sys/hash.h>
301.1Srmind
311.3Srmind#ifdef __weak_alias
321.3Srmind__weak_alias(murmurhash2,_murmurhash2)
331.1Srmind#endif
341.1Srmind
351.1Srminduint32_t
361.1Srmindmurmurhash2(const void *key, size_t len, uint32_t seed)
371.1Srmind{
381.1Srmind	/*
391.1Srmind	 * Note: 'm' and 'r' are mixing constants generated offline.
401.1Srmind	 * They're not really 'magic', they just happen to work well.
411.1Srmind	 * Initialize the hash to a 'random' value.
421.1Srmind	 */
431.1Srmind	const uint32_t m = 0x5bd1e995;
441.1Srmind	const int r = 24;
451.1Srmind
461.4Schristos	const uint8_t *data = key;
471.2Srmind	uint32_t h = seed ^ (uint32_t)len;
481.1Srmind
491.1Srmind	while (len >= sizeof(uint32_t)) {
501.1Srmind		uint32_t k;
511.1Srmind
521.1Srmind		k  = data[0];
531.1Srmind		k |= data[1] << 8;
541.1Srmind		k |= data[2] << 16;
551.1Srmind		k |= data[3] << 24;
561.1Srmind
571.1Srmind		k *= m;
581.1Srmind		k ^= k >> r;
591.1Srmind		k *= m;
601.1Srmind
611.1Srmind		h *= m;
621.1Srmind		h ^= k;
631.1Srmind
641.1Srmind		data += sizeof(uint32_t);
651.1Srmind		len -= sizeof(uint32_t);
661.1Srmind	}
671.1Srmind
681.1Srmind	/* Handle the last few bytes of the input array. */
691.1Srmind	switch (len) {
701.1Srmind	case 3:
711.1Srmind		h ^= data[2] << 16;
721.2Srmind		/* FALLTHROUGH */
731.1Srmind	case 2:
741.1Srmind		h ^= data[1] << 8;
751.2Srmind		/* FALLTHROUGH */
761.1Srmind	case 1:
771.1Srmind		h ^= data[0];
781.1Srmind		h *= m;
791.1Srmind	}
801.1Srmind
811.1Srmind	/*
821.1Srmind	 * Do a few final mixes of the hash to ensure the last few
831.1Srmind	 * bytes are well-incorporated.
841.1Srmind	 */
851.1Srmind	h ^= h >> 13;
861.1Srmind	h *= m;
871.1Srmind	h ^= h >> 15;
881.1Srmind
891.1Srmind	return h;
901.1Srmind}
91