Skip to content

Commit

Permalink
produce: adds a hashCode implementation for #25.
Browse files Browse the repository at this point in the history
  • Loading branch information
fgeller committed Jun 13, 2016
1 parent fbf140c commit cf47b47
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
23 changes: 23 additions & 0 deletions produce.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
40 changes: 40 additions & 0 deletions produce_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down

0 comments on commit cf47b47

Please sign in to comment.