github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/reflect2/test/slice_ptr_test.go (about)

     1  package test
     2  
     3  import (
     4  	"testing"
     5  	"github.com/v2pro/plz/reflect2"
     6  	"github.com/v2pro/plz/test"
     7  	"github.com/v2pro/plz/countlog"
     8  	"unsafe"
     9  	"github.com/v2pro/plz/test/must"
    10  )
    11  
    12  func Test_slice_ptr(t *testing.T) {
    13  	var pInt = func(val int) *int {
    14  		return &val
    15  	}
    16  	t.Run("MakeSlice", testOp(func(api reflect2.API) interface{} {
    17  		valType := api.TypeOf([]*int{}).(reflect2.SliceType)
    18  		obj := valType.MakeSlice(5, 10)
    19  		obj.([]*int)[0] = pInt(1)
    20  		obj.([]*int)[4] = pInt(5)
    21  		return obj
    22  	}))
    23  	t.Run("SetIndex", testOp(func(api reflect2.API) interface{} {
    24  		obj := []*int{pInt(1), nil}
    25  		valType := api.TypeOf(obj).(reflect2.SliceType)
    26  		valType.SetIndex(obj, 0, pInt(2))
    27  		valType.SetIndex(obj, 1, pInt(3))
    28  		return obj
    29  	}))
    30  	t.Run("UnsafeSetIndex", test.Case(func(ctx *countlog.Context) {
    31  		obj := []*int{pInt(1), nil}
    32  		valType := reflect2.TypeOf(obj).(reflect2.SliceType)
    33  		valType.UnsafeSetIndex(reflect2.PtrOf(obj), 0, unsafe.Pointer(pInt(2)))
    34  		valType.UnsafeSetIndex(reflect2.PtrOf(obj), 1, unsafe.Pointer(pInt(1)))
    35  		must.Equal([]*int{pInt(2), pInt(1)}, obj)
    36  	}))
    37  	t.Run("GetIndex", testOp(func(api reflect2.API) interface{} {
    38  		obj := []*int{pInt(1), nil}
    39  		valType := api.TypeOf(obj).(reflect2.SliceType)
    40  		return []interface{}{
    41  			valType.GetIndex(&obj, 0),
    42  			valType.GetIndex(&obj, 1),
    43  			valType.GetIndex(obj, 0),
    44  			valType.GetIndex(obj, 1),
    45  		}
    46  	}))
    47  	t.Run("Append", testOp(func(api reflect2.API) interface{} {
    48  		obj := make([]*int, 2, 3)
    49  		obj[0] = pInt(1)
    50  		obj[1] = pInt(2)
    51  		valType := api.TypeOf(obj).(reflect2.SliceType)
    52  		valType.Append(obj, pInt(3))
    53  		// will trigger grow
    54  		valType.Append(obj, pInt(4))
    55  		return obj
    56  	}))
    57  }