# Path: utils.py
# class ProtocolViolation(Exception):
#     """Indicates that the communication protocol between this and a remote
#     client has been violated. In this case we abort from the communication."""
#     def __init__(self, reason="unknown"):
#         self.reason = reason
#     def __repr__(self):
#         return "ProtocolViolation(%s)"%self.reason


from utils import ProtocolViolation
from socket import inet_ntoa, inet_aton
import struct

class Str():
    @staticmethod
    def tobinary(obj):
        return obj.encode("ascii") + '\0'
    @staticmethod
    def frombinary(bdata):
        bytes, ch, bdata = bdata.partition('\0')
        if ch == '':
            raise ProtocolViolation
        try:
            return bytes.decode("ascii"), bdata
        except UnicodeDecodeError:
            raise ProtocolViolation

Hash = structfmt("<32s")

class VarInt():
    @staticmethod
    def frombinary(bdata):
        try:
            if ord(bdata[0]) <= 0xfc:
                return ord(bdata[0]), bdata[1:]
            if ord(bdata[0]) == 0xfd:
                return struct.unpack("<xH", bdata[:3])[0], bdata[3:]
            if ord(bdata[0]) == 0xfe:
                return struct.unpack("<xI", bdata[:5])[0], bdata[5:]
            if ord(bdata[0]) == 0xff:
                return struct.unpack("<xQ", bdata[:9])[0], bdata[9:]
        except (struct.error, IndexError):

# Path: utils.py
# class ProtocolViolation(Exception):
#     """Indicates that the communication protocol between this and a remote
#     client has been violated. In this case we abort from the communication."""
#     def __init__(self, reason="unknown"):
#         self.reason = reason
#     def __repr__(self):
#         return "ProtocolViolation(%s)"%self.reason


# Path: bserialize.py
from utils import ProtocolViolation
from socket import inet_ntoa, inet_aton
import struct


class Str():
    @staticmethod
    def tobinary(obj):
        return obj.encode("ascii") + '\0'
    @staticmethod
    def frombinary(bdata):
        bytes, ch, bdata = bdata.partition('\0')
        if ch == '':
            raise ProtocolViolation
        try:
            return bytes.decode("ascii"), bdata
        except UnicodeDecodeError:
            raise ProtocolViolation

Hash = structfmt("<32s")

class VarInt():
    @staticmethod
    def frombinary(bdata):
        try:
            if ord(bdata[0]) <= 0xfc:
                return ord(bdata[0]), bdata[1:]
            if ord(bdata[0]) == 0xfd:
                return struct.unpack("<xH", bdata[:3])[0], bdata[3:]
            if ord(bdata[0]) == 0xfe:
                return struct.unpack("<xI", bdata[:5])[0], bdata[5:]
            if ord(bdata[0]) == 0xff:
                return struct.unpack("<xQ", bdata[:9])[0], bdata[9:]
        except (struct.error, IndexError):

            raise ProtocolViolation