Declaration of a message type.
| 58 | |
| 59 | |
| 60 | class MessageDeclaration(object): |
| 61 | ''' Declaration of a message type. ''' |
| 62 | |
| 63 | |
| 64 | def __init__(self, tag, *fields): |
| 65 | ''' Declares a message. |
| 66 | |
| 67 | @param tag: the tag used to identify the message type |
| 68 | @param fields: the fields declared for the message |
| 69 | ''' |
| 70 | |
| 71 | self.__tag = tag |
| 72 | self.__fields = fields |
| 73 | |
| 74 | self.__type = collections.namedtuple(self.__tag, ['tag'] + [field.name |
| 75 | for field |
| 76 | in self.__fields]) |
| 77 | |
| 78 | |
| 79 | @property |
| 80 | def tag(self): |
| 81 | ''' Returns the tag. ''' |
| 82 | |
| 83 | return self.__tag |
| 84 | |
| 85 | |
| 86 | def lex(self, load): |
| 87 | ''' Lex the message. ''' |
| 88 | |
| 89 | return self(**{field.name : field.lex(value) |
| 90 | for field, value |
| 91 | in itertools.izip(self.__fields, |
| 92 | load)}) |
| 93 | |
| 94 | |
| 95 | def format(self, message): |
| 96 | ''' Format the message. ''' |
| 97 | |
| 98 | # Format the values in the message skipping the first value as it is the tag |
| 99 | return [field.format(value) |
| 100 | for field, value |
| 101 | in itertools.izip(self.__fields, |
| 102 | message[1:])] |
| 103 | |
| 104 | |
| 105 | def __call__(self, *args, **kwargs): |
| 106 | return self.__type(tag = self.__tag, *args, **kwargs) |
| 107 | |
| 108 | |
| 109 |