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