#!/usr/bin/python3

r"""
Split up a file and yield its pieces based on some line terminator.

Usage looks like:
    $ /usr/local/cpython-3.6/bin/python3
    Python 3.6.0 (default, Apr 22 2017, 09:17:19)
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import readline0
    >>> file_ = open('/etc/shells', 'r')
    >>> for line in readline0.readline0(file_=file_, separator=b'\n'):
    ...     print(line)
    ...
    b'# /etc/shells: valid login shells'
    b'/bin/sh'
    b'/bin/dash'
    b'/bin/bash'
    b'/bin/rbash'
    >>>

Of course separator need not be a newline; it defaults to a null byte.
"""

# This software is the proprietary property of The Regents of the University of California ("The Regents") Copyright (c)
# 1993-2006 The Regents of the University of California, Irvine campus. All Rights Reserved.

# Redistributions of source code must retain the above copyright notice, this list of conditions and the following
# disclaimer.

# Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the distribution.

# Neither the name of The Regents nor the names of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.

# The end-user understands that the program was developed for research purposes and is advised not to rely exclusively
# on the program for any reason.

# THE SOFTWARE PROVIDED IS ON AN "AS IS" BASIS, AND THE REGENTS AND CONTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
# MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. THE REGENTS AND CONTRIBUTORS SPECIFICALLY DISCLAIM ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES, INCLUDING BUT NOT LIMITED TO PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES, LOSE OF USE, DATA OR PROFITS, OR BUSINESS INTERRUPTION, HOWEVER CAUSED AND UNDER ANY
# THEORY OF LIABILITY WHETHER IN CONTRACT, STRICT LIABILITY OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
# WAY OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import io
import os
import sys
import typing
import collections.abc


def readline0(
    file_: typing.Union[typing.BinaryIO, int] = sys.stdin.buffer, separator: bytes = b"\0", blocksize: int = 2**16
) -> collections.abc.Iterator[bytes]:
    """
    Instantiate Readline0 class and yield what we get back.

    file_ defaults to sys.stdin, separator defaults to a null, and blocksize defaults to 64K.
    """
    readline0_obj = Readline0(file_, separator, blocksize)
    # FIXME: This should become a yield from eventually.
    for line in readline0_obj.sequence():
        yield line


class Readline0:
    """Yield a series of blocks, separated by separator."""

    # This class assumes that there will be a null once in a while.  If you feed it with a huge block of data that has
    # no nulls (line separators), woe betide you.
    def __init__(self, file_: typing.Union[typing.BinaryIO, int], separator: bytes, blocksize: int) -> None:
        """Initialize."""
        self.file_ = file_
        self.blocksize = blocksize
        self.separator = separator

    def get(self, length: int) -> bytes:
        """Read up to `length` bytes from self.file_."""
        if isinstance(self.file_, int):
            assert isinstance(self.file_, int)
            return os.read(self.file_, length)
        elif isinstance(self.file_, io.IOBase):
            assert isinstance(self.file_, io.IOBase)
            block: bytes = self.file_.read(length)
            return block
        else:
            raise TypeError("self.file_ is neither an int nor a io.IOBase")

    def sequence(self) -> typing.Iterator[bytes]:
        """Generate each field (line) in turn."""
        buffer = b""
        while True:
            chunk = self.get(self.blocksize)
            if not chunk:
                if buffer:
                    yield buffer
                break
            buffer += chunk
            while self.separator in buffer:
                line, buffer = buffer.split(self.separator, 1)
                yield line
