View Javadoc

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  import org.apache.hadoop.classification.InterfaceAudience;
25  
26  @InterfaceAudience.Private
27  public abstract class ProtoUtil {
28  
29    /**
30     * Read a variable length integer in the same format that ProtoBufs encodes.
31     * @param in the input stream to read from
32     * @return the integer
33     * @throws IOException if it is malformed or EOF.
34     */
35    public static int readRawVarint32(DataInput in) throws IOException {
36      byte tmp = in.readByte();
37      if (tmp >= 0) {
38        return tmp;
39      }
40      int result = tmp & 0x7f;
41      if ((tmp = in.readByte()) >= 0) {
42        result |= tmp << 7;
43      } else {
44        result |= (tmp & 0x7f) << 7;
45        if ((tmp = in.readByte()) >= 0) {
46          result |= tmp << 14;
47        } else {
48          result |= (tmp & 0x7f) << 14;
49          if ((tmp = in.readByte()) >= 0) {
50            result |= tmp << 21;
51          } else {
52            result |= (tmp & 0x7f) << 21;
53            result |= (tmp = in.readByte()) << 28;
54            if (tmp < 0) {
55              // Discard upper 32 bits.
56              for (int i = 0; i < 5; i++) {
57                if (in.readByte() >= 0) {
58                  return result;
59                }
60              }
61              throw new IOException("Malformed varint");
62            }
63          }
64        }
65      }
66      return result;
67    }
68  
69  }