def utf8_machine(byte_data, emit):
    """
    State machine for UTF-8 decoding

    Args:
        byte_data (byte): byte to be parsed
        emit (callable): callback for parsed value (number)

    Returns:
        callable: utf-8 parsing state machine

    Raises:
        Exception: on invalid byte sequence
    """
    left = 0
    num = 0

    def _utf8(byte_data):
        nonlocal num, left
        if (byte_data & 0xc0) != 0x80:
            raise Exception(
                "Invalid byte in UTF-8 sequence: " + hex(byte_data))

        left = left - 1

        num |= (byte_data & 0x3f) << (left * 6)
        if left:
            return _utf8
        return emit(num)

    if 0xc0 <= byte_data < 0xe0:  # 2-byte UTF-8 Character
        left = 1
        num = (byte_data & 0x1f) << 6
        return _utf8

    if 0xe0 <= byte_data < 0xf0:  # 3-byte UTF-8 Character
        left = 2
        num = (byte_data & 0xf) << 12
        return _utf8

    if 0xf0 <= byte_data < 0xf8:  # 4-byte UTF-8 Character
        left = 3
        num = (byte_data & 0x07) << 18
        return _utf8

    raise Exception("Invalid byte in UTF-8 string: " + hex(byte_data))