Skip to content

Commit

Permalink
genericize logic
Browse files Browse the repository at this point in the history
  • Loading branch information
qingyang-hu committed Apr 17, 2024
1 parent bbfb128 commit e8d6685
Showing 1 changed file with 23 additions and 20 deletions.
43 changes: 23 additions & 20 deletions bson/primitive/primitive.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,22 +238,14 @@ func (d D) MarshalJSON() ([]byte, error) {

// UnmarshalJSON decodes D from JSON.
func (d *D) UnmarshalJSON(b []byte) error {
dec := json.NewDecoder(bytes.NewReader(b))
t, err := dec.Token()
dec, err := newJsonObjDecoder[D](b)
if err != nil {
return err
}
if t == nil {
if dec == nil {
*d = nil
return nil
}
if v, ok := t.(json.Delim); !ok || v != '{' {
return &json.UnmarshalTypeError{
Value: tokenString(t),
Type: reflect.TypeOf(*d),
Offset: dec.InputOffset(),
}
}
*d, err = jsonDecodeD(dec)
return err
}
Expand All @@ -275,22 +267,14 @@ type M map[string]interface{}

// UnmarshalJSON decodes M from JSON.
func (m *M) UnmarshalJSON(b []byte) error {
dec := json.NewDecoder(bytes.NewReader(b))
t, err := dec.Token()
dec, err := newJsonObjDecoder[M](b)
if err != nil {
return err
}
if t == nil {
if dec == nil {
*m = nil
return nil
}
if v, ok := t.(json.Delim); !ok || v != '{' {
return &json.UnmarshalTypeError{
Value: tokenString(t),
Type: reflect.TypeOf(*m),
Offset: dec.InputOffset(),
}
}
*m, err = jsonDecodeM(dec)
return err
}
Expand Down Expand Up @@ -326,6 +310,25 @@ func (a *A) UnmarshalJSON(b []byte) error {
return err
}

func newJsonObjDecoder[T D | M](b []byte) (*json.Decoder, error) {
dec := json.NewDecoder(bytes.NewReader(b))
t, err := dec.Token()
if err != nil {
return nil, err
}
if t == nil {
return nil, nil
}
if v, ok := t.(json.Delim); !ok || v != '{' {
return nil, &json.UnmarshalTypeError{
Value: tokenString(t),
Type: reflect.TypeOf((T)(nil)),
Offset: dec.InputOffset(),
}
}
return dec, nil
}

func jsonDecodeD(dec *json.Decoder) (D, error) {
res := D{}
for {
Expand Down

0 comments on commit e8d6685

Please sign in to comment.