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
8
9import (
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.
17type ArrayCodec struct{}
18
19var defaultArrayCodec = NewArrayCodec()
20
21// NewArrayCodec returns an ArrayCodec.
22func NewArrayCodec() *ArrayCodec {
23	return &ArrayCodec{}
24}
25
26// EncodeValue is the ValueEncoder for bsoncore.Array values.
27func (ac *ArrayCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
28	if !val.IsValid() || val.Type() != tCoreArray {
29		return ValueEncoderError{Name: "CoreArrayEncodeValue", Types: []reflect.Type{tCoreArray}, Received: val}
30	}
31
32	arr := val.Interface().(bsoncore.Array)
33	return bsonrw.Copier{}.CopyArrayFromBytes(vw, arr)
34}
35
36// DecodeValue is the ValueDecoder for bsoncore.Array values.
37func (ac *ArrayCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
38	if !val.CanSet() || val.Type() != tCoreArray {
39		return ValueDecoderError{Name: "CoreArrayDecodeValue", Types: []reflect.Type{tCoreArray}, Received: val}
40	}
41
42	if val.IsNil() {
43		val.Set(reflect.MakeSlice(val.Type(), 0, 0))
44	}
45
46	val.SetLen(0)
47	arr, err := bsonrw.Copier{}.AppendArrayBytes(val.Interface().(bsoncore.Array), vr)
48	val.Set(reflect.ValueOf(arr))
49	return err
50}
51