1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.codec.protobuf;
17
18 import org.jboss.netty.buffer.ChannelBuffer;
19 import org.jboss.netty.channel.Channel;
20 import org.jboss.netty.channel.ChannelHandlerContext;
21 import org.jboss.netty.handler.codec.frame.CorruptedFrameException;
22 import org.jboss.netty.handler.codec.frame.FrameDecoder;
23
24 import com.google.protobuf.CodedInputStream;
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 public class ProtobufVarint32FrameDecoder extends FrameDecoder {
42
43
44
45
46
47
48
49 public ProtobufVarint32FrameDecoder() {
50 super();
51 }
52
53 @Override
54 protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
55 buffer.markReaderIndex();
56 final byte[] buf = new byte[5];
57 for (int i = 0; i < buf.length; i ++) {
58 if (!buffer.readable()) {
59 buffer.resetReaderIndex();
60 return null;
61 }
62
63 buf[i] = buffer.readByte();
64 if (buf[i] >= 0) {
65 int length = CodedInputStream.newInstance(buf, 0, i + 1).readRawVarint32();
66 if (length < 0) {
67 throw new CorruptedFrameException("negative length: " + length);
68 }
69
70 if (buffer.readableBytes() < length) {
71 buffer.resetReaderIndex();
72 return null;
73 } else {
74 return buffer.readBytes(length);
75 }
76 }
77 }
78
79
80 throw new CorruptedFrameException("length wider than 32-bit");
81 }
82 }