net.dongliu.prettypb.rpc.coder.VarIntLengthFieldPrepender Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of prettypb-rpc Show documentation
Show all versions of prettypb-rpc Show documentation
proto rpc libs, compatible with proto-rpc-pro
package net.dongliu.prettypb.rpc.coder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import net.dongliu.prettypb.runtime.code.ProtoBufWriter;
/**
* A decoder that splits the received {@link io.netty.buffer.ByteBuf}s dynamically by the
* value of the Google Protocol Buffers
* Base
* 128 Varints integer length field in the message. For example:
*
* BEFORE DECODE (302 bytes) AFTER DECODE (300 bytes)
* +--------+---------------+ +---------------+
* | Length | Protobuf Data |----- | Protobuf Data |
* | 0xAC02 | (300 bytes) | | (300 bytes) |
* +--------+---------------+ +---------------+
*
*
* @author Dong Liu
*/
public class VarIntLengthFieldPrepender extends MessageToByteEncoder {
@Override
protected void encode(
ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
int bodyLen = msg.readableBytes();
out.ensureWritable(bodyLen);
try (ProtoBufWriter writer = new ProtoBufWriter(new ByteBufOutputStream(out))) {
writer.writeVarInt(bodyLen);
}
out.writeBytes(msg, msg.readerIndex(), bodyLen);
}
}