summaryrefslogtreecommitdiffstats
path: root/scripts/automation/trex_control_plane/stl/trex_stl_lib/utils/zipmsg.py
blob: a2a47927536c2b655b2e5f3f1a074585be32455c (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
33
34
35
36
37
38
39
40
41
42
43
44
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


    def is_compressed(self, msg):
        if len(msg) < 8:
            return False

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

        return True