gruel_press.py 文件源码

python
阅读 35 收藏 0 点赞 0 评论 0

项目:solent 作者: solent-eng 项目源码 文件源码
def _create(self, message_h, **fields):
        '''
        Render the supplied message values to the bytearray.
        '''
        #
        # ensure that the fields match the schema
        if message_h not in self.gruel_protocol:
            raise Exception("No message exists matching [%s]"%message_h)
        message_stencil = self.gruel_protocol.get_message_stencil(
            message_h=message_h)
        set_sch = set(message_stencil.field_names())
        set_got = set(fields.keys())
        if set_sch != set_got:
            raise Exception("Inconsistent fields/want:%s/got:%s"%(
                str(set_sch), str(set_got)))
        #
        # render
        offset = 0
        for (field_h, field_dt) in message_stencil.items():
            field_value = fields[field_h]
            # struct docs: https://docs.python.org/3.1/library/struct.html
            #log('** o%s press %s %s'%(offset, field_h, field_value))
            if field_dt.name == 'u1':
                bsize = 1
                struct.pack_into(
                    '!B',        # fmt. B is unsigned char
                    self.arr,    # buffer
                    offset,      # offset
                    field_value)
                offset += bsize
            elif field_dt.name == 'u2':
                bsize = 2
                struct.pack_into(
                    '!H',        # fmt. H is unsigned short
                    self.arr,    # buffer
                    offset,      # offset
                    field_value)
                offset += bsize
            elif field_dt.name == 'vs':
                s_len = len(field_value)
                # first we do a two-byte length, network-endian
                bsize = 2
                struct.pack_into(
                    '!H',        # fmt. H is unsigned short
                    self.arr,    # buffer
                    offset,      # offset
                    s_len)
                offset += bsize
                # Now we put that string into the array. Emphasis: these
                # strings are not zero-terminated.
                struct.pack_into(
                    '%ss'%s_len, # fmt.
                    self.arr,    # buffer
                    offset,      # offset
                    bytes(field_value, 'utf8'))
                offset += s_len
            else:
                raise Exception("Datatype not recognised/handled: %s"%(
                    field_dt.name))
        return self.arr
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号