map_key_ptr_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package test
  2. import (
  3. "testing"
  4. "github.com/modern-go/reflect2"
  5. "github.com/v2pro/plz/test/must"
  6. "github.com/v2pro/plz/test"
  7. "github.com/v2pro/plz/countlog"
  8. "unsafe"
  9. )
  10. func Test_map_key_ptr(t *testing.T) {
  11. var pInt = func(val int) *int {
  12. return &val
  13. }
  14. t.Run("SetIndex", testOp(func(api reflect2.API) interface{} {
  15. obj := map[*int]int{}
  16. valType := api.TypeOf(obj).(reflect2.MapType)
  17. key := pInt(2)
  18. valType.SetIndex(obj, &key, 4)
  19. valType.SetIndex(obj, &key, 9)
  20. //valType.SetIndex(obj, nil, 9)
  21. return obj[pInt(2)]
  22. }))
  23. t.Run("UnsafeSetIndex", test.Case(func(ctx *countlog.Context) {
  24. obj := map[*int]int{}
  25. valType := reflect2.TypeOf(obj).(reflect2.MapType)
  26. v := pInt(2)
  27. valType.UnsafeSetIndex(reflect2.PtrOf(obj), unsafe.Pointer(v), reflect2.PtrOf(4))
  28. must.Equal(4, obj[v])
  29. }))
  30. t.Run("GetIndex", testOp(func(api reflect2.API) interface{} {
  31. obj := map[*int]int{pInt(3): 9, pInt(2): 4}
  32. valType := api.TypeOf(obj).(reflect2.MapType)
  33. return []interface{}{
  34. valType.GetIndex(obj, pInt(3)),
  35. valType.GetIndex(obj, pInt(2)),
  36. valType.GetIndex(obj, nil),
  37. }
  38. }))
  39. t.Run("Iterate", testOp(func(api reflect2.API) interface{} {
  40. obj := map[*int]int{pInt(2): 4}
  41. valType := api.TypeOf(obj).(reflect2.MapType)
  42. iter := valType.Iterate(&obj)
  43. must.Pass(iter.HasNext(), "api", api)
  44. key1, elem1 := iter.Next()
  45. must.Pass(!iter.HasNext(), "api", api)
  46. return []interface{}{key1, elem1}
  47. }))
  48. }