MATSIM
VarIntUtils.java
Go to the documentation of this file.
1 package org.matsim.core.population.routes.heavycompressed;
2 
3 import java.nio.ByteBuffer;
4 
5 // inspired from https://github.com/nla/outbackcdx/blob/master/src/outbackcdx/VarInt.java
6 // licensed under the Apache 2 License.
7 // NO zig-zag encoding, NOT the same as protobuf varint! only for values >= 0
8 
9 public class VarIntUtils {
10 
11  private static final byte[] EMPTY_BYTE = new byte[0];
12  private static final int[] EMPTY_INT = new int[0];
13 
14  public static void encode(ByteBuffer bb, long x) {
15  while (Long.compareUnsigned(x, 127) > 0) {
16  bb.put((byte) (x & 127 | 128));
17  x >>>= 7;
18  }
19  bb.put((byte) (x & 127));
20  }
21 
22  public static long decode(ByteBuffer bb) {
23  long x = 0;
24  int shift = 0;
25  long b;
26  do {
27  b = bb.get() & 0xff;
28  x |= (b & 127) << shift;
29  shift += 7;
30  } while ((b & 128) != 0);
31  return x;
32  }
33 
34  public static byte[] encode(int[] values, int lower, int upper) {
35  if (values.length == 0) {
36  return EMPTY_BYTE;
37  }
38  ByteBuffer bb = ByteBuffer.allocate(5 * values.length + 5);
39  encode(bb, upper - lower);
40  for (int i = lower; i < upper; i++) {
41  encode(bb, values[i]);
42  }
43  byte[] bytes = bb.array();
44  byte[] trimmed = new byte[bb.position()];
45  System.arraycopy(bytes, 0, trimmed, 0, bb.position());
46  return trimmed;
47  }
48 
49  public static int[] decode(byte[] bytes) {
50  if (bytes.length == 0) {
51  return EMPTY_INT;
52  }
53  ByteBuffer bb = ByteBuffer.wrap(bytes);
54  int length = (int) decode(bb);
55  int[] values = new int[length];
56  for (int i = 0; i < length; i++) {
57  values[i] = (int) decode(bb);
58  }
59  return values;
60  }
61 
62 }
static byte [] encode(int[] values, int lower, int upper)