<s> from __future__ import print_function <EOL> from Bits import Bits <EOL> class MetaBitStruct ( type ) : <EOL> def __init__ ( meta , classname , supers , classdict ) : <EOL> meta . _classdict = { key : val for key , val in classdict . items ( ) <EOL> if not key . startswith ( '<STR_LIT:_>' ) } <EOL> return type . __init__ ( meta , classname , supers , classdict ) <EOL> def __call__ ( self , * args , ** kwargs ) : <EOL> def_inst = super ( MetaBitStruct , self ) . __call__ ( * args , ** kwargs ) <EOL> fields = [ ( name , obj ) for name , obj in <EOL> def_inst . __dict__ . items ( ) if isinstance ( obj , BitField ) ] <EOL> fields . sort ( lambda ( n1 , o1 ) , ( n2 , o2 ) : cmp ( o2 . id , o1 . id ) ) <EOL> nbits = sum ( [ f . nbits for name , f in fields ] ) <EOL> name_prfx = def_inst . __class__ . __name__ <EOL> name_sufx = '<STR_LIT:_>' . join ( str ( x ) for x in args ) <EOL> class_name = "<STR_LIT>" . format ( name_prfx , name_sufx ) <EOL> bitstruct_class = type ( class_name , ( BitStruct , ) , self . _classdict ) <EOL> start_pos = <NUM_LIT:0> <EOL> bitstruct_class . _bitfields = { } <EOL> for attr_name , bitfield in fields : <EOL> end_pos = start_pos + bitfield . nbits <EOL> addr = slice ( start_pos , end_pos ) <EOL> start_pos = end_pos <EOL> bitstruct_class . _bitfields [ attr_name ] = addr <EOL> def create_getter ( addr ) : <EOL> return lambda self : self . __getitem__ ( addr ) <EOL> def create_setter ( addr ) : <EOL> return lambda self , value : self . __setitem__ ( addr , value ) <EOL> setattr ( bitstruct_class , attr_name , <EOL> property ( create_getter ( addr ) , <EOL> create_setter ( addr ) <EOL> ) <EOL> ) <EOL> if '<STR_LIT>' in def_inst . __class__ . __dict__ : <EOL> bitstruct_class . __str__ = def_inst . __class__ . __dict__ [ '<STR_LIT>' ] <EOL> bitstruct_inst = bitstruct_class ( nbits ) <EOL> bitstruct_inst . _module = def_inst . __class__ . __module__ <EOL> bitstruct_inst . _classname = def_inst . __class__ . __name__ <EOL> bitstruct_inst . _instantiate = '<STR_LIT>' . format ( <EOL> class_name = def_inst . __class__ . __name__ , <EOL> args = args , <EOL> ) <EOL> assert not kwargs <EOL> return bitstruct_inst <EOL> class BitStructDefinition ( object ) : <EOL> __metaclass__ = MetaBitStruct <EOL> class BitField ( object ) : <EOL> ids = <NUM_LIT:0> <EOL> def __init__ ( self , nbits ) : <EOL> self . nbits = nbits <EOL> self . id = BitField . ids <EOL> BitField . ids += <NUM_LIT:1> <EOL> class BitStruct ( Bits ) : <EOL> @ property <EOL> def bitfields ( self ) : <EOL> return self . _bitfields <EOL> def __call__ ( self ) : <EOL> return type ( self ) ( self . nbits ) <EOL> def __hash__ ( self ) : <EOL> return hash ( ( self . __class__ . __name__ , self . _uint ) ) </s>
