github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/reflect2/test/slice_eface_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 "github.com/v2pro/plz/test/must" 9 "unsafe" 10 "github.com/v2pro/plz/test/should" 11 "fmt" 12 ) 13 14 func Test_slice_eface(t *testing.T) { 15 t.Run("MakeSlice", testOp(func(api reflect2.API) interface{} { 16 valType := api.TypeOf([]interface{}{}).(reflect2.SliceType) 17 obj := valType.MakeSlice(5, 10) 18 obj.([]interface{})[0] = 100 19 obj.([]interface{})[4] = 20 20 return obj 21 })) 22 t.Run("SetIndex", testOp(func(api reflect2.API) interface{} { 23 obj := []interface{}{1, nil} 24 valType := api.TypeOf(obj).(reflect2.SliceType) 25 elem0 := interface{}(100) 26 valType.SetIndex(obj, 0, &elem0) 27 elem1 := interface{}(20) 28 valType.SetIndex(obj, 1, &elem1) 29 return obj 30 })) 31 t.Run("UnsafeSetIndex", test.Case(func(ctx *countlog.Context) { 32 obj := []interface{}{1, 2} 33 valType := reflect2.TypeOf(obj).(reflect2.SliceType) 34 var elem0 interface{} = 100 35 valType.UnsafeSetIndex(reflect2.PtrOf(obj), 0, unsafe.Pointer(&elem0)) 36 var elem1 interface{} = 10 37 valType.UnsafeSetIndex(reflect2.PtrOf(obj), 1, unsafe.Pointer(&elem1)) 38 must.Equal([]interface{}{100, 10}, obj) 39 })) 40 t.Run("GetIndex", testOp(func(api reflect2.API) interface{} { 41 obj := []interface{}{1, nil} 42 valType := api.TypeOf(obj).(reflect2.SliceType) 43 fmt.Println(api, *valType.GetIndex(obj, 0).(*interface{})) 44 return []interface{}{ 45 valType.GetIndex(obj, 0), 46 valType.GetIndex(obj, 1), 47 } 48 })) 49 t.Run("UnsafeGetIndex", test.Case(func(ctx *countlog.Context) { 50 obj := []interface{}{1, nil} 51 valType := reflect2.TypeOf(obj).(reflect2.SliceType) 52 elem0 := valType.UnsafeGetIndex(reflect2.PtrOf(obj), 0) 53 must.Equal(1, *(*interface{})(elem0)) 54 })) 55 t.Run("Append", testOp(func(api reflect2.API) interface{} { 56 obj := make([]interface{}, 2, 3) 57 obj[0] = 1 58 obj[1] = 2 59 valType := api.TypeOf(obj).(reflect2.SliceType) 60 valType.Append(&obj, 3) 61 // will trigger grow 62 valType.Append(&obj, 4) 63 return obj 64 })) 65 t.Run("UnsafeAppend", test.Case(func(ctx *countlog.Context) { 66 obj := make([]interface{}, 2, 3) 67 obj[0] = 1 68 obj[1] = 2 69 valType := reflect2.TypeOf(obj).(reflect2.SliceType) 70 ptr := reflect2.PtrOf(obj) 71 var elem2 interface{} = 3 72 valType.UnsafeAppend(ptr, unsafe.Pointer(&elem2)) 73 var elem3 interface{} = 4 74 valType.UnsafeAppend(ptr, unsafe.Pointer(&elem3)) 75 should.Equal([]interface{}{1, 2, 3, 4}, valType.PackEFace(ptr)) 76 })) 77 }