dsdfd2322 2017-12-19 07:13
浏览 22
已采纳

序列化结构字段以预存现有的字节片

I have a setup where I receive data over the network and serialize it to my struct. It works fine, but now I need to serialize the data to a slice buffer to send it across the network.

I am trying to avoid having to allocate more than needed so I have already set up a buffer which I like to write to for all my serializing. But am not sure how to do this.

My setup is like this:

recieveBuffer := make([]byte, 1500)
header := recieveBuffer[0:1]
message := recieveBuffer[1:]

So I am trying to write fields from a struct to message and the total number of bytes for all the fields as a value for header.

This was how I deserialized to the struct:

// Deserialize ...
func (userSession *UserSession) Deserialize(message []byte) {
    userSession.UID = int64(binary.LittleEndian.Uint32(message[0:4]))
    userSession.UUID = string(message[4:40])
    userSession.Username = string(message[40:])
}

I don't really know how to do the reverse of this, however. Is it possible without creating buffers for each field I want to serialize before copying to message?

  • 写回答

2条回答 默认 最新

  • dongshi4078 2017-12-19 07:41
    关注

    Given the preallocated buffer buf, you can reverse the process like this:

    buf[0] = byte(40+len(userSession.Username))
    binary.LittleEndian.PutUint32(buf[1:], uint32(int32(userSession.UID)))
    copy(buf[5:41], userSession.UUID)
    copy(buf[41:], userSession.Username)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?