Return packed byte representation of the UDP header.
494205
def to_bytes(self):
        '''
        
        '''
        return struct.pack(UDP._PACKFMT, self._src, self._dst,
            self._len, self._checksum)
687613
def tobytes(self, prim, skipprepack = False):
        '''
        
        '''
        stream = BytesIO()
        self.tostream(prim, stream, skipprepack=skipprepack)
        return stream.getvalue()
588257
def byte(self):
        """"""
        flags = int(self._in_use) << 7 \
            | int(self._controller) << 6 \
            | int(self._bit5) << 5 \
            | int(self._bit4) << 4 \
            | int(self._used_before) << 1
        return flags
235103
def to_bytes(s, encoding=None, errors='strict'):
    """"""
    encoding = encoding or 'utf-8'

    if is_unicode(s):
        return s.encode(encoding, errors)
    elif is_strlike(s):
        return s
    else:
        if six.PY2:
            return str(s)
        else:
            return str(s).encode(encoding, errors)
638018
def unpack_ip_addr(addr):
    """"""
    if isinstance(addr, bytearray):
        addr = bytes(addr)
    return (socket.inet_ntoa(addr[0:4]), struct.unpack('!H', addr[4:6])[0])
1346174
def get_headers(msg):
    """"""
    headers = {}
    for k in msg.keys():
        # decode_header decodes header but does not convert charset, so these
        # may still be bytes, even in Python 3. However, if it's ASCII
        # only (hence unambiguous encoding), the header fields come back
        # as str (unicode) in Python 3.
        (header_txt, charset) = email.header.decode_header(msg[k])[0]
        if charset is not None:
            header_txt = header_txt.decode(charset)
        headers[k] = header_txt
    return headers
839402
def packet(tag, blob):
    """"""
    assert len(blob) < 2**32

    if len(blob) < 2**8:
        length_type = 0
    elif len(blob) < 2**16:
        length_type = 1
    else:
        length_type = 2

    fmt = ['>B', '>H', '>L'][length_type]
    leading_byte = 0x80 | (tag << 2) | (length_type)
    return struct.pack('>B', leading_byte) + util.prefix_len(fmt, blob)
926732
def pack_into(self, buf, offset, write_payload):
    
    return self._get_framed(buf, offset, write_payload)
994842
def parse_packet(data, format=None):
    
    unpacked = struct.unpack(BASE_FORMAT, data[:_FORMAT_SIZE])
    psize, protocol, mac, gateway, time, ptype = unpacked
    header = Header(psize, protocol, mac, gateway, time, ptype)
    return header, data[_FORMAT_SIZE:]
1236011
def _double_as_bytes(dval):
    ""
    tmp = list(struct.unpack('8B',struct.pack('d', dval)))
    if not _big_endian:
        tmp.reverse()
    return tmp
680004
def read_raw(self, length, *, error=None):
        """"""
        if length is None:
            length = len(self)

        raw = dict(
            packet=self._read_fileng(length),
            error=error or None,
        )

        return raw
29034
def parse_dbus_header(header):
    """"""
    if six.indexbytes(header, 0) == ord('l'):
        endian = '<'
    elif six.indexbytes(header, 0) == ord('B'):
        endian = '>'
    else:
        raise ValueError('illegal endianness')
    if not 1 <= six.indexbytes(header, 1) <= 4:
        raise ValueError('illegel message type')
    if struct.unpack(endian + 'I', header[8:12])[0] == 0:
        raise ValueError('illegal serial number')
    harrlen = struct.unpack(endian + 'I', header[12:16])[0]
    padlen = (8 - harrlen) % 8
    bodylen = struct.unpack(endian + 'I', header[4:8])[0]
    return 16 + harrlen + padlen + bodylen
1372072
def encode(self, b64=False):
        """"""
        encoded_payload = b''
        for pkt in self.packets:
            encoded_packet = pkt.encode(b64=b64)
            packet_len = len(encoded_packet)
            if b64:
                encoded_payload += str(packet_len).encode('utf-8') + b':' + \
                    encoded_packet
            else:
                binary_len = b''
                while packet_len != 0:
                    binary_len = six.int2byte(packet_len % 10) + binary_len
                    packet_len = int(packet_len / 10)
                if not pkt.binary:
                    encoded_payload += b'\0'
                else:
                    encoded_payload += b'\1'
                encoded_payload += binary_len + b'\xff' + encoded_packet
        return encoded_payload
97279
def bytes(self):
        """"""
        byteout = bytearray()
        for i in range(1, 15):
            key = 'd' + str(i)
            if self._userdata[key] is not None:
                byteout.append(self._userdata[key])
            else:
                byteout.append(0x00)
        return byteout
1199197
def encode(self):
        """"""
        if len(self.data) == 0:
            log.debug("Encoding an empty DAT packet")
        data = self.data
        if not isinstance(self.data, bytes):
            data = self.data.encode('ascii')
        fmt = b"!HH%ds" % len(data)
        self.buffer = struct.pack(fmt,
                                  self.opcode,
                                  self.blocknumber,
                                  data)
        return self
918745
def reply_bytes(self, request):
        """"""
        flags = struct.pack("<i", self._flags)
        cursor_id = struct.pack("<q", self._cursor_id)
        starting_from = struct.pack("<i", self._starting_from)
        number_returned = struct.pack("<i", len(self._docs))
        reply_id = random.randint(0, 1000000)
        response_to = request.request_id

        data = b''.join([flags, cursor_id, starting_from, number_returned])
        data += b''.join([bson.BSON.encode(doc) for doc in self._docs])

        message = struct.pack("<i", 16 + len(data))
        message += struct.pack("<i", reply_id)
        message += struct.pack("<i", response_to)
        message += struct.pack("<i", OP_REPLY)
        return message + data
1371869
def pack_bytes(self, obj_dict, encoding=None):
        """"""
        assert self.dict_to_bytes or self.dict_to_string
        encoding = encoding or self.default_encoding or 'utf-8'
        LOGGER.debug('%r encoding dict with encoding %s', self, encoding)
        if self.dict_to_bytes:
            return None, self.dict_to_bytes(obj_dict)
        try:
            return encoding, self.dict_to_string(obj_dict).encode(encoding)
        except LookupError as error:
            raise web.HTTPError(
                406, 'failed to encode result %r', error,
                reason='target charset {0} not found'.format(encoding))
        except UnicodeEncodeError as error:
            LOGGER.warning('failed to encode text as %s - %s, trying utf-8',
                           encoding, str(error))
            return 'utf-8', self.dict_to_string(obj_dict).encode('utf-8')