import six


def decode(string, encoding='utf-8'):
    """
    Decodes the binary string with the specified encoding (or passes through
    a non-binary string) and strips newlines off the end.

    :param string: The string, may be binary or non-binary but should be text
                   data.
    :param encoding: The encoding to use for a binary string. Defaults to utf-8.
    :returns: The decoded and stripped string.
    :raises TypeError: If the passed parameter is not a valid string.
    :raises UnicodeError: When decoding a binary string if there are encoding
                          errors.
    """
    if isinstance(string, six.text_type):
        return string.rstrip('\r\n')

    try:
        string = string.decode(encoding=encoding).rstrip('\r\n')
    except AttributeError:
        raise TypeError('Invalid type {} passed.'.format(type(string)))

    return string