ProtobufVarint32LengthFieldPrepender extends MessageToByteEncoder<ByteBuf> { static int computeRawVarint32Size(final int value) { if ((value & (0xffffffff << 7)) == 0) { return 1; } if ((value & (0xffffffff << 14)) == 0) { return 2; } if ((value & (0xffffffff << 21)) == 0) { return 3; } if ((value & (0xffffffff << 28)) == 0) { return 4; } return 5; }    }
@Test public void testSize1Varint() { final int size = 1; final int num = 10; assertThat(ProtobufVarint32LengthFieldPrepender.computeRawVarint32Size(num), is(size)); final byte[] buf = new byte[size + num]; buf[0] = 0x0A; for (int i = size; i < num + size; ++i) { buf[i] = 1; } assertTrue(ch.writeOutbound(wrappedBuffer(buf, size, buf.length - size))); ByteBuf expected = wrappedBuffer(buf); ByteBuf actual = ch.readOutbound(); assertThat(expected, is(actual)); assertFalse(ch.finish()); expected.release(); actual.release(); }
@Test public void testSize2Varint() { final int size = 2; final int num = 266; assertThat(ProtobufVarint32LengthFieldPrepender.computeRawVarint32Size(num), is(size)); final byte[] buf = new byte[size + num]; buf[0] = (byte) (0x8A & 0xFF); buf[1] = 0x02; for (int i = size; i < num + size; ++i) { buf[i] = 1; } assertTrue(ch.writeOutbound(wrappedBuffer(buf, size, buf.length - size))); ByteBuf expected = wrappedBuffer(buf); ByteBuf actual = ch.readOutbound(); assertThat(actual, is(expected)); assertFalse(ch.finish()); expected.release(); actual.release(); }
@Test public void testSize3Varint() { final int size = 3; final int num = 0x4000; assertThat(ProtobufVarint32LengthFieldPrepender.computeRawVarint32Size(num), is(size)); final byte[] buf = new byte[size + num]; buf[0] = (byte) (0x80 & 0xFF); buf[1] = (byte) (0x80 & 0xFF); buf[2] = 0x01; for (int i = size; i < num + size; ++i) { buf[i] = 1; } assertTrue(ch.writeOutbound(wrappedBuffer(buf, size, buf.length - size))); ByteBuf expected = wrappedBuffer(buf); ByteBuf actual = ch.readOutbound(); assertThat(expected, is(actual)); assertFalse(ch.finish()); expected.release(); actual.release(); }
@Test public void testSize4Varint() { final int size = 4; final int num = 0x200000; assertThat(ProtobufVarint32LengthFieldPrepender.computeRawVarint32Size(num), is(size)); final byte[] buf = new byte[size + num]; buf[0] = (byte) (0x80 & 0xFF); buf[1] = (byte) (0x80 & 0xFF); buf[2] = (byte) (0x80 & 0xFF); buf[3] = 0x01; for (int i = size; i < num + size; ++i) { buf[i] = 1; } assertTrue(ch.writeOutbound(wrappedBuffer(buf, size, buf.length - size))); ByteBuf expected = wrappedBuffer(buf); ByteBuf actual = ch.readOutbound(); assertThat(actual, is(expected)); assertFalse(ch.finish()); expected.release(); actual.release(); }