Skip to content

Commit

Permalink
Add JSON marshalling and unmarshalling (#71)
Browse files Browse the repository at this point in the history
Co-authored-by: krishna sindhur <[email protected]>
  • Loading branch information
AlekSi and KrishnaSindhur authored Dec 25, 2024
1 parent f782d49 commit e3aefb9
Show file tree
Hide file tree
Showing 4 changed files with 399 additions and 137 deletions.
50 changes: 48 additions & 2 deletions wirebson/array.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@ package wirebson
import (
"bytes"
"encoding/binary"
"encoding/json"
"iter"
"log/slog"
"sort"
"strconv"

"go.mongodb.org/mongo-driver/v2/bson"

"github.com/FerretDB/wire/internal/util/lazyerrors"
"github.com/FerretDB/wire/internal/util/must"
)
Expand Down Expand Up @@ -177,6 +180,23 @@ func (arr *Array) Encode() (RawArray, error) {
return buf.Bytes(), nil
}

// MarshalJSON implements [json.Marshaler].
func (arr *Array) MarshalJSON() ([]byte, error) {
must.NotBeZero(arr)

a, err := toDriver(arr)
if err != nil {
return nil, lazyerrors.Error(err)
}

b, err := bson.MarshalExtJSON(a, true, false)
if err != nil {
return nil, lazyerrors.Error(err)
}

return b, nil
}

// Decode returns itself to implement [AnyArray].
//
// Receiver must not be nil.
Expand All @@ -185,6 +205,30 @@ func (arr *Array) Decode() (*Array, error) {
return arr, nil
}

// UnmarshalJSON implements [json.Unmarshaler].
func (arr *Array) UnmarshalJSON(b []byte) error {
must.NotBeZero(arr)

var a bson.A
if err := bson.UnmarshalExtJSON(b, true, &a); err != nil {
return lazyerrors.Error(err)
}

v, err := fromDriver(a)
if err != nil {
return lazyerrors.Error(err)
}

switch v := v.(type) {
case *Array:
must.NotBeZero(v)
*arr = *v
return nil
default:
return lazyerrors.Errorf("expected *Array, got %T", v)
}
}

// LogValue implements [slog.LogValuer].
func (arr *Array) LogValue() slog.Value {
return slogValue(arr, 1)
Expand All @@ -202,6 +246,8 @@ func (arr *Array) LogMessageIndent() string {

// check interfaces
var (
_ AnyArray = (*Array)(nil)
_ slog.LogValuer = (*Array)(nil)
_ AnyArray = (*Array)(nil)
_ slog.LogValuer = (*Array)(nil)
_ json.Marshaler = (*Array)(nil)
_ json.Unmarshaler = (*Array)(nil)
)
6 changes: 2 additions & 4 deletions wirebson/binary.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,8 @@ func decodeBinary(b []byte) (Binary, error) {

res.Subtype = BinarySubtype(b[4])

if i > 0 {
res.B = make([]byte, i)
copy(res.B, b[5:5+i])
}
res.B = make([]byte, i)
copy(res.B, b[5:5+i])

return res, nil
}
Loading

0 comments on commit e3aefb9

Please sign in to comment.