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.CodedOutputStream;
19 import com.google.protobuf.nano.CodedOutputByteBufferNano;
20 import io.netty.buffer.ByteBuf;
21 import io.netty.channel.ChannelHandler.Sharable;
22 import io.netty.channel.ChannelHandlerContext;
23 import io.netty.handler.codec.MessageToByteEncoder;
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 @Sharable
41 public class ProtobufVarint32LengthFieldPrepender extends MessageToByteEncoder<ByteBuf> {
42
43 @Override
44 protected void encode(
45 ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
46 int bodyLen = msg.readableBytes();
47 int headerLen = computeRawVarint32Size(bodyLen);
48 out.ensureWritable(headerLen + bodyLen);
49 writeRawVarint32(out, bodyLen);
50 out.writeBytes(msg, msg.readerIndex(), bodyLen);
51 }
52
53
54
55
56
57
58 static void writeRawVarint32(ByteBuf out, int value) {
59 while (true) {
60 if ((value & ~0x7F) == 0) {
61 out.writeByte(value);
62 return;
63 } else {
64 out.writeByte((value & 0x7F) | 0x80);
65 value >>>= 7;
66 }
67 }
68 }
69
70
71
72
73
74
75 static int computeRawVarint32Size(final int value) {
76 if ((value & (0xffffffff << 7)) == 0) {
77 return 1;
78 }
79 if ((value & (0xffffffff << 14)) == 0) {
80 return 2;
81 }
82 if ((value & (0xffffffff << 21)) == 0) {
83 return 3;
84 }
85 if ((value & (0xffffffff << 28)) == 0) {
86 return 4;
87 }
88 return 5;
89 }
90 }