typecache.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. "sync/atomic"
  23. )
  24. // typeinfo is an entry in the type cache.
  25. type typeinfo struct {
  26. decoder decoder
  27. decoderErr error // error from makeDecoder
  28. writer writer
  29. writerErr error // error from makeWriter
  30. }
  31. // tags represents struct tags.
  32. type tags struct {
  33. // rlp:"nil" controls whether empty input results in a nil pointer.
  34. // nilKind is the kind of empty value allowed for the field.
  35. nilKind Kind
  36. nilOK bool
  37. // rlp:"optional" allows for a field to be missing in the input list.
  38. // If this is set, all subsequent fields must also be optional.
  39. optional bool
  40. // rlp:"tail" controls whether this field swallows additional list elements. It can
  41. // only be set for the last field, which must be of slice type.
  42. tail bool
  43. // rlp:"-" ignores fields.
  44. ignored bool
  45. }
  46. // typekey is the key of a type in typeCache. It includes the struct tags because
  47. // they might generate a different decoder.
  48. type typekey struct {
  49. reflect.Type
  50. tags
  51. }
  52. type decoder func(*Stream, reflect.Value) error
  53. type writer func(reflect.Value, *encbuf) error
  54. var theTC = newTypeCache()
  55. type typeCache struct {
  56. cur atomic.Value
  57. // This lock synchronizes writers.
  58. mu sync.Mutex
  59. next map[typekey]*typeinfo
  60. }
  61. func newTypeCache() *typeCache {
  62. c := new(typeCache)
  63. c.cur.Store(make(map[typekey]*typeinfo))
  64. return c
  65. }
  66. func cachedDecoder(typ reflect.Type) (decoder, error) {
  67. info := theTC.info(typ)
  68. return info.decoder, info.decoderErr
  69. }
  70. func cachedWriter(typ reflect.Type) (writer, error) {
  71. info := theTC.info(typ)
  72. return info.writer, info.writerErr
  73. }
  74. func (c *typeCache) info(typ reflect.Type) *typeinfo {
  75. key := typekey{Type: typ}
  76. if info := c.cur.Load().(map[typekey]*typeinfo)[key]; info != nil {
  77. return info
  78. }
  79. // Not in the cache, need to generate info for this type.
  80. return c.generate(typ, tags{})
  81. }
  82. func (c *typeCache) generate(typ reflect.Type, tags tags) *typeinfo {
  83. c.mu.Lock()
  84. defer c.mu.Unlock()
  85. cur := c.cur.Load().(map[typekey]*typeinfo)
  86. if info := cur[typekey{typ, tags}]; info != nil {
  87. return info
  88. }
  89. // Copy cur to next.
  90. c.next = make(map[typekey]*typeinfo, len(cur)+1)
  91. for k, v := range cur {
  92. c.next[k] = v
  93. }
  94. // Generate.
  95. info := c.infoWhileGenerating(typ, tags)
  96. // next -> cur
  97. c.cur.Store(c.next)
  98. c.next = nil
  99. return info
  100. }
  101. func (c *typeCache) infoWhileGenerating(typ reflect.Type, tags tags) *typeinfo {
  102. key := typekey{typ, tags}
  103. if info := c.next[key]; info != nil {
  104. return info
  105. }
  106. // Put a dummy value into the cache before generating.
  107. // If the generator tries to lookup itself, it will get
  108. // the dummy value and won't call itself recursively.
  109. info := new(typeinfo)
  110. c.next[key] = info
  111. info.generate(typ, tags)
  112. return info
  113. }
  114. type field struct {
  115. index int
  116. info *typeinfo
  117. optional bool
  118. }
  119. // structFields resolves the typeinfo of all public fields in a struct type.
  120. func structFields(typ reflect.Type) (fields []field, err error) {
  121. var (
  122. lastPublic = lastPublicField(typ)
  123. anyOptional = false
  124. )
  125. for i := 0; i < typ.NumField(); i++ {
  126. if f := typ.Field(i); f.PkgPath == "" { // exported
  127. tags, err := parseStructTag(typ, i, lastPublic)
  128. if err != nil {
  129. return nil, err
  130. }
  131. // Skip rlp:"-" fields.
  132. if tags.ignored {
  133. continue
  134. }
  135. // If any field has the "optional" tag, subsequent fields must also have it.
  136. if tags.optional || tags.tail {
  137. anyOptional = true
  138. } else if anyOptional {
  139. return nil, fmt.Errorf(`rlp: struct field %v.%s needs "optional" tag`, typ, f.Name)
  140. }
  141. info := theTC.infoWhileGenerating(f.Type, tags)
  142. fields = append(fields, field{i, info, tags.optional})
  143. }
  144. }
  145. return fields, nil
  146. }
  147. type structFieldError struct {
  148. typ reflect.Type
  149. field int
  150. err error
  151. }
  152. func (e structFieldError) Error() string {
  153. return fmt.Sprintf("%v (struct field %v.%s)", e.err, e.typ, e.typ.Field(e.field).Name)
  154. }
  155. type structTagError struct {
  156. typ reflect.Type
  157. field, tag, err string
  158. }
  159. func (e structTagError) Error() string {
  160. return fmt.Sprintf("rlp: invalid struct tag %q for %v.%s (%s)", e.tag, e.typ, e.field, e.err)
  161. }
  162. func parseStructTag(typ reflect.Type, fi, lastPublic int) (tags, error) {
  163. f := typ.Field(fi)
  164. var ts tags
  165. for _, t := range strings.Split(f.Tag.Get("rlp"), ",") {
  166. switch t = strings.TrimSpace(t); t {
  167. case "":
  168. case "-":
  169. ts.ignored = true
  170. case "nil", "nilString", "nilList":
  171. ts.nilOK = true
  172. if f.Type.Kind() != reflect.Ptr {
  173. return ts, structTagError{typ, f.Name, t, "field is not a pointer"}
  174. }
  175. switch t {
  176. case "nil":
  177. ts.nilKind = defaultNilKind(f.Type.Elem())
  178. case "nilString":
  179. ts.nilKind = String
  180. case "nilList":
  181. ts.nilKind = List
  182. }
  183. case "optional":
  184. ts.optional = true
  185. if ts.tail {
  186. return ts, structTagError{typ, f.Name, t, `also has "tail" tag`}
  187. }
  188. case "tail":
  189. ts.tail = true
  190. if fi != lastPublic {
  191. return ts, structTagError{typ, f.Name, t, "must be on last field"}
  192. }
  193. if ts.optional {
  194. return ts, structTagError{typ, f.Name, t, `also has "optional" tag`}
  195. }
  196. if f.Type.Kind() != reflect.Slice {
  197. return ts, structTagError{typ, f.Name, t, "field type is not slice"}
  198. }
  199. default:
  200. return ts, fmt.Errorf("rlp: unknown struct tag %q on %v.%s", t, typ, f.Name)
  201. }
  202. }
  203. return ts, nil
  204. }
  205. func lastPublicField(typ reflect.Type) int {
  206. last := 0
  207. for i := 0; i < typ.NumField(); i++ {
  208. if typ.Field(i).PkgPath == "" {
  209. last = i
  210. }
  211. }
  212. return last
  213. }
  214. func (i *typeinfo) generate(typ reflect.Type, tags tags) {
  215. i.decoder, i.decoderErr = makeDecoder(typ, tags)
  216. i.writer, i.writerErr = makeWriter(typ, tags)
  217. }
  218. // defaultNilKind determines whether a nil pointer to typ encodes/decodes
  219. // as an empty string or empty list.
  220. func defaultNilKind(typ reflect.Type) Kind {
  221. k := typ.Kind()
  222. if isUint(k) || k == reflect.String || k == reflect.Bool || isByteArray(typ) {
  223. return String
  224. }
  225. return List
  226. }
  227. func isUint(k reflect.Kind) bool {
  228. return k >= reflect.Uint && k <= reflect.Uintptr
  229. }
  230. func isByte(typ reflect.Type) bool {
  231. return typ.Kind() == reflect.Uint8 && !typ.Implements(encoderInterface)
  232. }
  233. func isByteArray(typ reflect.Type) bool {
  234. return (typ.Kind() == reflect.Slice || typ.Kind() == reflect.Array) && isByte(typ.Elem())
  235. }