reflect.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // +build !unsafe
  2. package protocol
  3. import (
  4. "reflect"
  5. )
  6. type index []int
  7. type _type struct{ typ reflect.Type }
  8. func typeOf(x interface{}) _type {
  9. return makeType(reflect.TypeOf(x))
  10. }
  11. func elemTypeOf(x interface{}) _type {
  12. return makeType(reflect.TypeOf(x).Elem())
  13. }
  14. func makeType(t reflect.Type) _type {
  15. return _type{typ: t}
  16. }
  17. type value struct {
  18. val reflect.Value
  19. }
  20. func nonAddressableValueOf(x interface{}) value {
  21. return value{val: reflect.ValueOf(x)}
  22. }
  23. func valueOf(x interface{}) value {
  24. return value{val: reflect.ValueOf(x).Elem()}
  25. }
  26. func makeValue(t reflect.Type) value {
  27. return value{val: reflect.New(t).Elem()}
  28. }
  29. func (v value) bool() bool { return v.val.Bool() }
  30. func (v value) int8() int8 { return int8(v.int64()) }
  31. func (v value) int16() int16 { return int16(v.int64()) }
  32. func (v value) int32() int32 { return int32(v.int64()) }
  33. func (v value) int64() int64 { return v.val.Int() }
  34. func (v value) string() string { return v.val.String() }
  35. func (v value) bytes() []byte { return v.val.Bytes() }
  36. func (v value) iface(t reflect.Type) interface{} { return v.val.Addr().Interface() }
  37. func (v value) array(t reflect.Type) array { return array{val: v.val} }
  38. func (v value) setBool(b bool) { v.val.SetBool(b) }
  39. func (v value) setInt8(i int8) { v.setInt64(int64(i)) }
  40. func (v value) setInt16(i int16) { v.setInt64(int64(i)) }
  41. func (v value) setInt32(i int32) { v.setInt64(int64(i)) }
  42. func (v value) setInt64(i int64) { v.val.SetInt(i) }
  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) }