示例#1
0
        /// <summary>
        /// Serializes the entire base message, including the 'length' field at the beginning.
        /// </summary>
        /// <remarks>The result can be directly sent over the network using stream protocol</remarks>
        /// <returns>Serialized message as a byte array</returns>
        /// <exception cref="Protocol.ProtoException">When serializing fails
        /// (for example if some of the required fields are not set).</exception>
        public byte[] SerializeMessageWithLength()
        {
            Buffer buf = new Buffer();

            this.SerializeMessageData(buf);

            int payloadSize = buf.Size;

            if (payloadSize < 1)
            {
                return(new byte[0]);
            }

            // We append the header at the end of the 'buf' - just after the payload.
            // We need it at the beginning, but until we actually serialize the data,
            // we don't know what the payload size is. We could also put it in a separate Buffer,
            // but we already have one that likely has some empty space left.
            // We would have to move things around anyway.
            Codec.AppendValue(buf, LengthFieldId, ( uint )payloadSize);

            byte[] ret = new byte[buf.Size];

            int idx = 0;

            // Let's copy the header (which was appended to the end of 'buf')
            // to the beginning of the buffer that we actually are about to return.
            for (int i = payloadSize; i < buf.Size; ++i)
            {
                ret[idx++] = buf.Bytes[i];
            }

            // And now append the actual payload.
            for (int i = 0; i < payloadSize; ++i)
            {
                ret[idx++] = buf.Bytes[i];
            }

            return(ret);
        }