public static void encodeCommand()

in impl/src/main/java/org/apache/rocketmq/remoting/impl/command/CodecHelper.java [39:117]


    public static void encodeCommand(final RemotingCommand command, final RemotingBuffer out) {
        out.writeByte(PROTOCOL_MAGIC);

        short remarkLen = 0;
        byte[] remark = null;
        if (command.remark() != null) {
            remark = command.remark().getBytes(REMOTING_CHARSET);
            if (remark.length > REMARK_MAX_LEN) {
                throw new RemotingCodecException(String.format("Remark len: %d over max limit: %d", remark.length, REMARK_MAX_LEN));
            }
            remarkLen = (short) remark.length;
        }

        byte[][] props = null;
        int propsLen = 0;
        StringBuilder sb = new StringBuilder();
        if (command.properties() != null && !command.properties().isEmpty()) {
            props = new byte[command.properties().size()][];
            int i = 0;
            for (Entry<String, String> next : command.properties().entrySet()) {
                sb.setLength(0);
                sb.append(next.getKey());
                sb.append(PROPERTY_SEPARATOR);
                sb.append(next.getValue());

                props[i] = sb.toString().getBytes(REMOTING_CHARSET);

                if (props[i].length > Short.MAX_VALUE) {
                    throw new RemotingCodecException(String.format("Property KV len: %d over max limit: %d", props[i].length, Short.MAX_VALUE));
                }

                propsLen += 2;
                propsLen += props[i].length;
                i++;
            }
        }

        if (propsLen > PROPERTY_MAX_LEN) {
            throw new RemotingCodecException(String.format("Properties total len: %d over max limit: %d", propsLen, PROPERTY_MAX_LEN));
        }

        int payloadLen = command.payload() == null ? 0 : command.payload().length;

        if (payloadLen > PAYLOAD_MAX_LEN) {
            throw new RemotingCodecException(String.format("Payload len: %d over max limit: %d", payloadLen, PAYLOAD_MAX_LEN));
        }

        int totalLength = MIN_PROTOCOL_LEN
            + remarkLen
            + propsLen
            + payloadLen;

        out.writeInt(totalLength);
        out.writeShort(command.cmdCode());
        out.writeShort(command.cmdVersion());
        out.writeInt(command.requestID());
        out.writeByte((byte) command.trafficType().ordinal());
        out.writeShort(command.opCode());

        out.writeShort(remarkLen);
        if (remarkLen != 0) {
            out.writeBytes(remark);
        }

        if (props != null) {
            out.writeShort((short) props.length);
            for (byte[] prop : props) {
                out.writeShort((short) prop.length);
                out.writeBytes(prop);
            }
        } else {
            out.writeShort((short) 0);
        }

        out.writeInt(payloadLen);
        if (payloadLen != 0) {
            out.writeBytes(command.payload());
        }
    }