def read_varint(readfn):
    """
    Reads a variable-length encoded integer.

    :param readfn: a callable that reads a given number of bytes,
        like file.read().
    """
    b = ord(readfn(1))
    i = b & 127
    shift = 7
    while b & 128 != 0:
        b = ord(readfn(1))
        i |= (b & 127) << shift
        shift += 7
    return i
