VarInt { public static long decodeLong(InputStream stream) throws IOException { long result = 0; int shift = 0; int b; do { b = stream.read(); if (b < 0) { if (shift == 0) { throw new EOFException(); } else { throw new IOException("varint not terminated"); } } long bits = b & 0x7F; if (shift >= 64 || (shift == 63 && bits > 1)) { throw new IOException("varint too long"); } result |= bits << shift; shift += 7; } while ((b & 0x80) != 0); return result; }  static void encode(int v, OutputStream stream); static void encode(long v, OutputStream stream); static int decodeInt(InputStream stream); static long decodeLong(InputStream stream); static int getLength(int v); static int getLength(long v);  }
@Test public void decodeThrowsExceptionForOverflow() throws IOException { final byte[] tooLargeNumber = { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x02 }; thrown.expect(IOException.class); decodeLong(tooLargeNumber); }
@Test public void decodeThrowsExceptionForNonterminated() throws IOException { final byte[] nonTerminatedNumber = {(byte) 0xff, (byte) 0xff}; thrown.expect(IOException.class); decodeLong(nonTerminatedNumber); }