Skip to content

Commit

Permalink
cleaned up encoder
Browse files Browse the repository at this point in the history
  • Loading branch information
jubeless committed Dec 5, 2023
1 parent e177b36 commit 1535160
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
11 changes: 3 additions & 8 deletions jsonencoder/encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,21 @@ import (

type Encoder struct {
protoRegistry *protoregistry.Registry
marshallers []*json.Marshalers
}

func New(files *protoregistry.Registry) *Encoder {
e := &Encoder{
return &Encoder{
protoRegistry: files,
}
e.marshallers = []*json.Marshalers{
json.MarshalFuncV2(e.anypb),
}
return e
}

func (e *Encoder) Marshal(in any) error {
return json.MarshalEncode(jsontext.NewEncoder(os.Stdout), in, json.WithMarshalers(json.NewMarshalers(e.marshallers...)))
return json.MarshalEncode(jsontext.NewEncoder(os.Stdout), in, json.WithMarshalers(e.getMarshallers("")))
}

func (e *Encoder) MarshalToString(in any) (string, error) {
buf := bytes.NewBuffer(nil)
if err := json.MarshalEncode(jsontext.NewEncoder(buf), in, json.WithMarshalers(json.NewMarshalers(e.marshallers...))); err != nil {
if err := json.MarshalEncode(jsontext.NewEncoder(buf), in, json.WithMarshalers(e.getMarshallers(""))); err != nil {
return "", err
}
return buf.String(), nil
Expand Down
16 changes: 12 additions & 4 deletions jsonencoder/marshallers.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ func (e *Encoder) anypb(encoder *jsontext.Encoder, t *anypb.Any, options json.Op
if err != nil {
return fmt.Errorf("unmarshalling proto any: %w", err)
}
setBytesEncoder(t.TypeUrl)
cnt, err := json.Marshal(msg, json.WithMarshalers(json.NewMarshalers(e.marshallers...)))

cnt, err := json.Marshal(msg, json.WithMarshalers(e.getMarshallers(t.TypeUrl)))
if err != nil {
return fmt.Errorf("json marshalling proto any: %w", err)
}
Expand All @@ -35,10 +35,18 @@ func (e *Encoder) hexBytes(encoder *jsontext.Encoder, t []byte, options json.Opt
return encoder.WriteToken(jsontext.String(hex.EncodeToString(t)))
}

func setBytesEncoder(typeURL string) {
func (e *Encoder) getMarshallers(typeURL string) *json.Marshalers {
out := []*json.Marshalers{
json.MarshalFuncV2(e.anypb),
}

if strings.Contains(typeURL, "solana") {
dynamic.SetDefaultBytesRepresentation(dynamic.BytesAsBase58)
return
out = append(out, json.MarshalFuncV2(e.base58Bytes))
return json.NewMarshalers(out...)
}

dynamic.SetDefaultBytesRepresentation(dynamic.BytesAsHex)
out = append(out, json.MarshalFuncV2(e.hexBytes))
return json.NewMarshalers(out...)
}

0 comments on commit 1535160

Please sign in to comment.