def encode(self, stream, complexType, topEncoder): packetFields = complexType.data() fieldToTag = self._processFields(packetFields.FIELDS) # Get all the fields that have data. encodeFields = [] for fieldName, fieldType in packetFields.FIELDS: rawField = packetFields.__getrawfield__(fieldName) if rawField.data() == PacketFieldType.UNSET: if PacketFieldType.GetAttribute(rawField, Optional, False) == True: continue else: raise PacketEncodingError("Field '{}' is unset and not marked as optional.".format(fieldName)) encodeFields.append((fieldName, rawField)) # Write the number of encoding fields into the stream stream.pack(self.FIELD_COUNT_PACK_CODE, len(encodeFields)) # Write the actual fields into the stream for fieldName, rawField in encodeFields: try: tag = fieldToTag[fieldName] stream.pack(self.FIELD_TAG_PACK_CODE, tag) topEncoder.encode(stream, rawField) except Exception as encodingException: raise PacketEncodingError("Error encoding field {}.".format(fieldName)) from encodingException
def _processFields(self, fields): autoTag = 0 fieldToTag = Bijection() for fieldName, fieldType in fields: if fieldName in fieldToTag: raise Exception("Duplicate Field") tag = PacketFieldType.GetAttribute(fieldType, ExplicitTag, None) if tag != None and tag in fieldToTag.inverse(): raise Exception("Duplicate Explicit Tag") if tag == None: while autoTag in fieldToTag.inverse(): autoTag += 1 tag = autoTag fieldToTag[fieldName] = tag return fieldToTag
def _getPackCode(self, fieldType): maxValue = PacketFieldType.GetAttribute(fieldType, MaxValue, self.DEFAULT_MAXVALUE) packCode = self._maxValueToPackCode(maxValue) return packCode
def decodeIterator(self, stream, uint, topDecoder): maxValue = PacketFieldType.GetAttribute(uint, MaxValue, self.DEFAULT_UINT_MAXVALUE) packCode = self._maxValueToPackCode(maxValue) uintData = yield from stream.unpackIterator(packCode) uint.setData(uintData)
def encode(self, stream, uint, topEncoder): maxValue = PacketFieldType.GetAttribute(uint, MaxValue, self.DEFAULT_UINT_MAXVALUE) packCode = self._maxValueToPackCode(maxValue) stream.pack(packCode, uint.data())
def _getPackCode(self, fieldType): maxValue = PacketFieldType.GetAttribute(fieldType, Bits, self.DEFAULT_BITS) packCode = self.SIZE_TO_PACKCODE_MAP[maxValue] return packCode