unsafe_field.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package reflect2
  2. import (
  3. "reflect"
  4. "unsafe"
  5. )
  6. type UnsafeStructField struct {
  7. reflect.StructField
  8. structType *UnsafeStructType
  9. rtype unsafe.Pointer
  10. ptrRType unsafe.Pointer
  11. }
  12. func newUnsafeStructField(structType *UnsafeStructType, structField reflect.StructField) *UnsafeStructField {
  13. return &UnsafeStructField{
  14. StructField: structField,
  15. rtype: unpackEFace(structField.Type).data,
  16. ptrRType: unpackEFace(reflect.PtrTo(structField.Type)).data,
  17. structType: structType,
  18. }
  19. }
  20. func (field *UnsafeStructField) Offset() uintptr {
  21. return field.StructField.Offset
  22. }
  23. func (field *UnsafeStructField) Name() string {
  24. return field.StructField.Name
  25. }
  26. func (field *UnsafeStructField) PkgPath() string {
  27. return field.StructField.PkgPath
  28. }
  29. func (field *UnsafeStructField) Type() Type {
  30. return field.structType.cfg.Type2(field.StructField.Type)
  31. }
  32. func (field *UnsafeStructField) Tag() reflect.StructTag {
  33. return field.StructField.Tag
  34. }
  35. func (field *UnsafeStructField) Index() []int {
  36. return field.StructField.Index
  37. }
  38. func (field *UnsafeStructField) Anonymous() bool {
  39. return field.StructField.Anonymous
  40. }
  41. func (field *UnsafeStructField) Set(obj interface{}, value interface{}) {
  42. objEFace := unpackEFace(obj)
  43. assertType("StructField.SetIndex argument 1", field.structType.ptrRType, objEFace.rtype)
  44. valueEFace := unpackEFace(value)
  45. assertType("StructField.SetIndex argument 2", field.ptrRType, valueEFace.rtype)
  46. field.UnsafeSet(objEFace.data, valueEFace.data)
  47. }
  48. func (field *UnsafeStructField) UnsafeSet(obj unsafe.Pointer, value unsafe.Pointer) {
  49. fieldPtr := add(obj, field.StructField.Offset, "same as non-reflect &v.field")
  50. typedmemmove(field.rtype, fieldPtr, value)
  51. }
  52. func (field *UnsafeStructField) Get(obj interface{}) interface{} {
  53. objEFace := unpackEFace(obj)
  54. assertType("StructField.GetIndex argument 1", field.structType.ptrRType, objEFace.rtype)
  55. value := field.UnsafeGet(objEFace.data)
  56. return packEFace(field.ptrRType, value)
  57. }
  58. func (field *UnsafeStructField) UnsafeGet(obj unsafe.Pointer) unsafe.Pointer {
  59. return add(obj, field.StructField.Offset, "same as non-reflect &v.field")
  60. }