encoder.py 850 Bytes
Newer Older
tlavocat's avatar
tlavocat committed
1
2
import sys
import struct
Swann Perarnau's avatar
Swann Perarnau committed
3
from ..isengard               import consts
tlavocat's avatar
tlavocat committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

class MPIDecoder:

    def unpack(self, to_unpack) :
        # length of the global message
        offset = 0
        fields = []
        while offset < len(to_unpack) :
            field_size  = struct.unpack_from('>I', to_unpack[offset:offset+4])[0]
            offset     += 4
            field       = to_unpack[offset:offset+field_size]
            offset     += field_size
            fields.append(field.decode(consts.encoding))
        return fields

    def pack(self, *fields) :
        packed  = None
        for field in fields :
            if packed == None :
                packed = struct.pack('>I', len(field))
            else :
                packed += struct.pack('>I', len(field))
            packed += bytes(field, consts.encoding)
        return packed;