from typing import Optional
from typing import IO
from typing import Union
import mmap


def header_bytes(
    header_length: Optional[int], file_handle: IO
) -> Union[bytes, mmap.mmap]:
    """Read in bytes from the start as a header for checking.

    If 0 or None is given for header_length, the entire file is memory
    mapped.

    Args:
        header_length (int):
            The number of bytes to read from the start of the file.
            If 0 or None, the entire file is memory mapped and checked.
        file_handle (file):
            The file handle to read from.

    Returns:
        The header bytes or memory mapped bytes.
    """
    if header_length:
        return file_handle.read(header_length)
    return mmap.mmap(file_handle.fileno(), 0, access=mmap.ACCESS_READ)