import struct


def DecodeVarint(in_file):
    """
    The decoding of the Varint32 is copied from
    google.protobuf.internal.decoder and is only repeated here to
    avoid depending on the internal functions in the library. If the
    end of file is reached, return (0, 0).
    """
    result = 0
    shift = 0
    pos = 0
    # Use a 32-bit mask
    mask = 0xffffffff
    while 1:
        c = in_file.read(1)
        if len(c) == 0:
            return (0, 0)
        b = struct.unpack('<B', c)[0]
        result |= ((b & 0x7f) << shift)
        pos += 1
        if not (b & 0x80):
            if result > 0x7fffffffffffffff:
                result -= (1 << 64)
                result |= ~mask
            else:
                result &= mask
                return (result, pos)
            shift += 7
            if shift >= 64:
                raise IOError('Too many bytes when decoding varint.')