github.com/cloudwego/dynamicgo@v0.2.6-0.20240519101509-707f41b6b834/conv/j2p/impl.go (about)

     1  package j2p
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/cloudwego/dynamicgo/http"
     8  	"github.com/cloudwego/dynamicgo/internal/rt"
     9  	"github.com/cloudwego/dynamicgo/meta"
    10  	"github.com/cloudwego/dynamicgo/proto"
    11  	"github.com/cloudwego/dynamicgo/proto/binary"
    12  )
    13  
    14  const (
    15  	_GUARD_SLICE_FACTOR = 1
    16  )
    17  
    18  func (self *BinaryConv) do(ctx context.Context, src []byte, desc *proto.TypeDescriptor, buf *[]byte, req http.RequestGetter) error {
    19  	//NOTICE: output buffer must be larger than src buffer
    20  	rt.GuardSlice(buf, len(src)*_GUARD_SLICE_FACTOR)
    21  	if err := self.unmarshal(src, buf, desc); err != nil {
    22  		return meta.NewError(meta.ErrConvert, fmt.Sprintf("json convert to protobuf failed, MessageDescriptor: %v", desc.Message().Name()), err)
    23  	}
    24  	return nil
    25  }
    26  
    27  func (self *BinaryConv) unmarshal(src []byte, out *[]byte, desc *proto.TypeDescriptor) error {
    28  	// use sonic to decode json bytes, get visitorUserNode
    29  	vu := newVisitorUserNodeBuffer()
    30  	vu.opts = &self.opts
    31  	vu.p = binary.NewBinaryProtocolBuffer()
    32  	// use Visitor onxxx() to decode json2pb
    33  	data, err := vu.decode(src, desc)
    34  	freeVisitorUserNodePool(vu)
    35  	if err != nil {
    36  		return newError(meta.ErrConvert, "sonic decode json bytes failed", err)
    37  	}
    38  	*out = data
    39  	return nil
    40  }