def _read_varint(stream):
    """
    read a varint from a stream
    :returns (result, bytes read)
    """
    mask = (1 << 32) - 1
    result = 0
    shift = 0
    pos = 0
    while 1:
        buf = stream.read(1)
        if not buf:
            return 0, 0
        b = buf[0]
        result |= (b & 127) << shift
        pos += 1
        if not b & 128:
            result &= mask
            result = int(result)
            return result, pos
        shift += 7
        if shift >= 64:
            raise RuntimeError('Too many bytes when decoding varint.')
