typecache.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. "sync"
  21. "sync/atomic"
  22. "github.com/ethereum/go-ethereum/rlp/internal/rlpstruct"
  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. // typekey is the key of a type in typeCache. It includes the struct tags because
  32. // they might generate a different decoder.
  33. type typekey struct {
  34. reflect.Type
  35. rlpstruct.Tags
  36. }
  37. type decoder func(*Stream, reflect.Value) error
  38. type writer func(reflect.Value, *encBuffer) error
  39. var theTC = newTypeCache()
  40. type typeCache struct {
  41. cur atomic.Value
  42. // This lock synchronizes writers.
  43. mu sync.Mutex
  44. next map[typekey]*typeinfo
  45. }
  46. func newTypeCache() *typeCache {
  47. c := new(typeCache)
  48. c.cur.Store(make(map[typekey]*typeinfo))
  49. return c
  50. }
  51. func cachedDecoder(typ reflect.Type) (decoder, error) {
  52. info := theTC.info(typ)
  53. return info.decoder, info.decoderErr
  54. }
  55. func cachedWriter(typ reflect.Type) (writer, error) {
  56. info := theTC.info(typ)
  57. return info.writer, info.writerErr
  58. }
  59. func (c *typeCache) info(typ reflect.Type) *typeinfo {
  60. key := typekey{Type: typ}
  61. if info := c.cur.Load().(map[typekey]*typeinfo)[key]; info != nil {
  62. return info
  63. }
  64. // Not in the cache, need to generate info for this type.
  65. return c.generate(typ, rlpstruct.Tags{})
  66. }
  67. func (c *typeCache) generate(typ reflect.Type, tags rlpstruct.Tags) *typeinfo {
  68. c.mu.Lock()
  69. defer c.mu.Unlock()
  70. cur := c.cur.Load().(map[typekey]*typeinfo)
  71. if info := cur[typekey{typ, tags}]; info != nil {
  72. return info
  73. }
  74. // Copy cur to next.
  75. c.next = make(map[typekey]*typeinfo, len(cur)+1)
  76. for k, v := range cur {
  77. c.next[k] = v
  78. }
  79. // Generate.
  80. info := c.infoWhileGenerating(typ, tags)
  81. // next -> cur
  82. c.cur.Store(c.next)
  83. c.next = nil
  84. return info
  85. }
  86. func (c *typeCache) infoWhileGenerating(typ reflect.Type, tags rlpstruct.Tags) *typeinfo {
  87. key := typekey{typ, tags}
  88. if info := c.next[key]; info != nil {
  89. return info
  90. }
  91. // Put a dummy value into the cache before generating.
  92. // If the generator tries to lookup itself, it will get
  93. // the dummy value and won't call itself recursively.
  94. info := new(typeinfo)
  95. c.next[key] = info
  96. info.generate(typ, tags)
  97. return info
  98. }
  99. type field struct {
  100. index int
  101. info *typeinfo
  102. optional bool
  103. }
  104. // structFields resolves the typeinfo of all public fields in a struct type.
  105. func structFields(typ reflect.Type) (fields []field, err error) {
  106. // Convert fields to rlpstruct.Field.
  107. var allStructFields []rlpstruct.Field
  108. for i := 0; i < typ.NumField(); i++ {
  109. rf := typ.Field(i)
  110. allStructFields = append(allStructFields, rlpstruct.Field{
  111. Name: rf.Name,
  112. Index: i,
  113. Exported: rf.PkgPath == "",
  114. Tag: string(rf.Tag),
  115. Type: *rtypeToStructType(rf.Type, nil),
  116. })
  117. }
  118. // Filter/validate fields.
  119. structFields, structTags, err := rlpstruct.ProcessFields(allStructFields)
  120. if err != nil {
  121. if tagErr, ok := err.(rlpstruct.TagError); ok {
  122. tagErr.StructType = typ.String()
  123. return nil, tagErr
  124. }
  125. return nil, err
  126. }
  127. // Resolve typeinfo.
  128. for i, sf := range structFields {
  129. typ := typ.Field(sf.Index).Type
  130. tags := structTags[i]
  131. info := theTC.infoWhileGenerating(typ, tags)
  132. fields = append(fields, field{sf.Index, info, tags.Optional})
  133. }
  134. return fields, nil
  135. }
  136. // firstOptionalField returns the index of the first field with "optional" tag.
  137. func firstOptionalField(fields []field) int {
  138. for i, f := range fields {
  139. if f.optional {
  140. return i
  141. }
  142. }
  143. return len(fields)
  144. }
  145. type structFieldError struct {
  146. typ reflect.Type
  147. field int
  148. err error
  149. }
  150. func (e structFieldError) Error() string {
  151. return fmt.Sprintf("%v (struct field %v.%s)", e.err, e.typ, e.typ.Field(e.field).Name)
  152. }
  153. func (i *typeinfo) generate(typ reflect.Type, tags rlpstruct.Tags) {
  154. i.decoder, i.decoderErr = makeDecoder(typ, tags)
  155. i.writer, i.writerErr = makeWriter(typ, tags)
  156. }
  157. // rtypeToStructType converts typ to rlpstruct.Type.
  158. func rtypeToStructType(typ reflect.Type, rec map[reflect.Type]*rlpstruct.Type) *rlpstruct.Type {
  159. k := typ.Kind()
  160. if k == reflect.Invalid {
  161. panic("invalid kind")
  162. }
  163. if prev := rec[typ]; prev != nil {
  164. return prev // short-circuit for recursive types
  165. }
  166. if rec == nil {
  167. rec = make(map[reflect.Type]*rlpstruct.Type)
  168. }
  169. t := &rlpstruct.Type{
  170. Name: typ.String(),
  171. Kind: k,
  172. IsEncoder: typ.Implements(encoderInterface),
  173. IsDecoder: typ.Implements(decoderInterface),
  174. }
  175. rec[typ] = t
  176. if k == reflect.Array || k == reflect.Slice || k == reflect.Ptr {
  177. t.Elem = rtypeToStructType(typ.Elem(), rec)
  178. }
  179. return t
  180. }
  181. // typeNilKind gives the RLP value kind for nil pointers to 'typ'.
  182. func typeNilKind(typ reflect.Type, tags rlpstruct.Tags) Kind {
  183. styp := rtypeToStructType(typ, nil)
  184. var nk rlpstruct.NilKind
  185. if tags.NilOK {
  186. nk = tags.NilKind
  187. } else {
  188. nk = styp.DefaultNilValue()
  189. }
  190. switch nk {
  191. case rlpstruct.NilKindString:
  192. return String
  193. case rlpstruct.NilKindList:
  194. return List
  195. default:
  196. panic("invalid nil kind value")
  197. }
  198. }
  199. func isUint(k reflect.Kind) bool {
  200. return k >= reflect.Uint && k <= reflect.Uintptr
  201. }
  202. func isByte(typ reflect.Type) bool {
  203. return typ.Kind() == reflect.Uint8 && !typ.Implements(encoderInterface)
  204. }