-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.go
More file actions
58 lines (46 loc) · 1.17 KB
/
encoder.go
File metadata and controls
58 lines (46 loc) · 1.17 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package polaris
import (
"bytes"
"encoding/gob"
"encoding/json"
"github.com/pkg/errors"
)
type Encoder[T any] interface {
Encode(v T) ([]byte, error)
Decode([]byte) (T, error)
}
var (
_ Encoder[any] = (*jsonEncoder[any])(nil)
)
type jsonEncoder[T any] struct{}
func (f jsonEncoder[T]) Encode(v T) ([]byte, error) {
return json.Marshal(v)
}
func (f jsonEncoder[T]) Decode(data []byte) (t T, err error) {
if err := json.Unmarshal(data, &t); err != nil {
return t, errors.WithStack(err)
}
return t, nil
}
// google.golang.org/genai supports json
func JSONEncoder[T any]() *jsonEncoder[T] {
return new(jsonEncoder[T])
}
type gobEncoder[T any] struct{}
func (g gobEncoder[T]) Encode(v T) ([]byte, error) {
buf := bytes.NewBuffer(nil)
if err := gob.NewEncoder(buf).Encode(v); err != nil {
return nil, errors.WithStack(err)
}
return buf.Bytes(), nil
}
func (g gobEncoder[T]) Decode(data []byte) (t T, err error) {
if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&t); err != nil {
return t, errors.WithStack(err)
}
return t, nil
}
// cloud.google.com/go/vertexai/genai are not support json
func GobEncoder[T any]() *gobEncoder[T] {
return new(gobEncoder[T])
}