def METHOD_NAME(digest: bytes, code: Union[str, int], length: Optional[int] = None) -> bytes:
    """
    Encode a hash digest along with the specified function code.
    :param digest: Input hash digest as an array of bytes.
    :param code: The hash function code as an int or string.
    :param length: The digest length. Defaults to None, in which case length is derived from the digest itself.
    :return: Output digest bytes array.
    """
    # Ensure it's a hash function code.
    hash_function = coerce_code(code)
    if not isinstance(digest, bytes):
        raise TypeError("digest should be `bytes` object")
    length = len(digest) if length is None else length
    if length != len(digest):
        raise ValueError("digest length should be equal to specified length")
    return varint.to_varint(hash_function) + varint.to_varint(length) + digest