gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/unsafe/unsafe_test.go (about)

     1  package unsafe
     2  
     3  import (
     4  	"fmt"
     5  	"gitee.com/sy_183/go-common/unit"
     6  	"testing"
     7  	"unsafe"
     8  )
     9  
    10  func TestOffset(t *testing.T) {
    11  	type st struct {
    12  		A string
    13  		B int
    14  		C bool
    15  		D float64
    16  		E []byte
    17  	}
    18  	s := st{
    19  		A: "a",
    20  		B: 1,
    21  		C: true,
    22  		D: 3.14,
    23  		E: []byte{1, 2, 3, 4},
    24  	}
    25  
    26  	if b := Offset[st, bool](&s, unsafe.Offsetof(s.C)); b != true {
    27  		panic(fmt.Sprintf("%t != %t", b, true))
    28  	}
    29  }
    30  
    31  func BenchmarkOffset(b *testing.B) {
    32  	b.Run("direct", func(b *testing.B) {
    33  		type st struct {
    34  			A string
    35  			B int
    36  			C bool
    37  			D float64
    38  			E []byte
    39  		}
    40  		s := st{
    41  			A: "a",
    42  			B: 1,
    43  			C: true,
    44  			D: 3.14,
    45  			E: []byte{1, 2, 3, 4},
    46  		}
    47  
    48  		for i := 0; i < b.N; i++ {
    49  			for i := 0; i < unit.MeBiByte; i++ {
    50  				s.B = i
    51  				if b := *(*int)(unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.B))); b != i {
    52  					panic(fmt.Sprintf("%d != %d", b, i))
    53  				}
    54  			}
    55  		}
    56  	})
    57  	b.Run("offset", func(b *testing.B) {
    58  		type st struct {
    59  			A string
    60  			B int
    61  			C bool
    62  			D float64
    63  			E []byte
    64  		}
    65  		s := st{
    66  			A: "a",
    67  			B: 1,
    68  			C: true,
    69  			D: 3.14,
    70  			E: []byte{1, 2, 3, 4},
    71  		}
    72  
    73  		for i := 0; i < b.N; i++ {
    74  			for i := 0; i < unit.MeBiByte; i++ {
    75  				s.B = i
    76  				if b := Offset[st, int](&s, unsafe.Offsetof(s.B)); b != i {
    77  					panic(fmt.Sprintf("%d != %d", b, i))
    78  				}
    79  			}
    80  		}
    81  	})
    82  }