...

Source file src/go.mongodb.org/mongo-driver/bson/bsoncodec/array_codec.go

Documentation: go.mongodb.org/mongo-driver/bson/bsoncodec

     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
     8  
     9  import (
    10  	"reflect"
    11  
    12  	"go.mongodb.org/mongo-driver/bson/bsonrw"
    13  	"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
    14  )
    15  
    16  // ArrayCodec is the Codec used for bsoncore.Array values.
    17  //
    18  // Deprecated: ArrayCodec will not be directly accessible in Go Driver 2.0.
    19  type ArrayCodec struct{}
    20  
    21  var defaultArrayCodec = NewArrayCodec()
    22  
    23  // NewArrayCodec returns an ArrayCodec.
    24  //
    25  // Deprecated: NewArrayCodec will not be available in Go Driver 2.0. See
    26  // [ArrayCodec] for more details.
    27  func NewArrayCodec() *ArrayCodec {
    28  	return &ArrayCodec{}
    29  }
    30  
    31  // EncodeValue is the ValueEncoder for bsoncore.Array values.
    32  func (ac *ArrayCodec) EncodeValue(_ EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
    33  	if !val.IsValid() || val.Type() != tCoreArray {
    34  		return ValueEncoderError{Name: "CoreArrayEncodeValue", Types: []reflect.Type{tCoreArray}, Received: val}
    35  	}
    36  
    37  	arr := val.Interface().(bsoncore.Array)
    38  	return bsonrw.Copier{}.CopyArrayFromBytes(vw, arr)
    39  }
    40  
    41  // DecodeValue is the ValueDecoder for bsoncore.Array values.
    42  func (ac *ArrayCodec) DecodeValue(_ DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
    43  	if !val.CanSet() || val.Type() != tCoreArray {
    44  		return ValueDecoderError{Name: "CoreArrayDecodeValue", Types: []reflect.Type{tCoreArray}, Received: val}
    45  	}
    46  
    47  	if val.IsNil() {
    48  		val.Set(reflect.MakeSlice(val.Type(), 0, 0))
    49  	}
    50  
    51  	val.SetLen(0)
    52  	arr, err := bsonrw.Copier{}.AppendArrayBytes(val.Interface().(bsoncore.Array), vr)
    53  	val.Set(reflect.ValueOf(arr))
    54  	return err
    55  }
    56  

View as plain text