github.com/cloudwego/dynamicgo@v0.2.6-0.20240519101509-707f41b6b834/internal/caching/hashing_test.go (about)

     1  /*
     2   * Copyright 2023 CloudWeGo Authors.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package caching
    18  
    19  import (
    20  	"fmt"
    21  	"testing"
    22  	"unsafe"
    23  
    24  	"github.com/cloudwego/dynamicgo/internal/rt"
    25  )
    26  
    27  const (
    28  	_H_basis uint64 = 0xcbf29ce484222325
    29  	_H_prime uint64 = 0x00000100000001b3
    30  )
    31  
    32  func fnv1a(s string) uint64 {
    33  	v := _H_basis
    34  	m := (*rt.GoString)(unsafe.Pointer(&s))
    35  
    36  	/* hash each byte */
    37  	for i := 0; i < m.Len; i++ {
    38  		v ^= uint64(*(*uint8)(unsafe.Pointer(uintptr(m.Ptr) + uintptr(i))))
    39  		v *= _H_prime
    40  	}
    41  
    42  	/* never returns 0 for hash */
    43  	if v == 0 {
    44  		return 1
    45  	} else {
    46  		return v
    47  	}
    48  }
    49  
    50  func TestHashing_Fnv1a(t *testing.T) {
    51  	fmt.Printf("%#x\n", fnv1a("hello, world"))
    52  }
    53  
    54  func TestHashing_StrHash(t *testing.T) {
    55  	s := "hello, world"
    56  	fmt.Printf("%#x\n", StrHash(s))
    57  }
    58  
    59  var fn_fnv1a = fnv1a
    60  
    61  func BenchmarkHashing_Fnv1a(b *testing.B) {
    62  	for i := 0; i < b.N; i++ {
    63  		fn_fnv1a("accountid_interval_aweme_second")
    64  	}
    65  }
    66  
    67  func BenchmarkHashing_StrHash(b *testing.B) {
    68  	for i := 0; i < b.N; i++ {
    69  		StrHash("accountid_interval_aweme_second")
    70  	}
    71  }
    72  
    73  func BenchmarkHashing_DJBHash32(b *testing.B) {
    74  	for i := 0; i < b.N; i++ {
    75  		DJBHash32("accountid_interval_aweme_second")
    76  	}
    77  }