1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package org.apache.hadoop.hbase.util;
20
21 import java.io.DataInput;
22 import java.io.IOException;
23
24 public abstract class ProtoUtil {
25
26 /**
27 * Read a variable length integer in the same format that ProtoBufs encodes.
28 * @param in the input stream to read from
29 * @return the integer
30 * @throws IOException if it is malformed or EOF.
31 */
32 public static int readRawVarint32(DataInput in) throws IOException {
33 byte tmp = in.readByte();
34 if (tmp >= 0) {
35 return tmp;
36 }
37 int result = tmp & 0x7f;
38 if ((tmp = in.readByte()) >= 0) {
39 result |= tmp << 7;
40 } else {
41 result |= (tmp & 0x7f) << 7;
42 if ((tmp = in.readByte()) >= 0) {
43 result |= tmp << 14;
44 } else {
45 result |= (tmp & 0x7f) << 14;
46 if ((tmp = in.readByte()) >= 0) {
47 result |= tmp << 21;
48 } else {
49 result |= (tmp & 0x7f) << 21;
50 result |= (tmp = in.readByte()) << 28;
51 if (tmp < 0) {
52 // Discard upper 32 bits.
53 for (int i = 0; i < 5; i++) {
54 if (in.readByte() >= 0) {
55 return result;
56 }
57 }
58 throw new IOException("Malformed varint");
59 }
60 }
61 }
62 }
63 return result;
64 }
65
66 }