github.com/emmansun/gmsm@v0.29.1/internal/subtle/constant_time_test.go (about)

     1  package subtle
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  )
     7  
     8  func TestConstantTimeAllZero(t *testing.T) {
     9  	type args struct {
    10  		bytes []byte
    11  	}
    12  	tests := []struct {
    13  		name string
    14  		args args
    15  		want int
    16  	}{
    17  		{"all zero", args{[]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 1},
    18  		{"not all zero", args{[]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}, 0},
    19  	}
    20  	for _, tt := range tests {
    21  		t.Run(tt.name, func(t *testing.T) {
    22  			if got := ConstantTimeAllZero(tt.args.bytes); got != tt.want {
    23  				t.Errorf("ConstantTimeAllZero() = %v, want %v", got, tt.want)
    24  			}
    25  		})
    26  	}
    27  }
    28  
    29  func BenchmarkConstantTimeAllZero(b *testing.B) {
    30  	data := make([]byte, 1<<15)
    31  	sizes := []int64{1 << 3, 1 << 4, 1 << 5, 1 << 7, 1 << 11, 1 << 13, 1 << 15}
    32  	for _, size := range sizes {
    33  		b.Run(fmt.Sprintf("%dBytes", size), func(b *testing.B) {
    34  			s0 := data[:size]
    35  			b.SetBytes(int64(size))
    36  			for i := 0; i < b.N; i++ {
    37  				ConstantTimeAllZero(s0)
    38  			}
    39  		})
    40  	}
    41  }