# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license

# Copyright (C) 2011,2017 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

"""DNS Wire Data Helper"""

import dns.exception


class WireData(bytes):
    # WireData is a binary type with stricter slicing

    def __getitem__(self, key):
        try:
            if isinstance(key, slice):
                # make sure we are not going outside of valid ranges,
                # do stricter control of boundaries than python does
                # by default

                for index in (key.start, key.stop):
                    if index is None:
                        continue
                    elif abs(index) > len(self):
                        raise dns.exception.FormError

                return WireData(super().__getitem__(key))
            return super().__getitem__(key)
        except IndexError:
            raise dns.exception.FormError

    def unwrap(self):
        return bytes(self)


def maybe_wrap(wire):
    if isinstance(wire, WireData):
        return wire
    elif isinstance(wire, bytes):
        return WireData(wire)
    elif isinstance(wire, str):
        return WireData(wire.encode())
    raise ValueError("unhandled type %s" % type(wire))
