66import struct
77import sys
88import time
9+ import zlib
10+
11+ from df_data .type_codes import header_types , meta_types
912
1013CUR_DIR = os .path .dirname (os .path .realpath (__file__ ))
1114if CUR_DIR not in sys .path :
1215 sys .path .append (CUR_DIR )
1316del CUR_DIR
1417
15- from df_data .type_codes import header_types
16- from df_data .type_codes import meta_types
17-
1818
1919def create_message (json_meta : dict , data : bytearray = b'' ,
2020 data_type : "binary_types" = 0 ) -> bytearray :
@@ -27,9 +27,9 @@ def create_message(json_meta: dict, data: bytearray=b'',
2727
2828 """
2929 __check_data (data )
30-
31- header = __create_machine_header (json_meta , data , data_type )
3230 meta = __prepare_meta (json_meta )
31+ data = __compress (json_meta , data )
32+ header = __create_machine_header (json_meta , data , data_type )
3333
3434 return header + meta + data
3535
@@ -50,7 +50,8 @@ def parse_from_file(filename: str, nodata: bool=False) \
5050 meta = __parse_meta (meta_raw , header )
5151 data = b''
5252 if not nodata :
53- data = file .read (header ['data_len' ])
53+ data = __decompress (meta , file .read (header ['data_len' ]))
54+
5455 return header , meta , data
5556
5657
@@ -69,7 +70,10 @@ def parse_message(message: bytearray, nodata: bool=False) \
6970 data_start = 30 + header ['meta_len' ]
7071 data = b''
7172 if not nodata :
72- data = message [data_start :data_start + header ['data_len' ]]
73+ data = __decompress (
74+ meta ,
75+ message [data_start :data_start + header ['data_len' ]]
76+ )
7377 return header , meta , data
7478
7579
@@ -119,8 +123,32 @@ def get_messages_from_stream(data: bytearray) \
119123 data = data [last_pos :]
120124 return messages , data
121125
126+
122127get_messages_from_stream .header_re = re .compile (b"#!.{24}!#" , re .DOTALL )
123128
129+
130+ def __decompress (meta , data ):
131+ if "compression" in meta :
132+ if meta ["compression" ] == "zlib" :
133+ return zlib .decompress (data )
134+ else :
135+ raise NotImplementedError (
136+ "Only zlib compression supported"
137+ )
138+ return data
139+
140+
141+ def __compress (meta , data ):
142+ if "compression" in meta :
143+ if meta ["compression" ] == "zlib" :
144+ return zlib .compress (data )
145+ else :
146+ raise NotImplementedError (
147+ "Only zlib compression supported"
148+ )
149+ return data
150+
151+
124152
125153def __parse_meta (meta_raw , header ):
126154 if header ["meta_type" ] == meta_types ["JSON_METATYPE" ]:
0 commit comments