1420c9859SShuo Chenpackage muduo.rpc;
2420c9859SShuo Chen
3420c9859SShuo Chenimport java.util.zip.Adler32;
4420c9859SShuo Chen
5420c9859SShuo Chenimport muduo.rpc.proto.RpcProto.RpcMessage;
6420c9859SShuo Chen
7420c9859SShuo Chenimport org.jboss.netty.buffer.BigEndianHeapChannelBuffer;
8420c9859SShuo Chenimport org.jboss.netty.buffer.ChannelBuffer;
9420c9859SShuo Chenimport org.jboss.netty.channel.Channel;
10420c9859SShuo Chenimport org.jboss.netty.channel.ChannelHandler.Sharable;
11420c9859SShuo Chenimport org.jboss.netty.channel.ChannelHandlerContext;
12420c9859SShuo Chenimport org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
13420c9859SShuo Chen
14420c9859SShuo Chenimport com.google.protobuf.CodedOutputStream;
15420c9859SShuo Chen
16420c9859SShuo Chen@Sharable
17420c9859SShuo Chenpublic class RpcEncoder extends OneToOneEncoder {
18420c9859SShuo Chen
19420c9859SShuo Chen    public RpcEncoder() {
20420c9859SShuo Chen        super();
21420c9859SShuo Chen    }
22420c9859SShuo Chen
23420c9859SShuo Chen    @Override
24420c9859SShuo Chen    public Object encode(ChannelHandlerContext ctx, Channel channel, Object obj)
25420c9859SShuo Chen            throws Exception {
26420c9859SShuo Chen        if (!(obj instanceof RpcMessage)) {
27420c9859SShuo Chen            return obj;
28420c9859SShuo Chen        }
29420c9859SShuo Chen        RpcMessage message = (RpcMessage) obj;
30420c9859SShuo Chen        int size = message.getSerializedSize();
31420c9859SShuo Chen        ChannelBuffer buffer = new BigEndianHeapChannelBuffer(4 + size + 4);
32420c9859SShuo Chen        buffer.writeBytes("RPC0".getBytes());
33420c9859SShuo Chen        int writerIndex = buffer.writerIndex();
34420c9859SShuo Chen        CodedOutputStream output = CodedOutputStream.newInstance(
35420c9859SShuo Chen                buffer.array(), buffer.writerIndex(), buffer.writableBytes() - 4);
36420c9859SShuo Chen        message.writeTo(output);
37420c9859SShuo Chen        output.checkNoSpaceLeft();
38420c9859SShuo Chen
39420c9859SShuo Chen        buffer.writerIndex(writerIndex + size);
40420c9859SShuo Chen        Adler32 checksum = new Adler32();
41420c9859SShuo Chen        checksum.update(buffer.array(), buffer.arrayOffset(), buffer.readableBytes());
42420c9859SShuo Chen        buffer.writeInt((int) checksum.getValue());
43420c9859SShuo Chen        return buffer;
44420c9859SShuo Chen    }
45420c9859SShuo Chen}