1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.data.protobuf;
|
---|
3 |
|
---|
4 | import java.util.ArrayList;
|
---|
5 | import java.util.List;
|
---|
6 |
|
---|
7 | /**
|
---|
8 | * Parse packed values (only numerical values)
|
---|
9 | *
|
---|
10 | * @author Taylor Smock
|
---|
11 | * @since xxx
|
---|
12 | */
|
---|
13 | public class ProtobufPacked {
|
---|
14 | private final byte[] bytes;
|
---|
15 | private final Number[] numbers;
|
---|
16 | private int location;
|
---|
17 |
|
---|
18 | /**
|
---|
19 | * Create a new ProtobufPacked object
|
---|
20 | *
|
---|
21 | * @param bytes The packed bytes
|
---|
22 | */
|
---|
23 | public ProtobufPacked(byte[] bytes) {
|
---|
24 | this.location = 0;
|
---|
25 | this.bytes = bytes;
|
---|
26 | List<Number> numbersT = new ArrayList<>();
|
---|
27 | while (this.location < bytes.length) {
|
---|
28 | numbersT.add(ProtobufParser.convertByteArray(this.nextVarInt(), ProtobufParser.VAR_INT_BYTE_SIZE));
|
---|
29 | }
|
---|
30 |
|
---|
31 | this.numbers = new Number[numbersT.size()];
|
---|
32 | for (int i = 0; i < numbersT.size(); i++) {
|
---|
33 | this.numbers[i] = numbersT.get(i);
|
---|
34 | }
|
---|
35 | }
|
---|
36 |
|
---|
37 | /**
|
---|
38 | * Get the parsed number array
|
---|
39 | *
|
---|
40 | * @return The number array
|
---|
41 | */
|
---|
42 | public Number[] getArray() {
|
---|
43 | return this.numbers;
|
---|
44 | }
|
---|
45 |
|
---|
46 | private byte[] nextVarInt() {
|
---|
47 | List<Byte> byteList = new ArrayList<>();
|
---|
48 | while ((this.bytes[this.location] & ProtobufParser.MOST_SIGNIFICANT_BYTE)
|
---|
49 | == ProtobufParser.MOST_SIGNIFICANT_BYTE) {
|
---|
50 | // Get rid of the leading bit (shift left 1, then shift right 1 unsigned)
|
---|
51 | byteList.add((byte) (this.bytes[this.location++] ^ ProtobufParser.MOST_SIGNIFICANT_BYTE));
|
---|
52 | }
|
---|
53 | // The last byte doesn't drop the most significant bit
|
---|
54 | byteList.add(this.bytes[this.location++]);
|
---|
55 | byte[] byteArray = new byte[byteList.size()];
|
---|
56 | for (int i = 0; i < byteList.size(); i++) {
|
---|
57 | byteArray[i] = byteList.get(i);
|
---|
58 | }
|
---|
59 |
|
---|
60 | return byteArray;
|
---|
61 | }
|
---|
62 | }
|
---|