-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarshaller.go
35 lines (30 loc) · 928 Bytes
/
marshaller.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
package encoder
import "github.com/koykov/bytealg"
// MarshallerInterface is the interface that wraps the basic Marshal method.
type MarshallerInterface interface {
Marshal() ([]byte, error)
}
// MarshallerToInterface is the interface that wraps the basic MarshalTo method.
type MarshallerToInterface interface {
Size() int
MarshalTo([]byte) (int, error)
}
// Marshaller is an encoder that can encode objects implementing MarshallerInterface or MarshallerToInterface interface.
type Marshaller struct{}
func (e Marshaller) Encode(dst []byte, x any) ([]byte, error) {
if m, ok := x.(MarshallerToInterface); ok {
off := len(dst)
dst = bytealg.GrowDelta(dst, m.Size())
_, err := m.MarshalTo(dst[off:])
return dst, err
}
if m, ok := x.(MarshallerInterface); ok {
b, err := m.Marshal()
if err != nil {
return dst, err
}
dst = append(dst, b...)
return dst, nil
}
return dst, ErrIncompatibleEncoder
}