def _utf8_chunk(bytestr):
    """If bytestr is a valid UTF-8 sequence, returns bytestr.
    If bytestr can be made a valid UTF-8 sequence by removing a few bytes
    from the end, returns a modified copy of bytestr.
    Otherwise, returns bytestr.

    The purpose of this method is to provide a safe way of reading chunks
    from the middle of a UTF-8 log file given an offset and length.
    Consider a caller reading a log file in 1MB chunks.  It's possible that
    a chunk would end in the middle of a UTF-8 encoded character, resulting
    in a broken string.  This method fixes up any such broken chunks."""
    try:
        bytestr.decode('utf-8')
        return bytestr
    except UnicodeDecodeError:
        pass
    idx = len(bytestr)
    while idx > 0:
        last_char = ord(bytestr[idx - 1:idx])
        if last_char < 128:
            break
        idx = idx - 1
        if last_char >= 192:
            break
    out = bytestr[:idx]
    try:
        out.decode('utf-8')
        return out
    except UnicodeDecodeError:
        return bytestr
