另客网go项目公用的代码库

unsafe_struct.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package reflect2
  2. import (
  3. "reflect"
  4. "unsafe"
  5. )
  6. type UnsafeStructType struct {
  7. unsafeType
  8. likePtr bool
  9. }
  10. func newUnsafeStructType(cfg *frozenConfig, type1 reflect.Type) *UnsafeStructType {
  11. return &UnsafeStructType{
  12. unsafeType: *newUnsafeType(cfg, type1),
  13. likePtr: likePtrType(type1),
  14. }
  15. }
  16. func (type2 *UnsafeStructType) LikePtr() bool {
  17. return type2.likePtr
  18. }
  19. func (type2 *UnsafeStructType) Indirect(obj interface{}) interface{} {
  20. objEFace := unpackEFace(obj)
  21. assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype)
  22. return type2.UnsafeIndirect(objEFace.data)
  23. }
  24. func (type2 *UnsafeStructType) UnsafeIndirect(ptr unsafe.Pointer) interface{} {
  25. if type2.likePtr {
  26. return packEFace(type2.rtype, *(*unsafe.Pointer)(ptr))
  27. }
  28. return packEFace(type2.rtype, ptr)
  29. }
  30. func (type2 *UnsafeStructType) FieldByName(name string) StructField {
  31. structField, found := type2.Type.FieldByName(name)
  32. if !found {
  33. return nil
  34. }
  35. return newUnsafeStructField(type2, structField)
  36. }
  37. func (type2 *UnsafeStructType) Field(i int) StructField {
  38. return newUnsafeStructField(type2, type2.Type.Field(i))
  39. }
  40. func (type2 *UnsafeStructType) FieldByIndex(index []int) StructField {
  41. return newUnsafeStructField(type2, type2.Type.FieldByIndex(index))
  42. }
  43. func (type2 *UnsafeStructType) FieldByNameFunc(match func(string) bool) StructField {
  44. structField, found := type2.Type.FieldByNameFunc(match)
  45. if !found {
  46. panic("field match condition not found in " + type2.Type.String())
  47. }
  48. return newUnsafeStructField(type2, structField)
  49. }