当前位置: 首页>>代码示例>>Python>>正文


Python ConstBitStream.readlist方法代码示例

本文整理汇总了Python中bitstring.ConstBitStream.readlist方法的典型用法代码示例。如果您正苦于以下问题:Python ConstBitStream.readlist方法的具体用法?Python ConstBitStream.readlist怎么用?Python ConstBitStream.readlist使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在bitstring.ConstBitStream的用法示例。


在下文中一共展示了ConstBitStream.readlist方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: from_bytes

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
    def from_bytes(cls, bitstream):
        '''
           +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
           |  /|    Priority   |    Weight     |  M Priority   |   M Weight    |
           | L +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
           | o |        Unused Flags     |L|p|R|           Loc-AFI             |
           | c +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
           |  \|                             Locator                           |
		   +-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        '''
        record = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the priorities and weights
        (record.priority, record.weight, record.m_priority,
         record.m_weight) = bitstream.readlist('4*uint:8')

        # Read over unused flags
        record.reserved = bitstream.read(13)

        # Read the flags
        (record.local,
         record.probed_locator,
         record.reachable) = bitstream.readlist('3*bool')

        # Read the locator
        record.address = read_afi_address_from_bitstream(bitstream)

        return record
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:37,代码来源:locator_record.py

示例2: mc_parser

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
def mc_parser():
    out, buff = yield

    while True:
        header_bytes = yield from buff.read(24)
        header = ConstBitStream(header_bytes)

        readlist_fmt = 'uint:8, uint:8, uint:16'
        magic, opcode, key_length = header.readlist(readlist_fmt)
        extras_length, data_type, status = header.readlist(readlist_fmt)
        total_body_length = header.read('uint:32')
        opaque = header.read('uint:32')
        cas = header.read('uint:64')

        extras = None
        if extras_length:
            extras = yield from buff.read(extras_length)

        key = None
        if key_length:
            key = yield from buff.read(key_length)

        value_length = total_body_length - (key_length + extras_length)
        value = None
        if value_length:
            value = yield from buff.read(value_length)

        out.feed_data(MCResponse(opcode, data_type, status, cas,
                                 extras, key, value))
开发者ID:patricklaw,项目名称:mc,代码行数:31,代码来源:parser.py

示例3: testReadList

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
 def testReadList(self):
     s = CBS("0b10001111001")
     t = s.readlist("pad:1, uint:3, pad:4, uint:3")
     self.assertEqual(t, [0, 1])
     s.pos = 0
     t = s.readlist("pad:1, pad:5")
     self.assertEqual(t, [])
     self.assertEqual(s.pos, 6)
     s.pos = 0
     t = s.readlist("pad:1, bin, pad:4, uint:3")
     self.assertEqual(t, ["000", 1])
     s.pos = 0
     t = s.readlist("pad, bin:3, pad:4, uint:3")
     self.assertEqual(t, ["000", 1])
开发者ID:carriercomm,项目名称:gecko-dev,代码行数:16,代码来源:test_constbitstream.py

示例4: parseAxisBlock

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
def parseAxisBlock(axBlkStr):
	ret = dict()
	if len(axBlkStr) != AX_BLK_SIZE:
		raise ValueError("Invalid passed string length")

	keys = ["status", "switches", "stopCode", "refPos", "motorPos",
	"posError", "auxPos", "vel", "torque", "analog"]

	statusKeys = ["moving", "motionMode1", "motionMode1", "findingEdge",
				  "homing", "homeP1Done", "homeP2Done", "coordMotion",
				  "movingNeg", "contourMode", "slewingMode", "stopping",
				  "finalDecel", "latchArmed", "offOnErrArmed", "motorOff"]

	# The fucking galil is little endian, so [:2] splits off the segment of the string we want, and [::-1] reverses it
	statusBs = ConstBitStream(bytes=axBlkStr[:2][::-1])

	# Status is 16 boolean values packed into a uint_16
	statusVals = statusBs.readlist(["uint:1"]*16)

	# zip flags and names into dict
	zipped = zip(statusKeys, statusVals)

	vals = [dict(zipped)]
	vals.extend(struct.unpack(AX_BLK_PARSE_STR, axBlkStr))

	ret = dict(zip(keys, vals))

	return ret
开发者ID:Caglow,项目名称:PyGalil,代码行数:30,代码来源:drParse.py

示例5: from_bytes

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
    def from_bytes(cls, bitstream):
        """
        Parse the given record and update properties accordingly
        """
        record = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the record TTL
        record.ttl = bitstream.read("uint:32")

        # Store the locator record count until we need it
        referral_count = bitstream.read("uint:8")

        # Store the EID prefix mask length until we need it
        eid_prefix_len = bitstream.read("uint:8")

        # Read the Negative Map_Reply action
        record.action = bitstream.read("uint:3")

        # Read the flags
        (record.authoritative, record.incomplete) = bitstream.readlist("2*bool")

        # Read reserved bits
        record._reserved1 = bitstream.read(11)

        # Read the signature count
        sig_count = bitstream.read("uint:4")

        # Read the map version
        record.map_version = bitstream.read("uint:12")

        # Read the EID prefix
        record.eid_prefix = read_afi_address_from_bitstream(bitstream, eid_prefix_len)

        # Read the locator records
        for dummy in range(referral_count):
            locator_record = LocatorRecord.from_bytes(bitstream)
            record.locator_records.append(locator_record)

        # TODO: Can't handle signatures yet! [LISP-Security]
        if sig_count:
            raise NotImplementedError("Cannot handle signatures yet")

        # Verify that the properties make sense
        record.sanitize()

        return record
开发者ID:hansomesong,项目名称:pylisp,代码行数:55,代码来源:map_referral_record.py

示例6: from_bytes

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
    def from_bytes(cls, bitstream):
        '''
        Parse the given packet and update properties accordingly
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the type
        type_nr = bitstream.read('uint:4')
        if type_nr != packet.message_type:
            msg = 'Invalid bitstream for a {0} packet'
            class_name = packet.__class__.__name__
            raise ValueError(msg.format(class_name))

        # Read the flags
        (packet.probe,
         packet.enlra_enabled,
         packet.security) = bitstream.readlist('3*bool')

        # Skip reserved bits
        packet._reserved1 = bitstream.read(17)

        # Store the record count until we need it
        record_count = bitstream.read('uint:8')

        # Read the nonce
        packet.nonce = bitstream.read('bytes:8')

        # Read the records
        for dummy in range(record_count):
            record = MapReplyRecord.from_bytes(bitstream)
            packet.records.append(record)

        # If the security flag is set then there should be security data left
        # TODO: deal with security flag [LISP-Security]
        if packet.security:
            raise NotImplementedError('Handling security data is not ' +
                                      'implemented yet')

        # Verify that the properties make sense
        packet.sanitize()

        return packet
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:51,代码来源:map_reply.py

示例7: from_bytes

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
    def from_bytes(cls, bitstream):
        '''
        Parse the given packet and update properties accordingly
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the source and destination ports
        (packet.source_port,
         packet.destination_port) = bitstream.readlist('2*uint:16')

        # Store the length
        length = bitstream.read('uint:16')
        if length < 8:
            raise ValueError('Invalid UDP length')

        # Read the checksum
        packet.checksum = bitstream.read('uint:16')

        # And the rest is payload
        payload_bytes = length - 8
        packet.payload = bitstream.read('bytes:%d' % payload_bytes)

        # LISP-specific handling
        if packet.source_port == 4341 or packet.destination_port == 4341:
            # Payload is a LISP data packet
            from pylisp.packet.lisp.data import DataPacket
            packet.payload = DataPacket.from_bytes(packet.payload)
        elif packet.source_port == 4342 or packet.destination_port == 4342:
            # Payload is a LISP control message
            from pylisp.packet.lisp.control.base import ControlMessage
            packet.payload = ControlMessage.from_bytes(packet.payload)

        # There should be no remaining bits
        if bitstream.pos != bitstream.len:
            raise ValueError('Bits remaining after processing packet')

        # Verify that the properties make sense
        packet.sanitize()

        return packet
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:49,代码来源:udp.py

示例8: extractXMP

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
 def extractXMP(self, filename):
     xmpStr = ""        
     # Can initialise from files, bytes, etc.
     try:
         s = ConstBitStream(filename = filename)
         # Search for ":xmpmeta" string in file
         keepSearching = True
         while keepSearching:
             keepSearching = False
             colonXmpmetaInHexStr = '0x3a786d706d657461'
             foundSt = s.find(colonXmpmetaInHexStr, bytealigned=True)
             if foundSt:
                 byteStart = (int(foundSt[0])//8)
                 # The start of data can be "<xmp:xmpmeta" or "<x:xmpmeta"
                 s.bytepos = byteStart - 4
                 prevals = s.peeklist("4*uint:8")
                 prestr = ''.join(chr(i) for i in prevals)
     #            print (prestr, prestr[2:])
                 if prestr == "<xmp":
                     byteStart = byteStart - 4
                     prefix = "0x3c2f786d70"  # "<\xmp" in hex
                 elif prestr[2:] == "<x":
                     byteStart = byteStart - 2
                     prefix = "0x3c2f78"  # "<\x" in hex
                 else:
     #                print ("Cont")
                     keepSearching = True
                     continue
     #            print("Found start code at byte offset %d." % byteStart)
                 foundEnd = s.find(prefix + colonXmpmetaInHexStr, bytealigned=True)
                 if foundEnd:
                     byteEnd = (int(foundEnd[0])//8)
                     s.bytepos = byteStart
     #                print("Found end code at byte offset %d." % byteEnd)
                     xmpBytes = s.readlist(str(byteEnd-byteStart+len(prefix)//2+9) +"*uint:8")
                     xmpStr = ''.join(chr(i) for i in xmpBytes)
                     #if "Rating" in xmpStr:
     #                print (xmpStr)
     except:
         xmpStr = ""
     return xmpStr
开发者ID:,项目名称:,代码行数:43,代码来源:

示例9: from_bytes

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
    def from_bytes(cls, bitstream, prefix_len=None):
        '''
        Look at the type of the message, instantiate the correct class and
        let it parse the message.
        '''
        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Skip the reserved bits
        rsvd1 = bitstream.read(8)

        # Read the flags (and ignore them, no flags are defined yet)
        flags = bitstream.readlist('8*bool')

        # Read the type
        type_nr = bitstream.read('uint:8')

        # Skip the reserved bits
        rsvd2 = bitstream.read(8)

        # Read the length
        length = bitstream.read('uint:16')

        # Read the data
        data = bitstream.read(length * 8)

        # Look for the right class
        from pylisp.utils.lcaf import type_registry
        type_class = type_registry.get_type_class(type_nr)
        if not type_class:
            raise ValueError("Can't handle LCAF type {0}".format(type_nr))

        # Let the specific class handle it from now on
        return type_class._from_data_bytes(data, prefix_len,
                                           rsvd1, flags, rsvd2)
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:41,代码来源:base.py

示例10: from_bytes

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
    def from_bytes(cls, bitstream):
        r'''
        Parse the given packet and update properties accordingly

        >>> data_hex = ('80000000'
        ...             '6e000000004811402a0086400001ffff'
        ...             '000000000000000a2a02000000000000'
        ...             '0000000000000000'
        ...             '10f610f600487396'
        ...             '10000201ee924adef97a97d700000001'
        ...             '57c3c44d00015f61535d0002200109e0'
        ...             '85000b000000000000000001000f0002'
        ...             '2a020000000000000000000000000000')
        >>> data = data_hex.decode('hex')
        >>> message = EncapsulatedControlMessage.from_bytes(data)
        >>> message.security
        False
        >>> message.ddt_originated
        False
        >>> bytes(message.payload)
        ... # doctest: +ELLIPSIS
        'n\x00\x00\x00\x00H\x11...\x00\x00'
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the type
        type_nr = bitstream.read('uint:4')
        if type_nr != packet.message_type:
            msg = 'Invalid bitstream for a {0} packet'
            class_name = packet.__class__.__name__
            raise ValueError(msg.format(class_name))

        # Read the flags
        (packet.security,
         packet.ddt_originated) = bitstream.readlist('2*bool')

        # Read reserved bits
        packet._reserved1 = bitstream.read(26)

        # If the security flag is set then there should be security data here
        # TODO: deal with security flag [LISP-Security]
        if packet.security:
            raise NotImplementedError('Handling security data is not ' +
                                      'implemented yet')

        # The rest of the packet is payload
        remaining = bitstream[bitstream.pos:]

        # Parse IP packet
        if len(remaining):
            ip_version = remaining.peek('uint:4')
            if ip_version == 4:
                packet.payload = IPv4Packet.from_bytes(remaining)
            elif ip_version == 6:
                packet.payload = IPv6Packet.from_bytes(remaining)
            else:
                packet.payload = remaining.bytes

        # Verify that the properties make sense
        packet.sanitize()

        return packet
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:71,代码来源:encapsulated_control_message.py

示例11: from_bytes

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
    def from_bytes(cls, bitstream, decode_payload=True):
        '''
        Parse the given packet and update properties accordingly
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the version
        version = bitstream.read('uint:4')
        if version != packet.version:
            raise ValueError('Provided bytes do not contain an IPv4 packet')

        # Read the header length
        ihl = bitstream.read('uint:4')
        if ihl < 5:
            raise ValueError('Invalid IPv4 header length')

        # Now that we know the length of the header we store it to be able
        # to easily recalculate the header checksum later
        remaining_header_bits = (ihl * 32) - 8
        header = (BitStream('uint:4=4, uint:4=%d' % ihl) +
                  bitstream.peek(remaining_header_bits))

        # Read the type of service
        packet.tos = bitstream.read('uint:8')

        # Read the total length
        total_length = bitstream.read('uint:16')
        if total_length < ihl * 4:
            raise ValueError('Total length is shorter than the header')

        # Read the identification
        packet.identification = bitstream.read('uint:16')

        # Read the flags
        (reserved,
         packet.dont_fragment,
         packet.more_fragments) = bitstream.readlist('3*bool')

        if reserved:
            raise ValueError('Reserved flag must be 0')

        # Read the fragment offset
        packet.fragment_offset = bitstream.read('uint:13')

        # Read the TTL
        packet.ttl = bitstream.read('uint:8')

        # Read the protocol number
        packet.protocol = bitstream.read('uint:8')

        # Read the header checksum
        header_checksum = bitstream.read('uint:16')

        # Set the checksum bits in the header to 0 and re-calculate
        header[80:96] = BitStream(16)
        my_checksum = checksum.ones_complement(header.bytes)

        if my_checksum != header_checksum:
            raise ValueError('Header checksum does not match')

        # Read the source and destination addresses
        packet.source = IPv4Address(bitstream.read('uint:32'))
        packet.destination = IPv4Address(bitstream.read('uint:32'))

        # Read the options
        option_len = (ihl - 5) * 4
        packet.options = bitstream.read('bytes:%d' % option_len)

        # And the rest is payload
        payload_bytes = (total_length) - (ihl * 4)
        packet.payload = bitstream.read('bytes:%d' % payload_bytes)

        if decode_payload:
            payload_class = protocol_registry.get_type_class(packet.protocol)
            if payload_class:
                packet.payload = payload_class.from_bytes(packet.payload)

        # There should be no remaining bits
        if bitstream.pos != bitstream.len:
            raise ValueError('Bits remaining after processing packet')

        # Verify that the properties make sense
        packet.sanitize()

        return packet
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:94,代码来源:ipv4.py

示例12: from_bytes

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
    def from_bytes(cls, bitstream, decode_payload=True):
        r'''
        Parse the given packet and update properties accordingly

        >>> data_hex = ('c033d3c10000000745c0005835400000'
        ...             'ff06094a254d38204d45d1a30016f597'
        ...             'a1c3c7406718bf1b50180ff0793f0000'
        ...             'b555e59ff5ba6aad33d875c600fd8c1f'
        ...             'c5268078f365ee199179fbd09d09d690'
        ...             '193622a6b70bcbc7bf5f20dda4258801')
        >>> data = data_hex.decode('hex')
        >>> message = DataPacket.from_bytes(data)
        >>> message.echo_nonce_request
        False
        >>> message.nonce
        '3\xd3\xc1'
        >>> message.source_map_version
        >>> message.destination_map_version
        >>> message.lsb
        ... # doctest: +ELLIPSIS
        [True, True, True, False, False, ..., False, False, False, False]
        >>> message.instance_id
        >>> bytes(message.payload)
        ... # doctest: +ELLIPSIS
        'E\xc0\[email protected]\x00\x00\xff\x06\tJ%M8...\xdd\xa4%\x88\x01'
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the flags
        (nonce_present,
         lsb_enabled,
         packet.echo_nonce_request,
         map_version_present,
         instance_id_present) = bitstream.readlist('5*bool')

        # Skip over reserved bits
        bitstream.read(3)

        # Parse nonce or map versions
        if nonce_present:
            # Nonce: yes, versions: no
            packet.nonce = bitstream.read('bytes:3')
            packet.source_map_version = None
            packet.destination_map_version = None
        elif map_version_present:
            # Nonce: no, versions: yes
            packet.nonce = None
            (packet.source_map_version,
             packet.destination_map_version) = bitstream.readlist('2*uint:12')
        else:
            # Nonce: no, versions: no
            packet.nonce = None
            packet.source_map_version = None
            packet.destination_map_version = None

            # Skip over the nonce/map-version bits
            bitstream.read(24)

        # Parse instance-id
        if instance_id_present:
            packet.instance_id = bitstream.read('uint:24')

            # 8 bits remaining for LSB
            lsb_bits = 8
        else:
            # 32 bits remaining for LSB
            lsb_bits = 32

        # Parse LSBs
        if lsb_enabled:
            packet.lsb = bitstream.readlist('%d*bool' % lsb_bits)

            # Reverse for readability: least significant locator-bit first
            packet.lsb.reverse()
        else:
            # Skip over the LSBs
            bitstream.read(lsb_bits)

        # The rest of the packet is payload
        remaining = bitstream[bitstream.pos:]

        # Parse IP packet
        if len(remaining):
            ip_version = remaining.peek('uint:4')
            if ip_version == 4:
                packet.payload = IPv4Packet.from_bytes(remaining, decode_payload=decode_payload)
            elif ip_version == 6:
                packet.payload = IPv6Packet.from_bytes(remaining, decode_payload=decode_payload)
            else:
                packet.payload = remaining.bytes

        # Verify that the properties make sense
        packet.sanitize()
#.........这里部分代码省略.........
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:103,代码来源:data.py

示例13: from_bytes

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
    def from_bytes(cls, bitstream):
        r'''
        Parse the given packet and update properties accordingly

        >>> data_hex = ('13000001ae92b5574f849cd00001ac10'
        ...             '1f0300015cfe1cbd00200001ac101f01')
        >>> data = data_hex.decode('hex')
        >>> message = ControlMessage.from_bytes(data)
        >>> message.message_type
        1
        >>> message.authoritative
        False
        >>> message.probe
        True
        >>> message.smr
        True
        >>> message.pitr
        False
        >>> message.smr_invoked
        False
        >>> message.nonce
        '\xae\x92\xb5WO\x84\x9c\xd0'
        >>> message.source_eid
        IPv4Address(u'172.16.31.3')
        >>> message.itr_rlocs
        [IPv4Address(u'92.254.28.189')]
        >>> message.eid_prefixes
        [IPv4Network(u'172.16.31.1/32')]
        >>> message.map_reply
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the message type
        type_nr = bitstream.read('uint:4')
        if type_nr != packet.message_type:
            msg = 'Invalid bitstream for a {0} packet'
            class_name = packet.__class__.__name__
            raise ValueError(msg.format(class_name))

        # Read the flags
        (packet.authoritative,
         map_data_present,
         packet.probe,
         packet.smr,
         packet.pitr,
         packet.smr_invoked) = bitstream.readlist('6*bool')

        # Skip over reserved bits
        packet._reserved1 = bitstream.read(9)

        # Save the IRC until we reach the actual data
        irc = bitstream.read('uint:5')

        # Save the record count until we reach the actual data
        record_count = bitstream.read('uint:8')

        # Read the nonce
        packet.nonce = bitstream.read('bytes:8')

        # Read the source EID
        packet.source_eid = read_afi_address_from_bitstream(bitstream)

        # Read the ITR RLOCs
        for dummy in range(irc + 1):
            itr_rloc = read_afi_address_from_bitstream(bitstream)
            packet.itr_rlocs.append(itr_rloc)

        # Read the EIDs
        for dummy in range(record_count):
            # A records begins with 8 reserved bits: skip
            bitstream.read(8)

            # Read 8 bits for the prefix length
            prefix_len = bitstream.read('uint:8')

            # Then an AFI style prefix
            eid_prefix = read_afi_address_from_bitstream(bitstream, prefix_len)
            packet.eid_prefixes.append(eid_prefix)

        # Read the map-reply record if present
        if map_data_present:
            packet.map_reply = MapReplyRecord.from_bytes(bitstream)

        # Verify that the properties make sense
        packet.sanitize()

        return packet
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:96,代码来源:map_request.py

示例14: from_bytes

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]
    def from_bytes(cls, bitstream):
		
        '''	
				0                   1                   2                   3
				0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
			   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
			   |Type=2 |P|E|S|          Reserved               | Record Count  |
			   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
			   |                         Nonce . . .                           |
			   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
			   |                         . . . Nonce                           |
		   +-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
		   |   |                          Record TTL                           |
		   |   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
		   R   | Locator Count | EID mask-len  | ACT |A|      Reserved         |
		   e   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
		   c   | Rsvd  |  Map-Version Number   |       EID-Prefix-AFI          |
		   o   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
		   r   |                          EID-Prefix                           |
		   d   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
		   |  /|    Priority   |    Weight     |  M Priority   |   M Weight    |
		   | L +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
		   | o |        Unused Flags     |L|p|R|           Loc-AFI             |
		   | c +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
		   |  \|                             Locator                           |
		   +-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
		'''
		
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the type
        type_nr = bitstream.read('uint:4')
        if type_nr != packet.message_type:
            msg = 'Invalid bitstream for a {0} packet'
            class_name = packet.__class__.__name__
            raise ValueError(msg.format(class_name))

        # Read the flags
        (packet.probe,
         packet.enlra_enabled,
         packet.security) = bitstream.readlist('3*bool')

        # Skip reserved bits
        packet._reserved1 = bitstream.read(17)

        # Store the record count until we need it
        record_count = bitstream.read('uint:8')

        # Read the nonce
        packet.nonce = bitstream.read('bytes:8')


        # Read the records
        for dummy in range(record_count):
            record = MapReplyRecord.from_bytes(bitstream)
            packet.records.append(record)

        return packet
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:67,代码来源:map_reply.py

示例15: DenseChunk

# 需要导入模块: from bitstring import ConstBitStream [as 别名]
# 或者: from bitstring.ConstBitStream import readlist [as 别名]

#.........这里部分代码省略.........
        self._buf_pos = self._bitmap_size + (
            self._curr_elem >> 3 if self._elem_size == 0 else self._curr_elem * self._elem_size)

    @property
    def end(self):
        return self._end

    @property
    def eof(self):
        return False

    def get_coordinates(self):
        l = self._curr_elem
        coords = {}
        for i in xrange(len(self._start_pos) - 1, -1, -1):
            pos = self._start_pos[i] + l % self._chunk_len[i]
            coords[self._schema.dimensions[i].name] = pos
            coords[i] = pos
            l /= self._chunk_len[i]
        return coords

    def get_item(self):
        if self.end:
            return None

        if self._nullable:
            null = False
            pos_tmp = self._buf_pos
            bitmap_pos = self._curr_elem >> 3
            self._chunk_data_stream.bytepos = bitmap_pos
            if self._chunk_data_stream.read('uintle:8') & (1 << (self._curr_elem & 7)):
                null = True
            self._buf_pos = pos_tmp
            if null:
                return None

        return self._item_getter()

    def _get_int8(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        return self._chunk_data_stream.read('intle:8')

    def _get_int16(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        return self._chunk_data_stream.read('intle:16')

    def _get_int32(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        return self._chunk_data_stream.read('intle:32')

    def _get_int64(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        return self._chunk_data_stream.read('intle:64')

    def _get_uint8(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        return self._chunk_data_stream.read('uintle:8')

    def _get_uint16(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        return self._chunk_data_stream.read('uintle:16')

    def _get_uint32(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        return self._chunk_data_stream.read('uintle:32')

    def _get_uint64(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        return self._chunk_data_stream.read('uintle:64')

    def _get_float(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        return self._chunk_data_stream.read('floatle:32')

    def _get_double(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        return self._chunk_data_stream.read('floatle:64')

    def _get_char(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        return chr(self._chunk_data_stream.read('intle:8'))

    def _get_bool(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        b = self._chunk_data_stream.read('intle:8')
        return (b & (1 << (self._curr_elem & 7))) != 0

    def _get_string(self):
        self._chunk_data_stream.bytepos = self._buf_pos
        data_offset = self._chunk_data_stream.read('intle:32')
        _buf_pos = self._bitmap_size + data_offset + self._varying_offs
        self._chunk_data_stream.bytepos = _buf_pos

        s = self._chunk_data_stream.read('uintle:8')
        if s != 0:
            item_size = s
        else:
            (a, b, c, d) = self._chunk_data_stream.readlist('uintle:8, uintle:8, uintle:8, uintle:8')
            item_size = (a << 24) | (b << 16) | (c << 8) | d
        return str(self._chunk_data_stream.read('bytes:%d' % (item_size - 1)))
开发者ID:Paradigm4,项目名称:scidb4py,代码行数:104,代码来源:_dense_chunk.py


注:本文中的bitstring.ConstBitStream.readlist方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。