...
1
2
3
4
5
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
17
18
19 type ArrayCodec struct{}
20
21 var defaultArrayCodec = NewArrayCodec()
22
23
24
25
26
27 func NewArrayCodec() *ArrayCodec {
28 return &ArrayCodec{}
29 }
30
31
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
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