summaryrefslogtreecommitdiffstats
path: root/scripts/automation/trex_control_plane/server/zipmsg.py
blob: 397ada1691d7b51dd654658b4590320eda9c13fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import zlib
import struct

class ZippedMsg:

    MSG_COMPRESS_THRESHOLD    = 256
    MSG_COMPRESS_HEADER_MAGIC = 0xABE85CEA

    def check_threshold (self, msg):
        return len(msg) >= self.MSG_COMPRESS_THRESHOLD

    def compress (self, msg):
        # compress
        compressed = zlib.compress(msg)
        new_msg = struct.pack(">II", self.MSG_COMPRESS_HEADER_MAGIC, len(msg)) + compressed
        return new_msg


    def decompress (self, msg):
        if len(msg) < 8:
            return None

        t = struct.unpack(">II", msg[:8])
        if (t[0] != self.MSG_COMPRESS_HEADER_MAGIC):
            return None

        x = zlib.decompress(msg[8:])
        if len(x) != t[1]:
            return None

        return x