slice_ptr_test.go 1.6 KB

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