util: Hash: avoid using bytes.Buffer and binary.Read to reduce allocations (fixes #141)
diff --git a/leveldb/util/hash.go b/leveldb/util/hash.go
index 5490366..7f3fa4e 100644
--- a/leveldb/util/hash.go
+++ b/leveldb/util/hash.go
@@ -7,38 +7,38 @@
 package util
 
 import (
-	"bytes"
 	"encoding/binary"
 )
 
 // Hash return hash of the given data.
 func Hash(data []byte, seed uint32) uint32 {
 	// Similar to murmur hash
-	var m uint32 = 0xc6a4a793
-	var r uint32 = 24
-	h := seed ^ (uint32(len(data)) * m)
+	const (
+		m = uint32(0xc6a4a793)
+		r = uint32(24)
+	)
+	var (
+		h = seed ^ (uint32(len(data)) * m)
+		i int
+	)
 
-	buf := bytes.NewBuffer(data)
-	for buf.Len() >= 4 {
-		var w uint32
-		binary.Read(buf, binary.LittleEndian, &w)
-		h += w
+	for n := len(data) - len(data)%4; i < n; i += 4 {
+		h += binary.LittleEndian.Uint32(data[i:])
 		h *= m
 		h ^= (h >> 16)
 	}
 
-	rest := buf.Bytes()
-	switch len(rest) {
+	switch len(data) - i {
 	default:
 		panic("not reached")
 	case 3:
-		h += uint32(rest[2]) << 16
+		h += uint32(data[i+2]) << 16
 		fallthrough
 	case 2:
-		h += uint32(rest[1]) << 8
+		h += uint32(data[i+1]) << 8
 		fallthrough
 	case 1:
-		h += uint32(rest[0])
+		h += uint32(data[i])
 		h *= m
 		h ^= (h >> r)
 	case 0:
diff --git a/leveldb/util/hash_test.go b/leveldb/util/hash_test.go
new file mode 100644
index 0000000..a35d273
--- /dev/null
+++ b/leveldb/util/hash_test.go
@@ -0,0 +1,46 @@
+// Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>
+// All rights reserved.
+//
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package util
+
+import (
+	"testing"
+)
+
+var hashTests = []struct {
+	data []byte
+	seed uint32
+	hash uint32
+}{
+	{nil, 0xbc9f1d34, 0xbc9f1d34},
+	{[]byte{0x62}, 0xbc9f1d34, 0xef1345c4},
+	{[]byte{0xc3, 0x97}, 0xbc9f1d34, 0x5b663814},
+	{[]byte{0xe2, 0x99, 0xa5}, 0xbc9f1d34, 0x323c078f},
+	{[]byte{0xe1, 0x80, 0xb9, 0x32}, 0xbc9f1d34, 0xed21633a},
+	{[]byte{
+		0x01, 0xc0, 0x00, 0x00,
+		0x00, 0x00, 0x00, 0x00,
+		0x00, 0x00, 0x00, 0x00,
+		0x00, 0x00, 0x00, 0x00,
+		0x14, 0x00, 0x00, 0x00,
+		0x00, 0x00, 0x04, 0x00,
+		0x00, 0x00, 0x00, 0x14,
+		0x00, 0x00, 0x00, 0x18,
+		0x28, 0x00, 0x00, 0x00,
+		0x00, 0x00, 0x00, 0x00,
+		0x02, 0x00, 0x00, 0x00,
+		0x00, 0x00, 0x00, 0x00,
+	}, 0x12345678, 0xf333dabb},
+}
+
+func TestHash(t *testing.T) {
+	for i, x := range hashTests {
+		h := Hash(x.data, x.seed)
+		if h != x.hash {
+			t.Fatalf("test-%d: invalid hash, %#x vs %#x", i, h, x.hash)
+		}
+	}
+}