github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/codec.go (about)

     1  package kiwi
     2  
     3  import (
     4  	"github.com/15mga/kiwi/util"
     5  	"reflect"
     6  )
     7  
     8  var (
     9  	_Codec ICodec
    10  )
    11  
    12  func Codec() ICodec {
    13  	return _Codec
    14  }
    15  
    16  func SetCodec(codec ICodec) {
    17  	_Codec = codec
    18  }
    19  
    20  type ICodec interface {
    21  	PbMarshal(obj util.IMsg) ([]byte, *util.Err)
    22  	PbUnmarshal(data []byte, msg util.IMsg) *util.Err
    23  	PbUnmarshal2(svc TSvc, mtd TCode, data []byte) (util.IMsg, *util.Err)
    24  	JsonMarshal(obj util.IMsg) ([]byte, *util.Err)
    25  	JsonUnmarshal(data []byte, msg util.IMsg) *util.Err
    26  	JsonUnmarshal2(svc TSvc, mtd TCode, data []byte) (util.IMsg, *util.Err)
    27  	Spawn(svc TSvc, mtd TCode) (util.IMsg, *util.Err)
    28  	SpawnRes(svc TSvc, mtd TCode) (util.IMsg, *util.Err)
    29  	BindFac(svc TSvc, mtd TCode, fac util.ToMsg)
    30  	BindReqToRes(svc TSvc, req, res TCode)
    31  	ReqToResCode(svc TSvc, req TCode) (TCode, *util.Err)
    32  	MsgToSvcCode(msg util.IMsg) (svc TSvc, code TCode)
    33  }
    34  
    35  func CodecSpawn[T any](svc TSvc, mtd TCode) (T, *util.Err) {
    36  	o, err := _Codec.Spawn(svc, mtd)
    37  	if err != nil {
    38  		return util.Default[T](), err
    39  	}
    40  	t, ok := o.(T)
    41  	if !ok {
    42  		return t, util.NewErr(util.EcWrongType, util.M{
    43  			"service":  svc,
    44  			"method":   mtd,
    45  			"expected": reflect.TypeOf(t).Name(),
    46  			"actual":   reflect.TypeOf(o).Name(),
    47  		})
    48  	}
    49  	return t, nil
    50  }
    51  
    52  func CodecSpawnRes[T any](svc TSvc, mtd TCode) (T, *util.Err) {
    53  	resMtd, err := _Codec.ReqToResCode(svc, mtd)
    54  	if err != nil {
    55  		return util.Default[T](), err
    56  	}
    57  	return CodecSpawn[T](svc, resMtd)
    58  }