reflect.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. //go:build !unsafe
  2. // +build !unsafe
  3. package protocol
  4. import (
  5. "reflect"
  6. )
  7. type index []int
  8. type _type struct{ typ reflect.Type }
  9. func typeOf(x interface{}) _type {
  10. return makeType(reflect.TypeOf(x))
  11. }
  12. func elemTypeOf(x interface{}) _type {
  13. return makeType(reflect.TypeOf(x).Elem())
  14. }
  15. func makeType(t reflect.Type) _type {
  16. return _type{typ: t}
  17. }
  18. type value struct {
  19. val reflect.Value
  20. }
  21. func nonAddressableValueOf(x interface{}) value {
  22. return value{val: reflect.ValueOf(x)}
  23. }
  24. func valueOf(x interface{}) value {
  25. return value{val: reflect.ValueOf(x).Elem()}
  26. }
  27. func (v value) bool() bool { return v.val.Bool() }
  28. func (v value) int8() int8 { return int8(v.int64()) }
  29. func (v value) int16() int16 { return int16(v.int64()) }
  30. func (v value) int32() int32 { return int32(v.int64()) }
  31. func (v value) int64() int64 { return v.val.Int() }
  32. func (v value) float64() float64 { return v.val.Float() }
  33. func (v value) string() string { return v.val.String() }
  34. func (v value) bytes() []byte { return v.val.Bytes() }
  35. func (v value) iface(t reflect.Type) interface{} { return v.val.Addr().Interface() }
  36. func (v value) array(t reflect.Type) array { return array(v) }
  37. func (v value) setBool(b bool) { v.val.SetBool(b) }
  38. func (v value) setInt8(i int8) { v.setInt64(int64(i)) }
  39. func (v value) setInt16(i int16) { v.setInt64(int64(i)) }
  40. func (v value) setInt32(i int32) { v.setInt64(int64(i)) }
  41. func (v value) setInt64(i int64) { v.val.SetInt(i) }
  42. func (v value) setFloat64(f float64) { v.val.SetFloat(f) }
  43. func (v value) setString(s string) { v.val.SetString(s) }
  44. func (v value) setBytes(b []byte) { v.val.SetBytes(b) }
  45. func (v value) setArray(a array) {
  46. if a.val.IsValid() {
  47. v.val.Set(a.val)
  48. } else {
  49. v.val.Set(reflect.Zero(v.val.Type()))
  50. }
  51. }
  52. func (v value) fieldByIndex(i index) value {
  53. return value{val: v.val.FieldByIndex(i)}
  54. }
  55. type array struct {
  56. val reflect.Value
  57. }
  58. func makeArray(t reflect.Type, n int) array {
  59. return array{val: reflect.MakeSlice(reflect.SliceOf(t), n, n)}
  60. }
  61. func (a array) index(i int) value { return value{val: a.val.Index(i)} }
  62. func (a array) length() int { return a.val.Len() }
  63. func (a array) isNil() bool { return a.val.IsNil() }
  64. func indexOf(s reflect.StructField) index { return index(s.Index) }
  65. func bytesToString(b []byte) string { return string(b) }