def decode(data, size):
    """
    Decodes RLE encoded data.
    """
    data = bytearray(data)
    result = bytearray(size)
    src = 0
    dst = 0
    while src < len(data):
        header = data[src]
        if header > 127:
            header -= 256
        src += 1
        if 0 <= header <= 127:
            length = header + 1
            if src + length <= len(data) and dst + length <= size:
                result[dst:dst + header + 1] = data[src:src + length]
                src += length
                dst += length
            else:
                raise ValueError('Invalid RLE compression')
        elif header == -128:
            pass
        else:
            length = 1 - header
            if src + 1 <= len(data) and dst + length <= size:
                result[dst:dst + length] = [data[src]] * length
                src += 1
                dst += length
            else:
                raise ValueError('Invalid RLE compression')
    if dst < size:
        raise ValueError('Expected %d bytes but decoded only %d bytes' % (
            size, dst))
    return bytes(result)
