podman
238 строк · 8.5 Кб
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
7package bsoncodec // import "go.mongodb.org/mongo-driver/bson/bsoncodec"
8
9import (
10"fmt"
11"reflect"
12"strings"
13
14"go.mongodb.org/mongo-driver/bson/bsonrw"
15"go.mongodb.org/mongo-driver/bson/bsontype"
16"go.mongodb.org/mongo-driver/bson/primitive"
17)
18
19var (
20emptyValue = reflect.Value{}
21)
22
23// Marshaler is an interface implemented by types that can marshal themselves
24// into a BSON document represented as bytes. The bytes returned must be a valid
25// BSON document if the error is nil.
26type Marshaler interface {
27MarshalBSON() ([]byte, error)
28}
29
30// ValueMarshaler is an interface implemented by types that can marshal
31// themselves into a BSON value as bytes. The type must be the valid type for
32// the bytes returned. The bytes and byte type together must be valid if the
33// error is nil.
34type ValueMarshaler interface {
35MarshalBSONValue() (bsontype.Type, []byte, error)
36}
37
38// Unmarshaler is an interface implemented by types that can unmarshal a BSON
39// document representation of themselves. The BSON bytes can be assumed to be
40// valid. UnmarshalBSON must copy the BSON bytes if it wishes to retain the data
41// after returning.
42type Unmarshaler interface {
43UnmarshalBSON([]byte) error
44}
45
46// ValueUnmarshaler is an interface implemented by types that can unmarshal a
47// BSON value representation of themselves. The BSON bytes and type can be
48// assumed to be valid. UnmarshalBSONValue must copy the BSON value bytes if it
49// wishes to retain the data after returning.
50type ValueUnmarshaler interface {
51UnmarshalBSONValue(bsontype.Type, []byte) error
52}
53
54// ValueEncoderError is an error returned from a ValueEncoder when the provided value can't be
55// encoded by the ValueEncoder.
56type ValueEncoderError struct {
57Name string
58Types []reflect.Type
59Kinds []reflect.Kind
60Received reflect.Value
61}
62
63func (vee ValueEncoderError) Error() string {
64typeKinds := make([]string, 0, len(vee.Types)+len(vee.Kinds))
65for _, t := range vee.Types {
66typeKinds = append(typeKinds, t.String())
67}
68for _, k := range vee.Kinds {
69if k == reflect.Map {
70typeKinds = append(typeKinds, "map[string]*")
71continue
72}
73typeKinds = append(typeKinds, k.String())
74}
75received := vee.Received.Kind().String()
76if vee.Received.IsValid() {
77received = vee.Received.Type().String()
78}
79return fmt.Sprintf("%s can only encode valid %s, but got %s", vee.Name, strings.Join(typeKinds, ", "), received)
80}
81
82// ValueDecoderError is an error returned from a ValueDecoder when the provided value can't be
83// decoded by the ValueDecoder.
84type ValueDecoderError struct {
85Name string
86Types []reflect.Type
87Kinds []reflect.Kind
88Received reflect.Value
89}
90
91func (vde ValueDecoderError) Error() string {
92typeKinds := make([]string, 0, len(vde.Types)+len(vde.Kinds))
93for _, t := range vde.Types {
94typeKinds = append(typeKinds, t.String())
95}
96for _, k := range vde.Kinds {
97if k == reflect.Map {
98typeKinds = append(typeKinds, "map[string]*")
99continue
100}
101typeKinds = append(typeKinds, k.String())
102}
103received := vde.Received.Kind().String()
104if vde.Received.IsValid() {
105received = vde.Received.Type().String()
106}
107return fmt.Sprintf("%s can only decode valid and settable %s, but got %s", vde.Name, strings.Join(typeKinds, ", "), received)
108}
109
110// EncodeContext is the contextual information required for a Codec to encode a
111// value.
112type EncodeContext struct {
113*Registry
114MinSize bool
115}
116
117// DecodeContext is the contextual information required for a Codec to decode a
118// value.
119type DecodeContext struct {
120*Registry
121Truncate bool
122
123// Ancestor is the type of a containing document. This is mainly used to determine what type
124// should be used when decoding an embedded document into an empty interface. For example, if
125// Ancestor is a bson.M, BSON embedded document values being decoded into an empty interface
126// will be decoded into a bson.M.
127//
128// Deprecated: Use DefaultDocumentM or DefaultDocumentD instead.
129Ancestor reflect.Type
130
131// defaultDocumentType specifies the Go type to decode top-level and nested BSON documents into. In particular, the
132// usage for this field is restricted to data typed as "interface{}" or "map[string]interface{}". If DocumentType is
133// set to a type that a BSON document cannot be unmarshaled into (e.g. "string"), unmarshalling will result in an
134// error. DocumentType overrides the Ancestor field.
135defaultDocumentType reflect.Type
136}
137
138// DefaultDocumentM will decode empty documents using the primitive.M type. This behavior is restricted to data typed as
139// "interface{}" or "map[string]interface{}".
140func (dc *DecodeContext) DefaultDocumentM() {
141dc.defaultDocumentType = reflect.TypeOf(primitive.M{})
142}
143
144// DefaultDocumentD will decode empty documents using the primitive.D type. This behavior is restricted to data typed as
145// "interface{}" or "map[string]interface{}".
146func (dc *DecodeContext) DefaultDocumentD() {
147dc.defaultDocumentType = reflect.TypeOf(primitive.D{})
148}
149
150// ValueCodec is the interface that groups the methods to encode and decode
151// values.
152type ValueCodec interface {
153ValueEncoder
154ValueDecoder
155}
156
157// ValueEncoder is the interface implemented by types that can handle the encoding of a value.
158type ValueEncoder interface {
159EncodeValue(EncodeContext, bsonrw.ValueWriter, reflect.Value) error
160}
161
162// ValueEncoderFunc is an adapter function that allows a function with the correct signature to be
163// used as a ValueEncoder.
164type ValueEncoderFunc func(EncodeContext, bsonrw.ValueWriter, reflect.Value) error
165
166// EncodeValue implements the ValueEncoder interface.
167func (fn ValueEncoderFunc) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
168return fn(ec, vw, val)
169}
170
171// ValueDecoder is the interface implemented by types that can handle the decoding of a value.
172type ValueDecoder interface {
173DecodeValue(DecodeContext, bsonrw.ValueReader, reflect.Value) error
174}
175
176// ValueDecoderFunc is an adapter function that allows a function with the correct signature to be
177// used as a ValueDecoder.
178type ValueDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) error
179
180// DecodeValue implements the ValueDecoder interface.
181func (fn ValueDecoderFunc) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
182return fn(dc, vr, val)
183}
184
185// typeDecoder is the interface implemented by types that can handle the decoding of a value given its type.
186type typeDecoder interface {
187decodeType(DecodeContext, bsonrw.ValueReader, reflect.Type) (reflect.Value, error)
188}
189
190// typeDecoderFunc is an adapter function that allows a function with the correct signature to be used as a typeDecoder.
191type typeDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Type) (reflect.Value, error)
192
193func (fn typeDecoderFunc) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
194return fn(dc, vr, t)
195}
196
197// decodeAdapter allows two functions with the correct signatures to be used as both a ValueDecoder and typeDecoder.
198type decodeAdapter struct {
199ValueDecoderFunc
200typeDecoderFunc
201}
202
203var _ ValueDecoder = decodeAdapter{}
204var _ typeDecoder = decodeAdapter{}
205
206// decodeTypeOrValue calls decoder.decodeType is decoder is a typeDecoder. Otherwise, it allocates a new element of type
207// t and calls decoder.DecodeValue on it.
208func decodeTypeOrValue(decoder ValueDecoder, dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
209td, _ := decoder.(typeDecoder)
210return decodeTypeOrValueWithInfo(decoder, td, dc, vr, t, true)
211}
212
213func decodeTypeOrValueWithInfo(vd ValueDecoder, td typeDecoder, dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type, convert bool) (reflect.Value, error) {
214if td != nil {
215val, err := td.decodeType(dc, vr, t)
216if err == nil && convert && val.Type() != t {
217// This conversion step is necessary for slices and maps. If a user declares variables like:
218//
219// type myBool bool
220// var m map[string]myBool
221//
222// and tries to decode BSON bytes into the map, the decoding will fail if this conversion is not present
223// because we'll try to assign a value of type bool to one of type myBool.
224val = val.Convert(t)
225}
226return val, err
227}
228
229val := reflect.New(t).Elem()
230err := vd.DecodeValue(dc, vr, val)
231return val, err
232}
233
234// CodecZeroer is the interface implemented by Codecs that can also determine if
235// a value of the type that would be encoded is zero.
236type CodecZeroer interface {
237IsTypeZero(interface{}) bool
238}
239