本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

385 lines
11KB

  1. // Copyright (C) MongoDB, Inc. 2017-present.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  6. package bsoncodec
  7. import (
  8. "errors"
  9. "reflect"
  10. "sync"
  11. "go.mongodb.org/mongo-driver/bson/bsontype"
  12. )
  13. // ErrNilType is returned when nil is passed to either LookupEncoder or LookupDecoder.
  14. var ErrNilType = errors.New("cannot perform a decoder lookup on <nil>")
  15. // ErrNotPointer is returned when a non-pointer type is provided to LookupDecoder.
  16. var ErrNotPointer = errors.New("non-pointer provided to LookupDecoder")
  17. // ErrNoEncoder is returned when there wasn't an encoder available for a type.
  18. type ErrNoEncoder struct {
  19. Type reflect.Type
  20. }
  21. func (ene ErrNoEncoder) Error() string {
  22. if ene.Type == nil {
  23. return "no encoder found for <nil>"
  24. }
  25. return "no encoder found for " + ene.Type.String()
  26. }
  27. // ErrNoDecoder is returned when there wasn't a decoder available for a type.
  28. type ErrNoDecoder struct {
  29. Type reflect.Type
  30. }
  31. func (end ErrNoDecoder) Error() string {
  32. return "no decoder found for " + end.Type.String()
  33. }
  34. // ErrNoTypeMapEntry is returned when there wasn't a type available for the provided BSON type.
  35. type ErrNoTypeMapEntry struct {
  36. Type bsontype.Type
  37. }
  38. func (entme ErrNoTypeMapEntry) Error() string {
  39. return "no type map entry found for " + entme.Type.String()
  40. }
  41. // ErrNotInterface is returned when the provided type is not an interface.
  42. var ErrNotInterface = errors.New("The provided type is not an interface")
  43. var defaultRegistry *Registry
  44. func init() {
  45. defaultRegistry = buildDefaultRegistry()
  46. }
  47. // A RegistryBuilder is used to build a Registry. This type is not goroutine
  48. // safe.
  49. type RegistryBuilder struct {
  50. typeEncoders map[reflect.Type]ValueEncoder
  51. interfaceEncoders []interfaceValueEncoder
  52. kindEncoders map[reflect.Kind]ValueEncoder
  53. typeDecoders map[reflect.Type]ValueDecoder
  54. interfaceDecoders []interfaceValueDecoder
  55. kindDecoders map[reflect.Kind]ValueDecoder
  56. typeMap map[bsontype.Type]reflect.Type
  57. }
  58. // A Registry is used to store and retrieve codecs for types and interfaces. This type is the main
  59. // typed passed around and Encoders and Decoders are constructed from it.
  60. type Registry struct {
  61. typeEncoders map[reflect.Type]ValueEncoder
  62. typeDecoders map[reflect.Type]ValueDecoder
  63. interfaceEncoders []interfaceValueEncoder
  64. interfaceDecoders []interfaceValueDecoder
  65. kindEncoders map[reflect.Kind]ValueEncoder
  66. kindDecoders map[reflect.Kind]ValueDecoder
  67. typeMap map[bsontype.Type]reflect.Type
  68. mu sync.RWMutex
  69. }
  70. // NewRegistryBuilder creates a new empty RegistryBuilder.
  71. func NewRegistryBuilder() *RegistryBuilder {
  72. return &RegistryBuilder{
  73. typeEncoders: make(map[reflect.Type]ValueEncoder),
  74. typeDecoders: make(map[reflect.Type]ValueDecoder),
  75. interfaceEncoders: make([]interfaceValueEncoder, 0),
  76. interfaceDecoders: make([]interfaceValueDecoder, 0),
  77. kindEncoders: make(map[reflect.Kind]ValueEncoder),
  78. kindDecoders: make(map[reflect.Kind]ValueDecoder),
  79. typeMap: make(map[bsontype.Type]reflect.Type),
  80. }
  81. }
  82. func buildDefaultRegistry() *Registry {
  83. rb := NewRegistryBuilder()
  84. defaultValueEncoders.RegisterDefaultEncoders(rb)
  85. defaultValueDecoders.RegisterDefaultDecoders(rb)
  86. return rb.Build()
  87. }
  88. // RegisterCodec will register the provided ValueCodec for the provided type.
  89. func (rb *RegistryBuilder) RegisterCodec(t reflect.Type, codec ValueCodec) *RegistryBuilder {
  90. rb.RegisterEncoder(t, codec)
  91. rb.RegisterDecoder(t, codec)
  92. return rb
  93. }
  94. // RegisterEncoder will register the provided ValueEncoder to the provided type.
  95. //
  96. // The type registered will be used directly, so an encoder can be registered for a type and a
  97. // different encoder can be registered for a pointer to that type.
  98. func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder {
  99. if t == tEmpty {
  100. rb.typeEncoders[t] = enc
  101. return rb
  102. }
  103. switch t.Kind() {
  104. case reflect.Interface:
  105. for idx, ir := range rb.interfaceEncoders {
  106. if ir.i == t {
  107. rb.interfaceEncoders[idx].ve = enc
  108. return rb
  109. }
  110. }
  111. rb.interfaceEncoders = append(rb.interfaceEncoders, interfaceValueEncoder{i: t, ve: enc})
  112. default:
  113. rb.typeEncoders[t] = enc
  114. }
  115. return rb
  116. }
  117. // RegisterDecoder will register the provided ValueDecoder to the provided type.
  118. //
  119. // The type registered will be used directly, so a decoder can be registered for a type and a
  120. // different decoder can be registered for a pointer to that type.
  121. func (rb *RegistryBuilder) RegisterDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder {
  122. if t == nil {
  123. rb.typeDecoders[nil] = dec
  124. return rb
  125. }
  126. if t == tEmpty {
  127. rb.typeDecoders[t] = dec
  128. return rb
  129. }
  130. switch t.Kind() {
  131. case reflect.Interface:
  132. for idx, ir := range rb.interfaceDecoders {
  133. if ir.i == t {
  134. rb.interfaceDecoders[idx].vd = dec
  135. return rb
  136. }
  137. }
  138. rb.interfaceDecoders = append(rb.interfaceDecoders, interfaceValueDecoder{i: t, vd: dec})
  139. default:
  140. rb.typeDecoders[t] = dec
  141. }
  142. return rb
  143. }
  144. // RegisterDefaultEncoder will registr the provided ValueEncoder to the provided
  145. // kind.
  146. func (rb *RegistryBuilder) RegisterDefaultEncoder(kind reflect.Kind, enc ValueEncoder) *RegistryBuilder {
  147. rb.kindEncoders[kind] = enc
  148. return rb
  149. }
  150. // RegisterDefaultDecoder will register the provided ValueDecoder to the
  151. // provided kind.
  152. func (rb *RegistryBuilder) RegisterDefaultDecoder(kind reflect.Kind, dec ValueDecoder) *RegistryBuilder {
  153. rb.kindDecoders[kind] = dec
  154. return rb
  155. }
  156. // RegisterTypeMapEntry will register the provided type to the BSON type. The primary usage for this
  157. // mapping is decoding situations where an empty interface is used and a default type needs to be
  158. // created and decoded into.
  159. //
  160. // NOTE: It is unlikely that registering a type for BSON Embedded Document is actually desired. By
  161. // registering a type map entry for BSON Embedded Document the type registered will be used in any
  162. // case where a BSON Embedded Document will be decoded into an empty interface. For example, if you
  163. // register primitive.M, the EmptyInterface decoder will always use primitive.M, even if an ancestor
  164. // was a primitive.D.
  165. func (rb *RegistryBuilder) RegisterTypeMapEntry(bt bsontype.Type, rt reflect.Type) *RegistryBuilder {
  166. rb.typeMap[bt] = rt
  167. return rb
  168. }
  169. // Build creates a Registry from the current state of this RegistryBuilder.
  170. func (rb *RegistryBuilder) Build() *Registry {
  171. registry := new(Registry)
  172. registry.typeEncoders = make(map[reflect.Type]ValueEncoder)
  173. for t, enc := range rb.typeEncoders {
  174. registry.typeEncoders[t] = enc
  175. }
  176. registry.typeDecoders = make(map[reflect.Type]ValueDecoder)
  177. for t, dec := range rb.typeDecoders {
  178. registry.typeDecoders[t] = dec
  179. }
  180. registry.interfaceEncoders = make([]interfaceValueEncoder, len(rb.interfaceEncoders))
  181. copy(registry.interfaceEncoders, rb.interfaceEncoders)
  182. registry.interfaceDecoders = make([]interfaceValueDecoder, len(rb.interfaceDecoders))
  183. copy(registry.interfaceDecoders, rb.interfaceDecoders)
  184. registry.kindEncoders = make(map[reflect.Kind]ValueEncoder)
  185. for kind, enc := range rb.kindEncoders {
  186. registry.kindEncoders[kind] = enc
  187. }
  188. registry.kindDecoders = make(map[reflect.Kind]ValueDecoder)
  189. for kind, dec := range rb.kindDecoders {
  190. registry.kindDecoders[kind] = dec
  191. }
  192. registry.typeMap = make(map[bsontype.Type]reflect.Type)
  193. for bt, rt := range rb.typeMap {
  194. registry.typeMap[bt] = rt
  195. }
  196. return registry
  197. }
  198. // LookupEncoder will inspect the registry for an encoder that satisfies the
  199. // type provided. An encoder registered for a specific type will take
  200. // precedence over an encoder registered for an interface the type satisfies,
  201. // which takes precedence over an encoder for the reflect.Kind of the value. If
  202. // no encoder can be found, an error is returned.
  203. func (r *Registry) LookupEncoder(t reflect.Type) (ValueEncoder, error) {
  204. encodererr := ErrNoEncoder{Type: t}
  205. r.mu.RLock()
  206. enc, found := r.lookupTypeEncoder(t)
  207. r.mu.RUnlock()
  208. if found {
  209. if enc == nil {
  210. return nil, ErrNoEncoder{Type: t}
  211. }
  212. return enc, nil
  213. }
  214. enc, found = r.lookupInterfaceEncoder(t)
  215. if found {
  216. r.mu.Lock()
  217. r.typeEncoders[t] = enc
  218. r.mu.Unlock()
  219. return enc, nil
  220. }
  221. if t == nil {
  222. r.mu.Lock()
  223. r.typeEncoders[t] = nil
  224. r.mu.Unlock()
  225. return nil, encodererr
  226. }
  227. enc, found = r.kindEncoders[t.Kind()]
  228. if !found {
  229. r.mu.Lock()
  230. r.typeEncoders[t] = nil
  231. r.mu.Unlock()
  232. return nil, encodererr
  233. }
  234. r.mu.Lock()
  235. r.typeEncoders[t] = enc
  236. r.mu.Unlock()
  237. return enc, nil
  238. }
  239. func (r *Registry) lookupTypeEncoder(t reflect.Type) (ValueEncoder, bool) {
  240. enc, found := r.typeEncoders[t]
  241. return enc, found
  242. }
  243. func (r *Registry) lookupInterfaceEncoder(t reflect.Type) (ValueEncoder, bool) {
  244. if t == nil {
  245. return nil, false
  246. }
  247. for _, ienc := range r.interfaceEncoders {
  248. if !t.Implements(ienc.i) {
  249. continue
  250. }
  251. return ienc.ve, true
  252. }
  253. return nil, false
  254. }
  255. // LookupDecoder will inspect the registry for a decoder that satisfies the
  256. // type provided. A decoder registered for a specific type will take
  257. // precedence over a decoder registered for an interface the type satisfies,
  258. // which takes precedence over a decoder for the reflect.Kind of the value. If
  259. // no decoder can be found, an error is returned.
  260. func (r *Registry) LookupDecoder(t reflect.Type) (ValueDecoder, error) {
  261. if t == nil {
  262. return nil, ErrNilType
  263. }
  264. decodererr := ErrNoDecoder{Type: t}
  265. r.mu.RLock()
  266. dec, found := r.lookupTypeDecoder(t)
  267. r.mu.RUnlock()
  268. if found {
  269. if dec == nil {
  270. return nil, ErrNoDecoder{Type: t}
  271. }
  272. return dec, nil
  273. }
  274. dec, found = r.lookupInterfaceDecoder(t)
  275. if found {
  276. r.mu.Lock()
  277. r.typeDecoders[t] = dec
  278. r.mu.Unlock()
  279. return dec, nil
  280. }
  281. dec, found = r.kindDecoders[t.Kind()]
  282. if !found {
  283. r.mu.Lock()
  284. r.typeDecoders[t] = nil
  285. r.mu.Unlock()
  286. return nil, decodererr
  287. }
  288. r.mu.Lock()
  289. r.typeDecoders[t] = dec
  290. r.mu.Unlock()
  291. return dec, nil
  292. }
  293. func (r *Registry) lookupTypeDecoder(t reflect.Type) (ValueDecoder, bool) {
  294. dec, found := r.typeDecoders[t]
  295. return dec, found
  296. }
  297. func (r *Registry) lookupInterfaceDecoder(t reflect.Type) (ValueDecoder, bool) {
  298. for _, idec := range r.interfaceDecoders {
  299. if !t.Implements(idec.i) && !reflect.PtrTo(t).Implements(idec.i) {
  300. continue
  301. }
  302. return idec.vd, true
  303. }
  304. return nil, false
  305. }
  306. // LookupTypeMapEntry inspects the registry's type map for a Go type for the corresponding BSON
  307. // type. If no type is found, ErrNoTypeMapEntry is returned.
  308. func (r *Registry) LookupTypeMapEntry(bt bsontype.Type) (reflect.Type, error) {
  309. t, ok := r.typeMap[bt]
  310. if !ok || t == nil {
  311. return nil, ErrNoTypeMapEntry{Type: bt}
  312. }
  313. return t, nil
  314. }
  315. type interfaceValueEncoder struct {
  316. i reflect.Type
  317. ve ValueEncoder
  318. }
  319. type interfaceValueDecoder struct {
  320. i reflect.Type
  321. vd ValueDecoder
  322. }
上海开阖软件有限公司 沪ICP备12045867号-1