You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by mm...@apache.org on 2019/05/14 16:33:59 UTC

[pulsar-client-go] 22/38: Added hash functions and tests

This is an automated email from the ASF dual-hosted git repository.

mmerli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pulsar-client-go.git

commit 0ac78681c6337874e250154a6d9ad4431edf0f24
Author: Matteo Merli <mm...@apache.org>
AuthorDate: Fri May 3 17:25:02 2019 -0700

    Added hash functions and tests
---
 pulsar/impl/hash.go      | 19 +++++++++++++++++++
 pulsar/impl/hash_test.go | 40 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 59 insertions(+)

diff --git a/pulsar/impl/hash.go b/pulsar/impl/hash.go
new file mode 100644
index 0000000..bd65da1
--- /dev/null
+++ b/pulsar/impl/hash.go
@@ -0,0 +1,19 @@
+package impl
+
+import "github.com/spaolacci/murmur3"
+
+func JavaStringHash(s string) uint32 {
+	var h uint32
+	for i, size := 0, len(s); i < size; i++ {
+		h = 31*h + uint32(s[i])
+	}
+
+	return h
+}
+
+func Murmur3_32Hash(s string) uint32 {
+	h := murmur3.New32()
+	h.Write([]byte(s))
+	// Maintain compatibility with values used in Java client
+	return h.Sum32() & 0x7fffffff
+}
diff --git a/pulsar/impl/hash_test.go b/pulsar/impl/hash_test.go
new file mode 100644
index 0000000..76b418a
--- /dev/null
+++ b/pulsar/impl/hash_test.go
@@ -0,0 +1,40 @@
+package impl
+
+import (
+	"github.com/stretchr/testify/assert"
+	"testing"
+)
+
+type testProvider struct {
+	str string
+
+	hash uint32
+}
+
+var javaHashValues = []testProvider{
+	{"", 0x0,},
+	{"hello", 0x5e918d2},
+	{"test", 0x364492},
+}
+
+var murmurHashValues = []testProvider{
+	{"", 0x0},
+	{"hello", 0x248bfa47},
+	{"test", 0x3a6bd213},
+}
+
+func TestJavaHash(t *testing.T) {
+	for _, p := range javaHashValues {
+		t.Run(p.str, func(t *testing.T) {
+			assert.Equal(t, p.hash, JavaStringHash(p.str))
+		})
+	}
+}
+
+func TestMurmurHash(t *testing.T) {
+	for _, p := range murmurHashValues {
+		t.Run(p.str, func(t *testing.T) {
+			assert.Equal(t, p.hash, Murmur3_32Hash(p.str))
+		})
+	}
+}