map_key_ptr_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package tests
  2. import (
  3. "github.com/modern-go/reflect2"
  4. "github.com/modern-go/test"
  5. "github.com/modern-go/test/must"
  6. "testing"
  7. "context"
  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, pInt(4))
  19. valType.SetIndex(&obj, &key, pInt(9))
  20. //valType.SetIndex(obj, nil, 9)
  21. return obj[pInt(2)]
  22. }))
  23. t.Run("UnsafeSetIndex", test.Case(func(ctx context.Context) {
  24. obj := map[*int]int{}
  25. valType := reflect2.TypeOf(obj).(reflect2.MapType)
  26. v := pInt(2)
  27. valType.UnsafeSetIndex(
  28. unsafe.Pointer(&obj), unsafe.Pointer(&v), reflect2.PtrOf(4))
  29. must.Equal(4, obj[v])
  30. }))
  31. t.Run("GetIndex", testOp(func(api reflect2.API) interface{} {
  32. obj := map[*int]int{pInt(3): 9, pInt(2): 4}
  33. valType := api.TypeOf(obj).(reflect2.MapType)
  34. key1 := pInt(3)
  35. key2 := pInt(2)
  36. key3 := (*int)(nil)
  37. return []interface{}{
  38. valType.GetIndex(&obj, &key1),
  39. valType.GetIndex(&obj, &key2),
  40. valType.GetIndex(&obj, &key3),
  41. }
  42. }))
  43. t.Run("Iterate", testOp(func(api reflect2.API) interface{} {
  44. obj := map[*int]int{pInt(2): 4}
  45. valType := api.TypeOf(obj).(reflect2.MapType)
  46. iter := valType.Iterate(&obj)
  47. must.Pass(iter.HasNext(), "api", api)
  48. key1, elem1 := iter.Next()
  49. must.Pass(!iter.HasNext(), "api", api)
  50. return []interface{}{key1, elem1}
  51. }))
  52. }