<s> import math <EOL> from bitstring import BitArray <EOL> from . struct import BreadStruct , build_struct <EOL> from . vendor import six <EOL> def new ( spec , type_name = '<STR_LIT>' , data = None ) : <EOL> struct = build_struct ( spec , type_name ) <EOL> if data is None : <EOL> data = BitArray ( bytearray ( int ( math . ceil ( len ( struct ) / <NUM_LIT> ) ) ) ) <EOL> if len ( struct ) > len ( data ) : <EOL> raise ValueError ( <EOL> ( "<STR_LIT>" <EOL> "<STR_LIT>" ) % <EOL> ( len ( struct ) , len ( data ) ) ) <EOL> struct . _set_data ( data [ : len ( struct ) ] ) <EOL> struct . _offset = <NUM_LIT:0> <EOL> return struct <EOL> def parse ( data_source , spec , type_name = '<STR_LIT>' ) : <EOL> if type ( data_source ) == str : <EOL> data_bits = BitArray ( bytes = six . b ( data_source ) ) <EOL> elif type ( data_source ) == list : <EOL> data_bits = BitArray ( bytes = data_source ) <EOL> else : <EOL> data_bits = BitArray ( data_source ) <EOL> return new ( spec , type_name = type_name , data = data_bits ) <EOL> def write ( parsed_obj , spec = None , filename = None ) : <EOL> """<STR_LIT>""" <EOL> if not isinstance ( parsed_obj , BreadStruct ) : <EOL> raise ValueError ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> if filename is not None : <EOL> with open ( filename , '<STR_LIT:wb>' ) as fp : <EOL> parsed_obj . _data_bits . tofile ( fp ) <EOL> else : <EOL> return bytearray ( parsed_obj . _data_bits . tobytes ( ) ) </s>
