github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/internal/rthash/hash_1.21_test.go (about)

     1  //go:build gc && go1.21
     2  
     3  package rthash
     4  
     5  import (
     6  	"fmt"
     7  	"testing"
     8  )
     9  
    10  func TestHashFunc_Interface(t *testing.T) {
    11  	t.Run("efaceHash / empty interface", func(t *testing.T) {
    12  		type myEface any
    13  		f := NewHashFunc[myEface]()
    14  		for _, x := range []myEface{
    15  			int8(123),
    16  			"a string",
    17  			complex(1, 2),
    18  			hashable{12345, "abcde"},
    19  			&hashable{12345, "abcde"},
    20  		} {
    21  			hash := f(x)
    22  			t.Logf("%T: %v, hash: %d", x, x, hash)
    23  		}
    24  	})
    25  
    26  	t.Run("efaceHash / non-empty interface", func(t *testing.T) {
    27  		f := NewHashFunc[fmt.Stringer]()
    28  		for _, x := range []fmt.Stringer{
    29  			stringerInt(12345),
    30  			stringerStr("abc"),
    31  			hashable{12345, "abcde"},
    32  			&hashable{12345, "abcde"},
    33  		} {
    34  			hash := f(x)
    35  			t.Logf("%T: %v, hash: %d", x, x, hash)
    36  		}
    37  	})
    38  }
    39  
    40  type stringerInt int
    41  
    42  func (x stringerInt) String() string {
    43  	return fmt.Sprint(int(x))
    44  }
    45  
    46  type stringerStr string
    47  
    48  func (x stringerStr) String() string {
    49  	return string(x)
    50  }
    51  
    52  func (x hashable) String() string {
    53  	return fmt.Sprintf("%d %s", x.A, x.B)
    54  }
    55  
    56  func BenchmarkHashFunc_efaceHash(b *testing.B) {
    57  	f := NewHashFunc[any]()
    58  	for i := 0; i < b.N; i++ {
    59  		_ = f(hashable{12345, "abcde"})
    60  	}
    61  }
    62  
    63  func BenchmarkHashFunc_typeHash(b *testing.B) {
    64  	f := NewHashFunc[hashable]()
    65  	for i := 0; i < b.N; i++ {
    66  		_ = f(hashable{12345, "abcde"})
    67  	}
    68  }