import difflib


def gen_ndiff(a, b):
    """
    Return a binary diff result of the byte sequence as a YARA signature.

    :param list a: First buffer representing code block as hexlified bytes.
    :param list b: Second buffer representing code block as hexlified bytes.

    :return: YARA compliant hex string sequence.
    :rtype: str
    """

    diff = difflib.ndiff(a, b)

    commons = []
    start = 0
    end = 0
    start_code = None
    end_code = None
    for d in diff:
        code = d[0:2]
        seq = d[2:]
        if code == '  ':

            if start > 0 and start == end and len(commons) > 0:
                commons.append('[%s]' % start)
            if start > 0 and end == 0 and len(commons) > 0:
                commons.append('[%s-%s]' % (end, start))
            if 0 < start != end > 0 and len(commons) > 0:
                commons.append('[%s-%s]' % (start, end))

            start = 0
            end = 0
            commons.append(seq)

        if code == '- ' and start == 0:
            start_code = '- '
            end_code = '+ '
        elif code == '+ ' and start == 0:
            start_code = '+ '
            end_code = '- '

        if code == start_code:
            start += 1
        if code == end_code:
            end += 1

    return '{ ' + ' '.join(commons) + ' }'