
def is_empty(s):
    return s is None or s == ""


def split_quoted_string(s):
    result = []
    item = ""
    started = False
    for c in s:
        if c == '"' and not started:
            started = True
        elif c == '"' and started:
            result.append(item)
            item = ""
            started = False
        elif c == ' ' and not started:
            if item != '':
                result.append(item)
                item = ""
        else:
            item += c

    if item != '':
        result .append(item)

    return result


def safe_utf8_decode(s):
    """If string is a unicode string - return it as is, if string is a binary string - decode it with UTF-8

    :type s: str | unicode
    :rtype: unicode
    """
    if isinstance(s, unicode):
        return s
    elif isinstance(s, str):
        return s.decode('utf-8')
    else:
        return unicode(s)


def safe_string_repr(s, omit_quotes=False, encoding=None):
    """If object can be interpreted as unicode, then return it as unicode. Otherwise return __repr__ of its __str__.

    Could be useful for safe logging, when usually you want to get just plain string, but if there are some issues
    with encoding - at least get its Python representation.

    :type s: any
    :type omit_quotes: bool
    :type encoding: str
    :rtype: unicode
    """
    if isinstance(s, unicode):
        return s
    else:
        try:
            if encoding is not None:
                s = str(s).decode(encoding)

            return unicode(s)
        except UnicodeError:
            if omit_quotes and isinstance(s, basestring):
                return (u"%r" % (s,))[1:-1]
            else:
                return u"%r" % (str(s),)

