murmur3_32_test.gno
2.61 Kb · 107 lines
1package murmur3_test
2
3import (
4 "testing"
5
6 "gno.land/p/jeronimoalbi/murmur3"
7)
8
9func TestHash32Sum32(t *testing.T) {
10 // Test cases -> https://en.wikipedia.org/wiki/MurmurHash#Algorithm
11 tests := []struct {
12 name string
13 data string
14 seed uint32
15 want uint32
16 }{
17 {"empty with seed 0", "", 0, 0},
18 {"empty with seed 1", "", 1, 0x514e28b7},
19 {"empty with seed max", "", 0xffffffff, 0x81f16f39},
20 {"test", "test", 0, 0xba6bd213},
21 {"test with seed", "test", 0x9747b28c, 0x704b81dc},
22 {"hello", "Hello, world!", 0, 0xc0363e43},
23 {"hello with seed", "Hello, world!", 42, 0x2c8c8533},
24 {"hello with seed 0x9747b28c", "Hello, world!", 0x9747b28c, 0x24884cba},
25 {"pangram", "The quick brown fox jumps over the lazy dog", 0, 0x2e4ff723},
26 {"pangram with seed", "The quick brown fox jumps over the lazy dog", 0x9747b28c, 0x2fa826cd},
27 }
28
29 for _, tt := range tests {
30 t.Run(tt.name, func(t *testing.T) {
31 got := murmur3.Sum32WithSeed([]byte(tt.data), tt.seed)
32 if got != tt.want {
33 t.Errorf("Sum32WithSeed(%q, %d) = 0x%08x, want 0x%08x", tt.data, tt.seed, got, tt.want)
34 }
35 })
36 }
37}
38
39func TestHash32InterfaceSizes(t *testing.T) {
40 h := murmur3.New32()
41 if h.Size() != 4 {
42 t.Errorf("Size() = %d, want 4", h.Size())
43 }
44 if h.BlockSize() != 4 {
45 t.Errorf("BlockSize() = %d, want 4", h.BlockSize())
46 }
47}
48
49func TestHash32IncrementalWrite(t *testing.T) {
50 want := uint32(3224780355)
51 data := []byte("Hello, world!")
52
53 // Hash one byte at a time
54 h := murmur3.New32()
55 for _, b := range data {
56 h.Write([]byte{b})
57 }
58
59 if got := h.Sum32(); got != want {
60 t.Errorf("incremental Write got 0x%08x, want 0x%08x", got, want)
61 }
62
63 // Hash in two parts
64 h.Reset()
65 h.Write(data[:5])
66 h.Write(data[5:])
67 if got := h.Sum32(); got != want {
68 t.Errorf("two-part Write got 0x%08x, want 0x%08x", got, want)
69 }
70}
71
72func TestHash32Sum(t *testing.T) {
73 h := murmur3.New32()
74 h.Write([]byte("Hello, world!"))
75 b := h.Sum(nil)
76 if len(b) != 4 {
77 t.Fatalf("Sum(nil) returned %d bytes, want 4", len(b))
78 }
79
80 got := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
81 want := uint32(3224780355)
82 if got != want {
83 t.Errorf("Sum got 0x%08x, want 0x%08x", got, want)
84 }
85}
86
87func TestHash32SumDoesNotChangeState(t *testing.T) {
88 h := murmur3.New32()
89 h.Write([]byte("Hello"))
90 s1 := h.Sum32()
91 s2 := h.Sum32()
92 if s1 != s2 {
93 t.Errorf("Sum32 changed state: first 0x%08x, second 0x%08x", s1, s2)
94 }
95}
96
97func TestHash32Reset(t *testing.T) {
98 h := murmur3.New32()
99 h.Write([]byte("some data"))
100 h.Reset()
101 h.Write([]byte("Hello, world!"))
102 got := h.Sum32()
103 want := uint32(3224780355)
104 if got != want {
105 t.Errorf("after Reset got 0x%08x, want 0x%08x", got, want)
106 }
107}