podman
99 строк · 2.8 Кб
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 bson8
9import (10"errors"11"reflect"12"sync"13
14"go.mongodb.org/mongo-driver/bson/bsoncodec"15"go.mongodb.org/mongo-driver/bson/bsonrw"16)
17
18// This pool is used to keep the allocations of Encoders down. This is only used for the Marshal*
19// methods and is not consumable from outside of this package. The Encoders retrieved from this pool
20// must have both Reset and SetRegistry called on them.
21var encPool = sync.Pool{22New: func() interface{} {23return new(Encoder)24},25}
26
27// An Encoder writes a serialization format to an output stream. It writes to a bsonrw.ValueWriter
28// as the destination of BSON data.
29type Encoder struct {30ec bsoncodec.EncodeContext31vw bsonrw.ValueWriter32}
33
34// NewEncoder returns a new encoder that uses the DefaultRegistry to write to vw.
35func NewEncoder(vw bsonrw.ValueWriter) (*Encoder, error) {36if vw == nil {37return nil, errors.New("cannot create a new Encoder with a nil ValueWriter")38}39
40return &Encoder{41ec: bsoncodec.EncodeContext{Registry: DefaultRegistry},42vw: vw,43}, nil44}
45
46// NewEncoderWithContext returns a new encoder that uses EncodeContext ec to write to vw.
47func NewEncoderWithContext(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter) (*Encoder, error) {48if ec.Registry == nil {49ec = bsoncodec.EncodeContext{Registry: DefaultRegistry}50}51if vw == nil {52return nil, errors.New("cannot create a new Encoder with a nil ValueWriter")53}54
55return &Encoder{56ec: ec,57vw: vw,58}, nil59}
60
61// Encode writes the BSON encoding of val to the stream.
62//
63// The documentation for Marshal contains details about the conversion of Go
64// values to BSON.
65func (e *Encoder) Encode(val interface{}) error {66if marshaler, ok := val.(Marshaler); ok {67// TODO(skriptble): Should we have a MarshalAppender interface so that we can have []byte reuse?68buf, err := marshaler.MarshalBSON()69if err != nil {70return err71}72return bsonrw.Copier{}.CopyDocumentFromBytes(e.vw, buf)73}74
75encoder, err := e.ec.LookupEncoder(reflect.TypeOf(val))76if err != nil {77return err78}79return encoder.EncodeValue(e.ec, e.vw, reflect.ValueOf(val))80}
81
82// Reset will reset the state of the encoder, using the same *EncodeContext used in
83// the original construction but using vw.
84func (e *Encoder) Reset(vw bsonrw.ValueWriter) error {85e.vw = vw86return nil87}
88
89// SetRegistry replaces the current registry of the encoder with r.
90func (e *Encoder) SetRegistry(r *bsoncodec.Registry) error {91e.ec.Registry = r92return nil93}
94
95// SetContext replaces the current EncodeContext of the encoder with er.
96func (e *Encoder) SetContext(ec bsoncodec.EncodeContext) error {97e.ec = ec98return nil99}
100