typecache.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package rlp
  17. import (
  18. "fmt"
  19. "reflect"
  20. "strings"
  21. "sync"
  22. )
  23. var (
  24. typeCacheMutex sync.RWMutex
  25. typeCache = make(map[typekey]*typeinfo)
  26. )
  27. type typeinfo struct {
  28. decoder decoder
  29. decoderErr error // error from makeDecoder
  30. writer writer
  31. writerErr error // error from makeWriter
  32. }
  33. // tags represents struct tags.
  34. type tags struct {
  35. // rlp:"nil" controls whether empty input results in a nil pointer.
  36. nilOK bool
  37. // This controls whether nil pointers are encoded/decoded as empty strings
  38. // or empty lists.
  39. nilKind Kind
  40. // rlp:"tail" controls whether this field swallows additional list
  41. // elements. It can only be set for the last field, which must be
  42. // of slice type.
  43. tail bool
  44. // rlp:"-" ignores fields.
  45. ignored bool
  46. }
  47. // typekey is the key of a type in typeCache. It includes the struct tags because
  48. // they might generate a different decoder.
  49. type typekey struct {
  50. reflect.Type
  51. tags
  52. }
  53. type decoder func(*Stream, reflect.Value) error
  54. type writer func(reflect.Value, *encbuf) error
  55. func cachedDecoder(typ reflect.Type) (decoder, error) {
  56. info := cachedTypeInfo(typ, tags{})
  57. return info.decoder, info.decoderErr
  58. }
  59. func cachedWriter(typ reflect.Type) (writer, error) {
  60. info := cachedTypeInfo(typ, tags{})
  61. return info.writer, info.writerErr
  62. }
  63. func cachedTypeInfo(typ reflect.Type, tags tags) *typeinfo {
  64. typeCacheMutex.RLock()
  65. info := typeCache[typekey{typ, tags}]
  66. typeCacheMutex.RUnlock()
  67. if info != nil {
  68. return info
  69. }
  70. // not in the cache, need to generate info for this type.
  71. typeCacheMutex.Lock()
  72. defer typeCacheMutex.Unlock()
  73. return cachedTypeInfo1(typ, tags)
  74. }
  75. func cachedTypeInfo1(typ reflect.Type, tags tags) *typeinfo {
  76. key := typekey{typ, tags}
  77. info := typeCache[key]
  78. if info != nil {
  79. // another goroutine got the write lock first
  80. return info
  81. }
  82. // put a dummy value into the cache before generating.
  83. // if the generator tries to lookup itself, it will get
  84. // the dummy value and won't call itself recursively.
  85. info = new(typeinfo)
  86. typeCache[key] = info
  87. info.generate(typ, tags)
  88. return info
  89. }
  90. type field struct {
  91. index int
  92. info *typeinfo
  93. }
  94. func structFields(typ reflect.Type) (fields []field, err error) {
  95. lastPublic := lastPublicField(typ)
  96. for i := 0; i < typ.NumField(); i++ {
  97. if f := typ.Field(i); f.PkgPath == "" { // exported
  98. tags, err := parseStructTag(typ, i, lastPublic)
  99. if err != nil {
  100. return nil, err
  101. }
  102. if tags.ignored {
  103. continue
  104. }
  105. info := cachedTypeInfo1(f.Type, tags)
  106. fields = append(fields, field{i, info})
  107. }
  108. }
  109. return fields, nil
  110. }
  111. type structFieldError struct {
  112. typ reflect.Type
  113. field int
  114. err error
  115. }
  116. func (e structFieldError) Error() string {
  117. return fmt.Sprintf("%v (struct field %v.%s)", e.err, e.typ, e.typ.Field(e.field).Name)
  118. }
  119. type structTagError struct {
  120. typ reflect.Type
  121. field, tag, err string
  122. }
  123. func (e structTagError) Error() string {
  124. return fmt.Sprintf("rlp: invalid struct tag %q for %v.%s (%s)", e.tag, e.typ, e.field, e.err)
  125. }
  126. func parseStructTag(typ reflect.Type, fi, lastPublic int) (tags, error) {
  127. f := typ.Field(fi)
  128. var ts tags
  129. for _, t := range strings.Split(f.Tag.Get("rlp"), ",") {
  130. switch t = strings.TrimSpace(t); t {
  131. case "":
  132. case "-":
  133. ts.ignored = true
  134. case "nil", "nilString", "nilList":
  135. ts.nilOK = true
  136. if f.Type.Kind() != reflect.Ptr {
  137. return ts, structTagError{typ, f.Name, t, "field is not a pointer"}
  138. }
  139. switch t {
  140. case "nil":
  141. ts.nilKind = defaultNilKind(f.Type.Elem())
  142. case "nilString":
  143. ts.nilKind = String
  144. case "nilList":
  145. ts.nilKind = List
  146. }
  147. case "tail":
  148. ts.tail = true
  149. if fi != lastPublic {
  150. return ts, structTagError{typ, f.Name, t, "must be on last field"}
  151. }
  152. if f.Type.Kind() != reflect.Slice {
  153. return ts, structTagError{typ, f.Name, t, "field type is not slice"}
  154. }
  155. default:
  156. return ts, fmt.Errorf("rlp: unknown struct tag %q on %v.%s", t, typ, f.Name)
  157. }
  158. }
  159. return ts, nil
  160. }
  161. func lastPublicField(typ reflect.Type) int {
  162. last := 0
  163. for i := 0; i < typ.NumField(); i++ {
  164. if typ.Field(i).PkgPath == "" {
  165. last = i
  166. }
  167. }
  168. return last
  169. }
  170. func (i *typeinfo) generate(typ reflect.Type, tags tags) {
  171. i.decoder, i.decoderErr = makeDecoder(typ, tags)
  172. i.writer, i.writerErr = makeWriter(typ, tags)
  173. }
  174. // defaultNilKind determines whether a nil pointer to typ encodes/decodes
  175. // as an empty string or empty list.
  176. func defaultNilKind(typ reflect.Type) Kind {
  177. k := typ.Kind()
  178. if isUint(k) || k == reflect.String || k == reflect.Bool || isByteArray(typ) {
  179. return String
  180. }
  181. return List
  182. }
  183. func isUint(k reflect.Kind) bool {
  184. return k >= reflect.Uint && k <= reflect.Uintptr
  185. }
  186. func isByte(typ reflect.Type) bool {
  187. return typ.Kind() == reflect.Uint8 && !typ.Implements(encoderInterface)
  188. }
  189. func isByteArray(typ reflect.Type) bool {
  190. return (typ.Kind() == reflect.Slice || typ.Kind() == reflect.Array) && isByte(typ.Elem())
  191. }