github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/protocol/message/gen/gen.go (about)

     1  package gen
     2  
     3  import (
     4  	"github.com/nyan233/littlerpc/core/container"
     5  	message2 "github.com/nyan233/littlerpc/core/protocol/message"
     6  	"github.com/nyan233/littlerpc/core/protocol/message/mux"
     7  	"github.com/nyan233/littlerpc/core/utils/random"
     8  )
     9  
    10  const (
    11  	Big    int = 5000
    12  	Little int = 50
    13  )
    14  
    15  // NoMux level为生成的消息的标准, Big/Little
    16  func NoMux(level int) *message2.Message {
    17  	msg := message2.New()
    18  	msg.SetMsgId(uint64(random.FastRand()))
    19  	msg.MetaData.Store(message2.CodecScheme, random.GenStringOnAscii(100))
    20  	msg.MetaData.Store(message2.PackerScheme, random.GenStringOnAscii(100))
    21  	msg.SetMsgType(uint8(random.FastRand()))
    22  	msg.SetServiceName(random.GenStringOnAscii(100))
    23  	for i := 0; i < int(random.FastRandN(50)+1); i++ {
    24  		msg.AppendPayloads(random.GenBytesOnAscii(random.FastRandN(uint32(level))))
    25  	}
    26  	for i := 0; i < int(random.FastRandN(10)+1); i++ {
    27  		msg.MetaData.Store(random.GenStringOnAscii(uint32(level)), random.GenStringOnAscii(10))
    28  	}
    29  	return msg
    30  }
    31  
    32  func NoMuxToBytes(level int) []byte {
    33  	var bytes []byte
    34  	msg := NoMux(level)
    35  	err := message2.Marshal(msg, (*container.Slice[byte])(&bytes))
    36  	if err != nil {
    37  		return nil
    38  	}
    39  	return bytes
    40  }
    41  
    42  func MuxToBytes(level int) []byte {
    43  	var bytes []byte
    44  	msg := NoMux(level)
    45  	err := message2.Marshal(msg, (*container.Slice[byte])(&bytes))
    46  	if err != nil {
    47  		return nil
    48  	}
    49  	toBytes := make([]byte, 0, len(bytes))
    50  	for len(bytes) > 0 {
    51  		var readN int
    52  		if len(bytes) > mux.MaxPayloadSizeOnMux {
    53  			readN = mux.MaxPayloadSizeOnMux
    54  		} else {
    55  			readN = len(bytes)
    56  		}
    57  		muxPayloads := bytes[:readN]
    58  		block := mux.Block{
    59  			Flags:         mux.Enabled,
    60  			StreamId:      0x0bbbb,
    61  			MsgId:         msg.GetMsgId(),
    62  			PayloadLength: uint16(readN),
    63  			Payloads:      muxPayloads,
    64  		}
    65  		marshalContainer := make([]byte, 0, readN+mux.BlockBaseLen)
    66  		mux.Marshal(&block, (*container.Slice[byte])(&marshalContainer))
    67  		toBytes = append(toBytes, marshalContainer...)
    68  		bytes = bytes[readN:]
    69  	}
    70  	return toBytes
    71  }