<s> import struct <EOL> import zlib <EOL> def parse_from ( binary ) : <EOL> """<STR_LIT>""" <EOL> size = struct . unpack ( '<STR_LIT>' , binary [ <NUM_LIT:0> : <NUM_LIT:4> ] ) [ <NUM_LIT:0> ] <EOL> magic = struct . unpack ( '<STR_LIT>' , binary [ <NUM_LIT:4> : <NUM_LIT:5> ] ) [ <NUM_LIT:0> ] <EOL> checksum = struct . unpack ( '<STR_LIT>' , binary [ <NUM_LIT:5> : <NUM_LIT:9> ] ) [ <NUM_LIT:0> ] <EOL> payload = binary [ <NUM_LIT:9> : <NUM_LIT:9> + size ] <EOL> return Message ( payload , magic , checksum ) <EOL> class Message ( object ) : <EOL> """<STR_LIT>""" <EOL> MAGIC_IDENTIFIER_DEFAULT = <NUM_LIT:0> <EOL> def __init__ ( self , payload = None , magic = MAGIC_IDENTIFIER_DEFAULT , checksum = None ) : <EOL> self . magic = magic <EOL> self . checksum = checksum <EOL> self . payload = None <EOL> if payload is not None : <EOL> self . payload = str ( payload ) <EOL> if self . payload is not None and self . checksum is None : <EOL> self . checksum = self . calculate_checksum ( ) <EOL> def __str__ ( self ) : <EOL> return self . payload <EOL> def __eq__ ( self , other ) : <EOL> if isinstance ( other , self . __class__ ) : <EOL> return self . magic == other . magic and self . payload == other . payload and self . checksum == other . checksum <EOL> return False <EOL> def __ne__ ( self , other ) : <EOL> return not self . __eq__ ( other ) <EOL> def calculate_checksum ( self ) : <EOL> """<STR_LIT>""" <EOL> return zlib . crc32 ( self . payload ) <EOL> def is_valid ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . checksum == self . calculate_checksum ( ) <EOL> def encode ( self ) : <EOL> """<STR_LIT>""" <EOL> return struct . pack ( '<STR_LIT>' % len ( self . payload ) , self . magic , self . calculate_checksum ( ) , self . payload ) </s>
