podman

Форк
0
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

7
package bsoncodec // import "go.mongodb.org/mongo-driver/bson/bsoncodec"
8

9
import (
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

19
var (
20
	emptyValue = 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.
26
type Marshaler interface {
27
	MarshalBSON() ([]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.
34
type ValueMarshaler interface {
35
	MarshalBSONValue() (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.
42
type Unmarshaler interface {
43
	UnmarshalBSON([]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.
50
type ValueUnmarshaler interface {
51
	UnmarshalBSONValue(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.
56
type ValueEncoderError struct {
57
	Name     string
58
	Types    []reflect.Type
59
	Kinds    []reflect.Kind
60
	Received reflect.Value
61
}
62

63
func (vee ValueEncoderError) Error() string {
64
	typeKinds := make([]string, 0, len(vee.Types)+len(vee.Kinds))
65
	for _, t := range vee.Types {
66
		typeKinds = append(typeKinds, t.String())
67
	}
68
	for _, k := range vee.Kinds {
69
		if k == reflect.Map {
70
			typeKinds = append(typeKinds, "map[string]*")
71
			continue
72
		}
73
		typeKinds = append(typeKinds, k.String())
74
	}
75
	received := vee.Received.Kind().String()
76
	if vee.Received.IsValid() {
77
		received = vee.Received.Type().String()
78
	}
79
	return 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.
84
type ValueDecoderError struct {
85
	Name     string
86
	Types    []reflect.Type
87
	Kinds    []reflect.Kind
88
	Received reflect.Value
89
}
90

91
func (vde ValueDecoderError) Error() string {
92
	typeKinds := make([]string, 0, len(vde.Types)+len(vde.Kinds))
93
	for _, t := range vde.Types {
94
		typeKinds = append(typeKinds, t.String())
95
	}
96
	for _, k := range vde.Kinds {
97
		if k == reflect.Map {
98
			typeKinds = append(typeKinds, "map[string]*")
99
			continue
100
		}
101
		typeKinds = append(typeKinds, k.String())
102
	}
103
	received := vde.Received.Kind().String()
104
	if vde.Received.IsValid() {
105
		received = vde.Received.Type().String()
106
	}
107
	return 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.
112
type EncodeContext struct {
113
	*Registry
114
	MinSize bool
115
}
116

117
// DecodeContext is the contextual information required for a Codec to decode a
118
// value.
119
type DecodeContext struct {
120
	*Registry
121
	Truncate 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.
129
	Ancestor 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.
135
	defaultDocumentType 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{}".
140
func (dc *DecodeContext) DefaultDocumentM() {
141
	dc.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{}".
146
func (dc *DecodeContext) DefaultDocumentD() {
147
	dc.defaultDocumentType = reflect.TypeOf(primitive.D{})
148
}
149

150
// ValueCodec is the interface that groups the methods to encode and decode
151
// values.
152
type ValueCodec interface {
153
	ValueEncoder
154
	ValueDecoder
155
}
156

157
// ValueEncoder is the interface implemented by types that can handle the encoding of a value.
158
type ValueEncoder interface {
159
	EncodeValue(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.
164
type ValueEncoderFunc func(EncodeContext, bsonrw.ValueWriter, reflect.Value) error
165

166
// EncodeValue implements the ValueEncoder interface.
167
func (fn ValueEncoderFunc) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
168
	return fn(ec, vw, val)
169
}
170

171
// ValueDecoder is the interface implemented by types that can handle the decoding of a value.
172
type ValueDecoder interface {
173
	DecodeValue(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.
178
type ValueDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) error
179

180
// DecodeValue implements the ValueDecoder interface.
181
func (fn ValueDecoderFunc) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
182
	return 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.
186
type typeDecoder interface {
187
	decodeType(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.
191
type typeDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Type) (reflect.Value, error)
192

193
func (fn typeDecoderFunc) decodeType(dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
194
	return fn(dc, vr, t)
195
}
196

197
// decodeAdapter allows two functions with the correct signatures to be used as both a ValueDecoder and typeDecoder.
198
type decodeAdapter struct {
199
	ValueDecoderFunc
200
	typeDecoderFunc
201
}
202

203
var _ ValueDecoder = decodeAdapter{}
204
var _ 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.
208
func decodeTypeOrValue(decoder ValueDecoder, dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type) (reflect.Value, error) {
209
	td, _ := decoder.(typeDecoder)
210
	return decodeTypeOrValueWithInfo(decoder, td, dc, vr, t, true)
211
}
212

213
func decodeTypeOrValueWithInfo(vd ValueDecoder, td typeDecoder, dc DecodeContext, vr bsonrw.ValueReader, t reflect.Type, convert bool) (reflect.Value, error) {
214
	if td != nil {
215
		val, err := td.decodeType(dc, vr, t)
216
		if 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.
224
			val = val.Convert(t)
225
		}
226
		return val, err
227
	}
228

229
	val := reflect.New(t).Elem()
230
	err := vd.DecodeValue(dc, vr, val)
231
	return 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.
236
type CodecZeroer interface {
237
	IsTypeZero(interface{}) bool
238
}
239

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.