001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 019package org.apache.hadoop.util; 020 021import java.io.DataInput; 022import java.io.IOException; 023 024public abstract class ProtoUtil { 025 026 /** 027 * Read a variable length integer in the same format that ProtoBufs encodes. 028 * @param in the input stream to read from 029 * @return the integer 030 * @throws IOException if it is malformed or EOF. 031 */ 032 public static int readRawVarint32(DataInput in) throws IOException { 033 byte tmp = in.readByte(); 034 if (tmp >= 0) { 035 return tmp; 036 } 037 int result = tmp & 0x7f; 038 if ((tmp = in.readByte()) >= 0) { 039 result |= tmp << 7; 040 } else { 041 result |= (tmp & 0x7f) << 7; 042 if ((tmp = in.readByte()) >= 0) { 043 result |= tmp << 14; 044 } else { 045 result |= (tmp & 0x7f) << 14; 046 if ((tmp = in.readByte()) >= 0) { 047 result |= tmp << 21; 048 } else { 049 result |= (tmp & 0x7f) << 21; 050 result |= (tmp = in.readByte()) << 28; 051 if (tmp < 0) { 052 // Discard upper 32 bits. 053 for (int i = 0; i < 5; i++) { 054 if (in.readByte() >= 0) { 055 return result; 056 } 057 } 058 throw new IOException("Malformed varint"); 059 } 060 } 061 } 062 } 063 return result; 064 } 065 066}