1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.protobuf;
17
18 import com.google.protobuf.CodedInputStream;
19 import com.google.protobuf.nano.CodedInputByteBufferNano;
20 import io.netty.buffer.ByteBuf;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.handler.codec.ByteToMessageDecoder;
23 import io.netty.handler.codec.CorruptedFrameException;
24
25 import java.util.List;
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43 public class ProtobufVarint32FrameDecoder extends ByteToMessageDecoder {
44
45
46
47
48 @Override
49 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
50 throws Exception {
51 in.markReaderIndex();
52 int preIndex = in.readerIndex();
53 int length = readRawVarint32(in);
54 if (preIndex == in.readerIndex()) {
55 return;
56 }
57 if (length < 0) {
58 throw new CorruptedFrameException("negative length: " + length);
59 }
60
61 if (in.readableBytes() < length) {
62 in.resetReaderIndex();
63 } else {
64 out.add(in.readRetainedSlice(length));
65 }
66 }
67
68
69
70
71
72
73 static int readRawVarint32(ByteBuf buffer) {
74 if (buffer.readableBytes() < 4) {
75 return readRawVarint24(buffer);
76 }
77 int wholeOrMore = buffer.getIntLE(buffer.readerIndex());
78 int firstOneOnStop = ~wholeOrMore & 0x80808080;
79 if (firstOneOnStop == 0) {
80 return readRawVarint40(buffer, wholeOrMore);
81 }
82 int bitsToKeep = Integer.numberOfTrailingZeros(firstOneOnStop) + 1;
83 buffer.skipBytes(bitsToKeep >> 3);
84 int thisVarintMask = firstOneOnStop ^ (firstOneOnStop - 1);
85 int wholeWithContinuations = wholeOrMore & thisVarintMask;
86
87
88
89
90
91
92
93 wholeWithContinuations = (wholeWithContinuations & 0x7F007F) | ((wholeWithContinuations & 0x7F007F00) >> 1);
94
95
96
97 return (wholeWithContinuations & 0x3FFF) | ((wholeWithContinuations & 0x3FFF0000) >> 2);
98 }
99
100 private static int readRawVarint40(ByteBuf buffer, int wholeOrMore) {
101 byte lastByte;
102 if (buffer.readableBytes() == 4 || (lastByte = buffer.getByte(buffer.readerIndex() + 4)) < 0) {
103 throw new CorruptedFrameException("malformed varint.");
104 }
105 buffer.skipBytes(5);
106
107 return wholeOrMore & 0x7F |
108 (((wholeOrMore >> 8) & 0x7F) << 7) |
109 (((wholeOrMore >> 16) & 0x7F) << 14) |
110 (((wholeOrMore >> 24) & 0x7F) << 21) |
111 (lastByte << 28);
112 }
113
114 private static int readRawVarint24(ByteBuf buffer) {
115 if (!buffer.isReadable()) {
116 return 0;
117 }
118 buffer.markReaderIndex();
119
120 byte tmp = buffer.readByte();
121 if (tmp >= 0) {
122 return tmp;
123 }
124 int result = tmp & 127;
125 if (!buffer.isReadable()) {
126 buffer.resetReaderIndex();
127 return 0;
128 }
129 if ((tmp = buffer.readByte()) >= 0) {
130 return result | tmp << 7;
131 }
132 result |= (tmp & 127) << 7;
133 if (!buffer.isReadable()) {
134 buffer.resetReaderIndex();
135 return 0;
136 }
137 if ((tmp = buffer.readByte()) >= 0) {
138 return result | tmp << 14;
139 }
140 return result | (tmp & 127) << 14;
141 }
142 }