github.com/wfusion/gofusion@v1.1.14/common/utils/serialize/marshal.go (about)

     1  package serialize
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  
     7  	"github.com/wfusion/gofusion/common/utils"
     8  )
     9  
    10  func MarshalFunc(algo Algorithm, opts ...utils.OptionExtender) func(src any) ([]byte, error) {
    11  	fn, ok := marshalFuncMap[algo]
    12  	if !ok {
    13  		panic(fmt.Errorf("unknown serialize algorithm type %+v", algo))
    14  	}
    15  	opt := utils.ApplyOptions[marshalOption](opts...)
    16  	return func(src any) (dst []byte, err error) {
    17  		bs, cb := utils.BytesBufferPool.Get(nil)
    18  		defer cb()
    19  
    20  		if err = fn(bs, src, opt); err != nil {
    21  			return
    22  		}
    23  
    24  		dst = make([]byte, bs.Len())
    25  		copy(dst, bs.Bytes())
    26  		return
    27  	}
    28  }
    29  
    30  func MarshalStreamFunc(algo Algorithm, opts ...utils.OptionExtender) func(dst io.Writer, src any) error {
    31  	fn, ok := marshalFuncMap[algo]
    32  	if !ok {
    33  		panic(fmt.Errorf("unknown serialize algorithm type %+v", algo))
    34  	}
    35  	opt := utils.ApplyOptions[marshalOption](opts...)
    36  	return func(dst io.Writer, src any) error {
    37  		return fn(dst, src, opt)
    38  	}
    39  }