forked from mihaiav/chromedp-undetected
/
easyjson.go
38 lines (30 loc) · 1 KB
/
easyjson.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Package easyjson provides utilities for use with easyjson.
package easyjson
import (
"encoding/json"
"github.com/mailru/easyjson"
"github.com/mailru/easyjson/jlexer"
"github.com/mailru/easyjson/jwriter"
)
var _ easyjson.MarshalerUnmarshaler = (*GenericEJ[any])(nil)
// New creates a new geneic EasyJSON container.
func New[T any](data T) *GenericEJ[T] {
return &GenericEJ[T]{data}
}
// GenericEJ is a type that uses the stdlib json (un)marshaler to make any
// type compatible with easyjson by implementing the EasyJSON interfaces.
type GenericEJ[T any] struct {
Data T
}
// MarshalEasyJSON marshals any type to json with use of the stdlib json pkg.
func (t *GenericEJ[T]) MarshalEasyJSON(w *jwriter.Writer) {
b, err := json.Marshal(t.Data)
w.Buffer.AppendBytes(b)
w.Error = err
}
// UnmarshalEasyJSON unmarshals any type from json with use of the stdlib json pkg.
func (t *GenericEJ[T]) UnmarshalEasyJSON(w *jlexer.Lexer) {
if err := json.Unmarshal(w.Data, &t.Data); err != nil {
w.AddError(err)
}
}