map_elem_bytes_test.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package tests
  2. import (
  3. "context"
  4. "github.com/modern-go/reflect2"
  5. "github.com/modern-go/test"
  6. "github.com/modern-go/test/must"
  7. "testing"
  8. "unsafe"
  9. )
  10. func Test_map_elem_bytes(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][]byte{}
  16. valType := api.TypeOf(obj).(reflect2.MapType)
  17. elem1 := []byte("hello")
  18. valType.SetIndex(&obj, pInt(2), &elem1)
  19. elem2 := []byte(nil)
  20. valType.SetIndex(&obj, pInt(3), &elem2)
  21. return obj
  22. }))
  23. t.Run("UnsafeSetIndex", test.Case(func(ctx context.Context) {
  24. obj := map[int][]byte{}
  25. valType := reflect2.TypeOf(obj).(reflect2.MapType)
  26. hello := []byte("hello")
  27. valType.UnsafeSetIndex(unsafe.Pointer(&obj), reflect2.PtrOf(2), unsafe.Pointer(&hello))
  28. elem2 := []byte(nil)
  29. valType.UnsafeSetIndex(unsafe.Pointer(&obj), reflect2.PtrOf(3), unsafe.Pointer(&elem2))
  30. must.Equal([]byte("hello"), obj[2])
  31. must.Nil(obj[3])
  32. }))
  33. t.Run("UnsafeGetIndex", test.Case(func(ctx context.Context) {
  34. obj := map[int][]byte{2: []byte("hello")}
  35. valType := reflect2.TypeOf(obj).(reflect2.MapType)
  36. elem := valType.UnsafeGetIndex(unsafe.Pointer(&obj), reflect2.PtrOf(2))
  37. must.Equal([]byte("hello"), valType.Elem().UnsafeIndirect(elem))
  38. }))
  39. }