github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/gnovm/stdlibs/hash/marshal_test.gno (about)

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Test that the hashes in the standard library implement
     6  // BinaryMarshaler, BinaryUnmarshaler,
     7  // and lock in the current representations.
     8  
     9  package hash
    10  
    11  import (
    12  	"bytes"
    13  	"crypto/md5"
    14  	"crypto/sha1"
    15  	"crypto/sha256"
    16  	"encoding"
    17  	"encoding/hex"
    18  	"hash"
    19  	"hash/adler32"
    20  	"testing"
    21  )
    22  
    23  func fromHex(s string) []byte {
    24  	b, err := hex.DecodeString(s)
    25  	if err != nil {
    26  		panic(err)
    27  	}
    28  	return b
    29  }
    30  
    31  var marshalTests = []struct {
    32  	name   string
    33  	new    func() hash.Hash
    34  	golden []byte
    35  }{
    36  	{"adler32", func() hash.Hash { return adler32.New() }, fromHex("61646c01460a789d")},
    37  }
    38  
    39  func TestMarshalHash(t *testing.T) {
    40  	for _, tt := range marshalTests {
    41  		t.Run(tt.name, func(t *testing.T) {
    42  			buf := make([]byte, 256)
    43  			for i := range buf {
    44  				buf[i] = byte(i)
    45  			}
    46  
    47  			h := tt.new()
    48  			h.Write(buf[:256])
    49  			sum := h.Sum(nil)
    50  
    51  			h2 := tt.new()
    52  			h3 := tt.new()
    53  			const split = 249
    54  			for i := 0; i < split; i++ {
    55  				h2.Write(buf[i : i+1])
    56  			}
    57  			h2m, ok := h2.(encoding.BinaryMarshaler)
    58  			if !ok {
    59  				t.Fatalf("Hash does not implement MarshalBinary")
    60  			}
    61  			enc, err := h2m.MarshalBinary()
    62  			if err != nil {
    63  				t.Fatalf("MarshalBinary: %v", err)
    64  			}
    65  			if !bytes.Equal(enc, tt.golden) {
    66  				t.Errorf("MarshalBinary = %x, want %x", enc, tt.golden)
    67  			}
    68  			h3u, ok := h3.(encoding.BinaryUnmarshaler)
    69  			if !ok {
    70  				t.Fatalf("Hash does not implement UnmarshalBinary")
    71  			}
    72  			if err := h3u.UnmarshalBinary(enc); err != nil {
    73  				t.Fatalf("UnmarshalBinary: %v", err)
    74  			}
    75  			h2.Write(buf[split:])
    76  			h3.Write(buf[split:])
    77  			sum2 := h2.Sum(nil)
    78  			sum3 := h3.Sum(nil)
    79  			if !bytes.Equal(sum2, sum) {
    80  				t.Fatalf("Sum after MarshalBinary = %x, want %x", sum2, sum)
    81  			}
    82  			if !bytes.Equal(sum3, sum) {
    83  				t.Fatalf("Sum after UnmarshalBinary = %x, want %x", sum3, sum)
    84  			}
    85  		})
    86  	}
    87  }