bsoncodec.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 // import "go.mongodb.org/mongo-driver/bson/bsoncodec"
  7. import (
  8. "fmt"
  9. "reflect"
  10. "strings"
  11. "go.mongodb.org/mongo-driver/bson/bsonrw"
  12. "go.mongodb.org/mongo-driver/bson/bsontype"
  13. "go.mongodb.org/mongo-driver/bson/primitive"
  14. )
  15. var (
  16. emptyValue = reflect.Value{}
  17. )
  18. // Marshaler is an interface implemented by types that can marshal themselves
  19. // into a BSON document represented as bytes. The bytes returned must be a valid
  20. // BSON document if the error is nil.
  21. //
  22. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Marshaler] instead.
  23. type Marshaler interface {
  24. MarshalBSON() ([]byte, error)
  25. }
  26. // ValueMarshaler is an interface implemented by types that can marshal
  27. // themselves into a BSON value as bytes. The type must be the valid type for
  28. // the bytes returned. The bytes and byte type together must be valid if the
  29. // error is nil.
  30. //
  31. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.ValueMarshaler] instead.
  32. type ValueMarshaler interface {
  33. MarshalBSONValue() (bsontype.Type, []byte, error)
  34. }
  35. // Unmarshaler is an interface implemented by types that can unmarshal a BSON
  36. // document representation of themselves. The BSON bytes can be assumed to be
  37. // valid. UnmarshalBSON must copy the BSON bytes if it wishes to retain the data
  38. // after returning.
  39. //
  40. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Unmarshaler] instead.
  41. type Unmarshaler interface {
  42. UnmarshalBSON([]byte) error
  43. }
  44. // ValueUnmarshaler is an interface implemented by types that can unmarshal a
  45. // BSON value representation of themselves. The BSON bytes and type can be
  46. // assumed to be valid. UnmarshalBSONValue must copy the BSON value bytes if it
  47. // wishes to retain the data after returning.
  48. //
  49. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.ValueUnmarshaler] instead.
  50. type ValueUnmarshaler interface {
  51. UnmarshalBSONValue(bsontype.Type, []byte) error
  52. }
  53. // ValueEncoderError is an error returned from a ValueEncoder when the provided value can't be
  54. // encoded by the ValueEncoder.
  55. type ValueEncoderError struct {
  56. Name string
  57. Types []reflect.Type
  58. Kinds []reflect.Kind
  59. Received reflect.Value
  60. }
  61. func (vee ValueEncoderError) Error() string {
  62. typeKinds := make([]string, 0, len(vee.Types)+len(vee.Kinds))
  63. for _, t := range vee.Types {
  64. typeKinds = append(typeKinds, t.String())
  65. }
  66. for _, k := range vee.Kinds {
  67. if k == reflect.Map {
  68. typeKinds = append(typeKinds, "map[string]*")
  69. continue
  70. }
  71. typeKinds = append(typeKinds, k.String())
  72. }
  73. received := vee.Received.Kind().String()
  74. if vee.Received.IsValid() {
  75. received = vee.Received.Type().String()
  76. }
  77. return fmt.Sprintf("%s can only encode valid %s, but got %s", vee.Name, strings.Join(typeKinds, ", "), received)
  78. }
  79. // ValueDecoderError is an error returned from a ValueDecoder when the provided value can't be
  80. // decoded by the ValueDecoder.
  81. type ValueDecoderError struct {
  82. Name string
  83. Types []reflect.Type
  84. Kinds []reflect.Kind
  85. Received reflect.Value
  86. }
  87. func (vde ValueDecoderError) Error() string {
  88. typeKinds := make([]string, 0, len(vde.Types)+len(vde.Kinds))
  89. for _, t := range vde.Types {
  90. typeKinds = append(typeKinds, t.String())
  91. }
  92. for _, k := range vde.Kinds {
  93. if k == reflect.Map {
  94. typeKinds = append(typeKinds, "map[string]*")
  95. continue
  96. }
  97. typeKinds = append(typeKinds, k.String())
  98. }
  99. received := vde.Received.Kind().String()
  100. if vde.Received.IsValid() {
  101. received = vde.Received.Type().String()
  102. }
  103. return fmt.Sprintf("%s can only decode valid and settable %s, but got %s", vde.Name, strings.Join(typeKinds, ", "), received)
  104. }
  105. // EncodeContext is the contextual information required for a Codec to encode a
  106. // value.
  107. type EncodeContext struct {
  108. *Registry
  109. // MinSize causes the Encoder to marshal Go integer values (int, int8, int16, int32, int64,
  110. // uint, uint8, uint16, uint32, or uint64) as the minimum BSON int size (either 32 or 64 bits)
  111. // that can represent the integer value.
  112. //
  113. // Deprecated: Use bson.Encoder.IntMinSize instead.
  114. MinSize bool
  115. errorOnInlineDuplicates bool
  116. stringifyMapKeysWithFmt bool
  117. nilMapAsEmpty bool
  118. nilSliceAsEmpty bool
  119. nilByteSliceAsEmpty bool
  120. omitZeroStruct bool
  121. useJSONStructTags bool
  122. }
  123. // ErrorOnInlineDuplicates causes the Encoder to return an error if there is a duplicate field in
  124. // the marshaled BSON when the "inline" struct tag option is set.
  125. //
  126. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.ErrorOnInlineDuplicates] instead.
  127. func (ec *EncodeContext) ErrorOnInlineDuplicates() {
  128. ec.errorOnInlineDuplicates = true
  129. }
  130. // StringifyMapKeysWithFmt causes the Encoder to convert Go map keys to BSON document field name
  131. // strings using fmt.Sprintf() instead of the default string conversion logic.
  132. //
  133. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.StringifyMapKeysWithFmt] instead.
  134. func (ec *EncodeContext) StringifyMapKeysWithFmt() {
  135. ec.stringifyMapKeysWithFmt = true
  136. }
  137. // NilMapAsEmpty causes the Encoder to marshal nil Go maps as empty BSON documents instead of BSON
  138. // null.
  139. //
  140. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.NilMapAsEmpty] instead.
  141. func (ec *EncodeContext) NilMapAsEmpty() {
  142. ec.nilMapAsEmpty = true
  143. }
  144. // NilSliceAsEmpty causes the Encoder to marshal nil Go slices as empty BSON arrays instead of BSON
  145. // null.
  146. //
  147. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.NilSliceAsEmpty] instead.
  148. func (ec *EncodeContext) NilSliceAsEmpty() {
  149. ec.nilSliceAsEmpty = true
  150. }
  151. // NilByteSliceAsEmpty causes the Encoder to marshal nil Go byte slices as empty BSON binary values
  152. // instead of BSON null.
  153. //
  154. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.NilByteSliceAsEmpty] instead.
  155. func (ec *EncodeContext) NilByteSliceAsEmpty() {
  156. ec.nilByteSliceAsEmpty = true
  157. }
  158. // OmitZeroStruct causes the Encoder to consider the zero value for a struct (e.g. MyStruct{})
  159. // as empty and omit it from the marshaled BSON when the "omitempty" struct tag option is set.
  160. //
  161. // Note that the Encoder only examines exported struct fields when determining if a struct is the
  162. // zero value. It considers pointers to a zero struct value (e.g. &MyStruct{}) not empty.
  163. //
  164. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.OmitZeroStruct] instead.
  165. func (ec *EncodeContext) OmitZeroStruct() {
  166. ec.omitZeroStruct = true
  167. }
  168. // UseJSONStructTags causes the Encoder to fall back to using the "json" struct tag if a "bson"
  169. // struct tag is not specified.
  170. //
  171. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Encoder.UseJSONStructTags] instead.
  172. func (ec *EncodeContext) UseJSONStructTags() {
  173. ec.useJSONStructTags = true
  174. }
  175. // DecodeContext is the contextual information required for a Codec to decode a
  176. // value.
  177. type DecodeContext struct {
  178. *Registry
  179. // Truncate, if true, instructs decoders to to truncate the fractional part of BSON "double"
  180. // values when attempting to unmarshal them into a Go integer (int, int8, int16, int32, int64,
  181. // uint, uint8, uint16, uint32, or uint64) struct field. The truncation logic does not apply to
  182. // BSON "decimal128" values.
  183. //
  184. // Deprecated: Use bson.Decoder.AllowTruncatingDoubles instead.
  185. Truncate bool
  186. // Ancestor is the type of a containing document. This is mainly used to determine what type
  187. // should be used when decoding an embedded document into an empty interface. For example, if
  188. // Ancestor is a bson.M, BSON embedded document values being decoded into an empty interface
  189. // will be decoded into a bson.M.
  190. //
  191. // Deprecated: Use bson.Decoder.DefaultDocumentM or bson.Decoder.DefaultDocumentD instead.
  192. Ancestor reflect.Type
  193. // defaultDocumentType specifies the Go type to decode top-level and nested BSON documents into. In particular, the
  194. // usage for this field is restricted to data typed as "interface{}" or "map[string]interface{}". If DocumentType is
  195. // set to a type that a BSON document cannot be unmarshaled into (e.g. "string"), unmarshalling will result in an
  196. // error. DocumentType overrides the Ancestor field.
  197. defaultDocumentType reflect.Type
  198. binaryAsSlice bool
  199. useJSONStructTags bool
  200. useLocalTimeZone bool
  201. zeroMaps bool
  202. zeroStructs bool
  203. }
  204. // BinaryAsSlice causes the Decoder to unmarshal BSON binary field values that are the "Generic" or
  205. // "Old" BSON binary subtype as a Go byte slice instead of a primitive.Binary.
  206. //
  207. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.BinaryAsSlice] instead.
  208. func (dc *DecodeContext) BinaryAsSlice() {
  209. dc.binaryAsSlice = true
  210. }
  211. // UseJSONStructTags causes the Decoder to fall back to using the "json" struct tag if a "bson"
  212. // struct tag is not specified.
  213. //
  214. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.UseJSONStructTags] instead.
  215. func (dc *DecodeContext) UseJSONStructTags() {
  216. dc.useJSONStructTags = true
  217. }
  218. // UseLocalTimeZone causes the Decoder to unmarshal time.Time values in the local timezone instead
  219. // of the UTC timezone.
  220. //
  221. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.UseLocalTimeZone] instead.
  222. func (dc *DecodeContext) UseLocalTimeZone() {
  223. dc.useLocalTimeZone = true
  224. }
  225. // ZeroMaps causes the Decoder to delete any existing values from Go maps in the destination value
  226. // passed to Decode before unmarshaling BSON documents into them.
  227. //
  228. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.ZeroMaps] instead.
  229. func (dc *DecodeContext) ZeroMaps() {
  230. dc.zeroMaps = true
  231. }
  232. // ZeroStructs causes the Decoder to delete any existing values from Go structs in the destination
  233. // value passed to Decode before unmarshaling BSON documents into them.
  234. //
  235. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.ZeroStructs] instead.
  236. func (dc *DecodeContext) ZeroStructs() {
  237. dc.zeroStructs = true
  238. }
  239. // DefaultDocumentM causes the Decoder to always unmarshal documents into the primitive.M type. This
  240. // behavior is restricted to data typed as "interface{}" or "map[string]interface{}".
  241. //
  242. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.DefaultDocumentM] instead.
  243. func (dc *DecodeContext) DefaultDocumentM() {
  244. dc.defaultDocumentType = reflect.TypeOf(primitive.M{})
  245. }
  246. // DefaultDocumentD causes the Decoder to always unmarshal documents into the primitive.D type. This
  247. // behavior is restricted to data typed as "interface{}" or "map[string]interface{}".
  248. //
  249. // Deprecated: Use [go.mongodb.org/mongo-driver/bson.Decoder.DefaultDocumentD] instead.
  250. func (dc *DecodeContext) DefaultDocumentD() {
  251. dc.defaultDocumentType = reflect.TypeOf(primitive.D{})
  252. }
  253. // ValueCodec is an interface for encoding and decoding a reflect.Value.
  254. // values.
  255. //
  256. // Deprecated: Use [ValueEncoder] and [ValueDecoder] instead.
  257. type ValueCodec interface {
  258. ValueEncoder
  259. ValueDecoder
  260. }
  261. // ValueEncoder is the interface implemented by types that can handle the encoding of a value.
  262. type ValueEncoder interface {
  263. EncodeValue(EncodeContext, bsonrw.ValueWriter, reflect.Value) error
  264. }
  265. // ValueEncoderFunc is an adapter function that allows a function with the correct signature to be
  266. // used as a ValueEncoder.
  267. type ValueEncoderFunc func(EncodeContext, bsonrw.ValueWriter, reflect.Value) error
  268. // EncodeValue implements the ValueEncoder interface.
  269. func (fn ValueEncoderFunc) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
  270. return fn(ec, vw, val)
  271. }
  272. // ValueDecoder is the interface implemented by types that can handle the decoding of a value.
  273. type ValueDecoder interface {
  274. DecodeValue(DecodeContext, bsonrw.ValueReader, reflect.Value) error
  275. }
  276. // ValueDecoderFunc is an adapter function that allows a function with the correct signature to be
  277. // used as a ValueDecoder.
  278. type ValueDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) error
  279. // DecodeValue implements the ValueDecoder interface.
  280. func (fn ValueDecoderFunc) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
  281. return fn(dc, vr, val)
  282. }
  283. // typeDecoder is the interface implemented by types that can handle the decoding of a value given its type.
  284. type typeDecoder interface {
  285. decodeType(DecodeContext, bsonrw.ValueReader, reflect.Type) (reflect.Value, error)
  286. }
  287. // typeDecoderFunc is an adapter function that allows a function with the correct signature to be used as a typeDecoder.
  288. type typeDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Type) (reflect.Value, error)
  289. func (fn typeDecoderFunc) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
  290. return fn(dc, vr, t)
  291. }
  292. // decodeAdapter allows two functions with the correct signatures to be used as both a ValueDecoder and typeDecoder.
  293. type decodeAdapter struct {
  294. ValueDecoderFunc
  295. typeDecoderFunc
  296. }
  297. var _ ValueDecoder = decodeAdapter{}
  298. var _ typeDecoder = decodeAdapter{}
  299. // decodeTypeOrValue calls decoder.decodeType is decoder is a typeDecoder. Otherwise, it allocates a new element of type
  300. // t and calls decoder.DecodeValue on it.
  301. func decodeTypeOrValue(decoder ValueDecoder, dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
  302. td, _ := decoder.(typeDecoder)
  303. return decodeTypeOrValueWithInfo(decoder, td, dc, vr, t, true)
  304. }
  305. func decodeTypeOrValueWithInfo(vd ValueDecoder, td typeDecoder, dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type, convert bool) (reflect.Value, error) {
  306. if td != nil {
  307. val, err := td.decodeType(dc, vr, t)
  308. if err == nil && convert && val.Type() != t {
  309. // This conversion step is necessary for slices and maps. If a user declares variables like:
  310. //
  311. // type myBool bool
  312. // var m map[string]myBool
  313. //
  314. // and tries to decode BSON bytes into the map, the decoding will fail if this conversion is not present
  315. // because we'll try to assign a value of type bool to one of type myBool.
  316. val = val.Convert(t)
  317. }
  318. return val, err
  319. }
  320. val := reflect.New(t).Elem()
  321. err := vd.DecodeValue(dc, vr, val)
  322. return val, err
  323. }
  324. // CodecZeroer is the interface implemented by Codecs that can also determine if
  325. // a value of the type that would be encoded is zero.
  326. //
  327. // Deprecated: Defining custom rules for the zero/empty value will not be supported in Go Driver
  328. // 2.0. Users who want to omit empty complex values should use a pointer field and set the value to
  329. // nil instead.
  330. type CodecZeroer interface {
  331. IsTypeZero(interface{}) bool
  332. }