From cf47b478d133337444e55c6cf2eca5ef46bc6916 Mon Sep 17 00:00:00 2001 From: Felix Geller Date: Mon, 13 Jun 2016 22:52:54 +1200 Subject: [PATCH] produce: adds a hashCode implementation for #25. --- produce.go | 23 +++++++++++++++++++++++ produce_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/produce.go b/produce.go index 3a0666f..33684b1 100644 --- a/produce.go +++ b/produce.go @@ -430,3 +430,26 @@ func readInput(wg *sync.WaitGroup, signals chan struct{}, stdin chan string, out } } } + +// hashCode imitates the behavior of the JDK's Object#hashCode method. +// https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#hashCode() +// +// TODO: utf16 vs utf8 +func hashCode(s string) int32 { + var hc, c, n int32 + for range s { + n++ + } + + for _, r := range s { + c++ + var p int32 = 1 + for i := c; i < n; i++ { + p *= 31 + } + + hc += r * p + } + + return hc +} diff --git a/produce_test.go b/produce_test.go index 166794f..11df61d 100644 --- a/produce_test.go +++ b/produce_test.go @@ -6,6 +6,46 @@ import ( "testing" ) +func TestHashCode(t *testing.T) { + + data := []struct { + in string + expected int32 + }{ + { + in: "", + expected: 0, + }, + { + in: "a", + expected: 97, + }, + { + in: "b", + expected: 98, + }, + { + in: "⌘", + expected: 8984, + }, + { + in: "hashCode", + expected: 147696667, + }, + { + in: "c03a3475-3ed6-4ed1-8ae5-1c432da43e73", + expected: 1116730239, + }, + } + + for _, d := range data { + actual := hashCode(d.in) + if actual != d.expected { + t.Errorf("expected %v but found %v\n", d.expected, actual) + } + } +} + func TestProduceParseArgs(t *testing.T) { configBefore := config defer func() {