github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/unsafe/reflectx/unsafeheader_test.go (about)

     1  package reflectx
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  	"unsafe"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestStringToBytes(t *testing.T) {
    12  	s := "hello, world"
    13  	b := StringToBytes(s)
    14  	assert.Equal(t, []byte(s), b)
    15  
    16  	strHeader := (*StringHeader)(unsafe.Pointer(&s))
    17  	bytesHeader := (*SliceHeader)(unsafe.Pointer(&b))
    18  	assert.Equal(t, strHeader.Data, bytesHeader.Data)
    19  }
    20  
    21  func TestBytesToString(t *testing.T) {
    22  	b := []byte("hello, world")
    23  	s := BytesToString(b)
    24  	assert.Equal(t, "hello, world", s)
    25  
    26  	bytesHeader := (*SliceHeader)(unsafe.Pointer(&b))
    27  	strHeader := (*StringHeader)(unsafe.Pointer(&s))
    28  	assert.Equal(t, bytesHeader.Data, strHeader.Data)
    29  }
    30  
    31  func TestUnpackSlice(t *testing.T) {
    32  	slice := make([]int, 3, 6)
    33  	slice[0], slice[1], slice[2] = 0, 1, 2
    34  	eface, header := UnpackSlice(slice)
    35  
    36  	assert.Equal(t, 3, header.Len)
    37  	assert.Equal(t, 6, header.Cap)
    38  	assert.Equal(t, reflect.Slice, eface.RType.Kind())
    39  	assert.Equal(t, reflect.Int, eface.RType.Elem().Kind())
    40  
    41  	assert.Equal(t, 3, SliceLen(slice))
    42  	assert.Equal(t, 6, SliceCap(slice))
    43  }