github.com/gochain-io/gochain@v2.2.26+incompatible/crypto/sha3/hashes_test.go (about) 1 package sha3 2 3 import ( 4 "bytes" 5 "testing" 6 ) 7 8 func TestKeccak256(t *testing.T) { 9 for _, data := range [][]byte{ 10 []byte("hello world"), 11 []byte("hello world hello world hello world hello world hello world hello world"), 12 []byte("0123456789asdfjkl;"), 13 } { 14 h := NewKeccak256() 15 h.Write(data) 16 a := h.Sum(nil) 17 var b [32]byte 18 Keccak256(b[:], data) 19 if !bytes.Equal(a, b[:]) { 20 t.Errorf("%q: expected %X got %X", data, a, b) 21 } 22 } 23 } 24 25 func BenchmarkKeccak256(b *testing.B) { 26 a := []byte("hello world hello world hello world hello world hello world hello world") 27 b.Run("unoptimized", func(b *testing.B) { 28 b.ReportAllocs() 29 for i := 0; i < b.N; i++ { 30 h := NewKeccak256() 31 h.Write(a) 32 _ = h.Sum(nil) 33 } 34 }) 35 b.Run("optimized", func(b *testing.B) { 36 var hash [32]byte 37 b.ReportAllocs() 38 for i := 0; i < b.N; i++ { 39 Keccak256(hash[:], a) 40 } 41 }) 42 } 43 44 func TestKeccak512(t *testing.T) { 45 for _, data := range [][]byte{ 46 []byte("hello world"), 47 []byte("hello world hello world hello world hello world hello world hello world"), 48 []byte("0123456789asdfjkl;"), 49 } { 50 h := NewKeccak512() 51 h.Write(data) 52 a := h.Sum(nil) 53 b := Keccak512(data) 54 if !bytes.Equal(a, b) { 55 t.Errorf("%q: expected %X got %X", data, a, b) 56 } 57 } 58 } 59 60 func BenchmarkKeccak512(b *testing.B) { 61 a := []byte("hello world hello world hello world hello world hello world hello world") 62 b.Run("unoptimized", func(b *testing.B) { 63 b.ReportAllocs() 64 for i := 0; i < b.N; i++ { 65 h := NewKeccak512() 66 h.Write(a) 67 _ = h.Sum(nil) 68 } 69 }) 70 b.Run("optimized", func(b *testing.B) { 71 b.ReportAllocs() 72 for i := 0; i < b.N; i++ { 73 _ = Keccak512(a) 74 } 75 }) 76 }