github.com/bcskill/bcschain/v3@v3.4.9-beta2/core/rawdb/schema_test.go (about)

     1  package rawdb
     2  
     3  import (
     4  	"bytes"
     5  	"testing"
     6  
     7  	"github.com/bcskill/bcschain/v3/common"
     8  )
     9  
    10  func TestNumHashKey(t *testing.T) {
    11  	prefix := []byte{headerPrefix}
    12  	hash := common.Hash{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}
    13  
    14  	for i, test := range []struct {
    15  		orig, opt []byte
    16  	}{
    17  		{
    18  			orig: append(append(prefix, encodeBlockNumber(123456789)...), hash.Bytes()...),
    19  			opt:  numHashKey(headerPrefix, 123456789, hash),
    20  		},
    21  		{
    22  			orig: append(append(prefix, encodeBlockNumber(123456789)...), []byte{numSuffix}...),
    23  			opt:  numKey(123456789),
    24  		},
    25  		{
    26  			orig: append(append(append(prefix, encodeBlockNumber(123456789)...), hash[:]...), []byte{tdSuffix}...),
    27  			opt:  tdKey(123456789, hash),
    28  		},
    29  	} {
    30  		if !bytes.Equal(test.orig, test.opt) {
    31  			t.Errorf("%d expected:\n\t%X\nbut got:\n\t%X", i, test.orig, test.opt)
    32  		}
    33  	}
    34  }
    35  
    36  func BenchmarkNumHashKey(b *testing.B) {
    37  	prefix := []byte("h")
    38  	b.Run("unoptimized", func(b *testing.B) {
    39  		b.ReportAllocs()
    40  		for i := 0; i < b.N; i++ {
    41  			_ = append(append(prefix, encodeBlockNumber(123456789)...), common.Hash{}.Bytes()...)
    42  		}
    43  	})
    44  	b.Run("optimized", func(b *testing.B) {
    45  		b.ReportAllocs()
    46  		for i := 0; i < b.N; i++ {
    47  			_ = numHashKey(headerPrefix, 123456789, common.Hash{})
    48  		}
    49  	})
    50  }