Skip to content

Commit

Permalink
new marshaller
Browse files Browse the repository at this point in the history
  • Loading branch information
miiu96 committed Feb 4, 2025
1 parent 04144b1 commit 4e0afa9
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
16 changes: 16 additions & 0 deletions marshal/gogoProtoMarshalizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,22 @@ func (x *GogoProtoMarshalizer) Unmarshal(obj interface{}, buff []byte) error {
return fmt.Errorf("%T, %w", obj, ErrUnmarshallingProto)
}

func (x *GogoProtoMarshalizer) MarshalWithExtraCapacity(obj interface{}, extraCapacity int) ([]byte, error) {
if msg, ok := obj.(GogoProtoObj); ok {
size := msg.Size()
data := make([]byte, size, size+extraCapacity)

n, err := msg.MarshalToSizedBuffer(data[:size])
if err != nil {
return nil, err
}

return data[:n], nil
}

return nil, fmt.Errorf("%T, %w", obj, ErrMarshallingProto)
}

// IsInterfaceNil returns true if there is no value under the interface
func (x *GogoProtoMarshalizer) IsInterfaceNil() bool {
return x == nil
Expand Down
4 changes: 4 additions & 0 deletions marshal/jsonMarshalizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ func (jm JsonMarshalizer) Unmarshal(obj interface{}, buff []byte) error {
return json.Unmarshal(buff, obj)
}

func (jm JsonMarshalizer) MarshalWithExtraCapacity(obj interface{}, _ int) ([]byte, error) {
return jm.Marshal(obj)
}

// IsInterfaceNil returns true if there is no value under the interface
func (jm *JsonMarshalizer) IsInterfaceNil() bool {
return jm == nil
Expand Down
9 changes: 9 additions & 0 deletions marshal/marshalizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (

// GogoProtoObj groups the necessary of a gogo protobuf marshalizeble object
type GogoProtoObj interface {
Size() int
MarshalToSizedBuffer(dAtA []byte) (int, error)
gproto.Marshaler
gproto.Unmarshaler
proto.Message
Expand All @@ -18,3 +20,10 @@ type Marshalizer interface {
Unmarshal(obj interface{}, buff []byte) error
IsInterfaceNil() bool
}

type MarshalizerWithExtraSize interface {
MarshalWithExtraCapacity(obj interface{}, extraCapacity int) ([]byte, error)
Marshal(obj interface{}) ([]byte, error)
Unmarshal(obj interface{}, buff []byte) error
IsInterfaceNil() bool
}

0 comments on commit 4e0afa9

Please sign in to comment.