Returns an encoder for a message field.
487517
def MessageEncoder(field_number, is_repeated, is_packed):
  """"""

  tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  local_EncodeVarint = _EncodeVarint
  assert not is_packed
  if is_repeated:
    def EncodeRepeatedField(write, value):
      for element in value:
        write(tag)
        local_EncodeVarint(write, element.ByteSize())
        element._InternalSerialize(write)
    return EncodeRepeatedField
  else:
    def EncodeField(write, value):
      write(tag)
      local_EncodeVarint(write, value.ByteSize())
      return value._InternalSerialize(write)
    return EncodeField
1274267
private String encode(String message) {
        return message == null ? null : message.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
    }
993396
def EncodeMessageList(cls, message_list, packed_message_list):
    """"""
    # By default uncompress
    uncompressed_data = message_list.SerializeToString()
    packed_message_list.message_list = uncompressed_data

    compressed_data = zlib.compress(uncompressed_data)

    # Only compress if it buys us something.
    if len(compressed_data) < len(uncompressed_data):
      packed_message_list.compression = (
          rdf_flows.PackedMessageList.CompressionType.ZCOMPRESSION)
      packed_message_list.message_list = compressed_data
173021
def MessageToJson(message, include_fields=None):
    """"""
    result = _ProtoJsonApiTools.Get().encode_message(message)
    return _IncludeFields(result, message, include_fields)
598956
def encode_value_using_ma(message_attribute: int, value: Optional[Union[int, float]]) -> int:
    """"""
    if message_attribute == MA_TX3AC_100A:
        # TX-3AC in 100A mode; use value as-is, with 0xFE indicating null
        if value is None:
            return 0xfe
        return int(value)
    elif message_attribute == MA_TX3AC_10A:
        # TX-3AC in 10A mode; shift decimal point, with 0xFE indicating null
        if value is None:
            return 0xfe
        return int(value * 10)
    else:
        # Signed byte, with 0x80 indicating null
        if value is None:
            return 0x80
        elif value < 0:
            return 0x100 + int(value)
        return int(value)
937864
def _ConvertWrapperMessage(self, value, message):
    """"""
    field = message.DESCRIPTOR.fields_by_name['value']
    setattr(message, 'value', _ConvertScalarFieldValue(value, field))
244730
private int generateEncodeDecode(
        final StringBuilder sb,
        final String typeName,
        final List<Token> tokens,
        final boolean isMessage,
        final boolean isExtensible)
    {
        final char varName = Character.toLowerCase(typeName.charAt(0));
        final StringBuilder encode = new StringBuilder();
        final StringBuilder decode = new StringBuilder();
        final StringBuilder init = new StringBuilder();
        final StringBuilder rangeCheck = new StringBuilder();
        final StringBuilder nested = new StringBuilder();
        int currentOffset = 0;
        int gap;
        boolean extensionStarted = false;

        // Open all our methods
        generateEncodeDecodeOpen(encode, decode, rangeCheck, init, varName, typeName, isMessage, isExtensible);

        for (int i = 0; i < tokens.size(); i++)
        {
            final Token signalToken = tokens.get(i);
            final String propertyName = formatPropertyName(signalToken.name());

            switch (signalToken.signal())
            {
                case BEGIN_MESSAGE: // Check range *before* we encode setting the acting version to schema version
                    encode.append(String.format(
                        "\tif doRangeCheck {\n" +
                        "\t\tif err := %1$s.RangeCheck(%1$s.SbeSchemaVersion(), %1$s.SbeSchemaVersion());" +
                        " err != nil {\n" +
                        "\t\t\treturn err\n" +
                        "\t\t}\n" +
                        "\t}\n",
                        varName));
                    break;

                case END_MESSAGE:
                    // Newer version extra fields check
                    if (isExtensible && !extensionStarted)
                    {
                        generateExtensionCheck(decode, varName);
                        extensionStarted = true;
                    }

                    // Check range *after* we decode using the acting
                    // version of the encoded message
                    decode.append(String.format(
                        "\tif doRangeCheck {\n" +
                        "\t\tif err := %1$s.RangeCheck(actingVersion, %1$s.SbeSchemaVersion()); err != nil {\n" +
                        "\t\t\treturn err\n" +
                        "\t\t}\n" +
                        "\t}\n",
                        varName));
                    break;

                case BEGIN_ENUM:
                case BEGIN_SET:
                    currentOffset += generatePropertyEncodeDecode(
                        signalToken, typeName, encode, decode, currentOffset);
                    i += signalToken.componentTokenCount() - 1;
                    break;

                case BEGIN_COMPOSITE:
                    currentOffset += generatePropertyEncodeDecode(
                        signalToken, typeName, encode, decode, currentOffset);
                    i += signalToken.componentTokenCount() - 1;

                    rangeCheck.append(String.format(
                        "\tif err := %1$s.%2$s.RangeCheck(actingVersion, schemaVersion); err != nil {\n" +
                        "\t\treturn err\n" +
                        "\t}\n",
                        varName, propertyName));
                    break;

                case BEGIN_FIELD:
                    if (tokens.size() >= i + 1)
                    {
                        currentOffset += generateFieldEncodeDecode(
                            tokens.subList(i, tokens.size() - 1),
                            varName, currentOffset, encode, decode, rangeCheck, init);

                        // Encodings just move past the encoding token
                        if (tokens.get(i + 1).signal() == Signal.ENCODING)
                        {
                            i += 1;
                        }
                        else
                        {
                            i += signalToken.componentTokenCount() - 1;
                        }
                    }
                    break;

                case ENCODING:
                    gap = signalToken.offset() - currentOffset;
                    encode.append(generateEncodeOffset(gap, ""));
                    decode.append(generateDecodeOffset(gap, ""));
                    currentOffset += signalToken.encodedLength() + gap;
                    final String primitive = varName + "." + propertyName;

                    // Encode of a constant is a nullop and we want to
                    // initialize constant values.
                    if (signalToken.isConstantEncoding())
                    {
                        generateConstantInitPrimitive(init, primitive, signalToken);
                    }
                    else
                    {
                        generateEncodePrimitive(encode, varName, formatPropertyName(signalToken.name()), signalToken);
                    }

                    // Optional tokens also get initialized
                    if (signalToken.isOptionalEncoding())
                    {
                        generateOptionalInitPrimitive(init, primitive, signalToken);
                    }

                    generateDecodePrimitive(decode, primitive, signalToken);
                    generateRangeCheckPrimitive(rangeCheck, primitive, signalToken, signalToken.isOptionalEncoding());
                    break;

                case BEGIN_GROUP:
                    // Newer version extra fields check
                    if (isExtensible && !extensionStarted)
                    {
                        generateExtensionCheck(decode, varName);
                        extensionStarted = true;
                    }

                    // Write the group, saving any extra offset we need to skip
                    currentOffset += generateGroupEncodeDecode(
                        tokens.subList(i, tokens.size() - 1),
                        typeName,
                        encode, decode, rangeCheck, currentOffset);

                    // Recurse
                    gap = Math.max(0,
                        signalToken.encodedLength() -
                            generateEncodeDecode(
                                nested,
                                typeName + toUpperFirstChar(signalToken.name()),
                                tokens.subList(i + 5, tokens.size() - 1),
                                false, true));

                    // Group gap block length handling
                    encode.append(generateEncodeOffset(gap, "\t")).append("\t}\n");
                    decode.append(generateDecodeOffset(gap, "\t")).append("\t}\n");

                    // And we can move over this group to the END_GROUP
                    i += signalToken.componentTokenCount() - 1;
                    break;

                case END_GROUP:
                    // Newer version extra fields check
                    if (isExtensible && !extensionStarted)
                    {
                        generateExtensionCheck(decode, varName);
                    }
                    // Close out this group and unwind
                    generateEncodeDecodeClose(encode, decode, rangeCheck, init);
                    sb.append(encode).append(decode).append(rangeCheck).append(init).append(nested);
                    return currentOffset; // for gap calculations

                case BEGIN_VAR_DATA:
                    // Newer version extra fields check
                    if (isExtensible && !extensionStarted)
                    {
                        generateExtensionCheck(decode, varName);
                        extensionStarted = true;
                    }
                    currentOffset += generateVarDataEncodeDecode(
                        tokens.subList(i, tokens.size() - 1),
                        typeName,
                        encode, decode, rangeCheck, currentOffset);
                    // And we can move over this group
                    i += signalToken.componentTokenCount() - 1;
                    break;
            }
        }

        // You can use blockLength on both messages and groups (handled above)
        // to leave some space (akin to an offset).
        final Token endToken = tokens.get(tokens.size() - 1);
        if (endToken.signal() == Signal.END_MESSAGE)
        {
            gap = endToken.encodedLength() - currentOffset;
            encode.append(generateEncodeOffset(gap, ""));
            decode.append(generateDecodeOffset(gap, ""));
        }

        // Close out the methods and append
        generateEncodeDecodeClose(encode, decode, rangeCheck, init);
        sb.append(encode).append(decode).append(rangeCheck).append(init).append(nested);

        return currentOffset;
    }
1251358
def _EncodeUnknownFields(message):
    """"""
    source = _UNRECOGNIZED_FIELD_MAPPINGS.get(type(message))
    if source is None:
        return message
    # CopyProtoMessage uses _ProtoJsonApiTools, which uses this message. Use
    # the vanilla protojson-based copy function to avoid infinite recursion.
    result = _CopyProtoMessageVanillaProtoJson(message)
    pairs_field = message.field_by_name(source)
    if not isinstance(pairs_field, messages.MessageField):
        raise exceptions.InvalidUserInputError(
            'Invalid pairs field %s' % pairs_field)
    pairs_type = pairs_field.message_type
    value_field = pairs_type.field_by_name('value')
    value_variant = value_field.variant
    pairs = getattr(message, source)
    codec = _ProtoJsonApiTools.Get()
    for pair in pairs:
        encoded_value = codec.encode_field(value_field, pair.value)
        result.set_unrecognized_field(pair.key, encoded_value, value_variant)
    setattr(result, source, [])
    return result
262874
def encode(self, envelope, session, **kwargs):
		
		return WMessengerTextEnvelope(str(WHex(envelope.message())), meta=envelope)
721745
function encoder(mtype) {
  const gen = util.codegen([ 'm', 'w' ], mtype.name + '$encode')('if(!w)')('w=Writer.create()');
  let ref;

  // "when a message is serialized its known fields should be written sequentially by field number"
  const fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);

  for (let i = 0; i < fields.length; ++i) {
    const field = fields[i].resolve();
    const index = mtype._fieldsArray.indexOf(field);
    const type = field.resolvedType instanceof Enum ? 'int32' : field.type;
    const wireType = types.basic[type];
    ref = 'm' + util.safeProp(field.name);

    // Map fields
    if (field.map) {
      gen('if(%s && %s[Symbol.iterator]){', ref, ref)('for(var k of %s.keys()) {', ref)('w.uint32(%d).fork().uint32(%d).%s(k)', (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);
      if (wireType === undefined) {
        gen('types[%d].encode(%s.get(k),w.uint32(18).fork()).ldelim().ldelim()', index, ref); // can't be groups
      } else {
        gen('.uint32(%d).%s(%s.get(k)).ldelim()', 16 | wireType, type, ref);
      }
      gen('}');
      gen('} else if(%s!=null&&m.hasOwnProperty(%j)){', ref, field.name)('for(var ks=Object.keys(%s),i=0;i<ks.length;++i){', ref)('w.uint32(%i).fork().uint32(%i).%s(ks[i])', (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);
      if (wireType === undefined) {
        gen('types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()', index, ref); // can't be groups
      } else {
        gen('.uint32(%i).%s(%s[ks[i]]).ldelim()', 16 | wireType, type, ref);
      }
      gen('}')('}');

      // Repeated fields
    } else if (field.repeated) {
      gen('if(%s!=null&&%s.length){', ref, ref); // !== undefined && !== null

      // Packed repeated
      if (field.packed && types.packed[type] !== undefined) {
        gen('w.uint32(%i).fork()', (field.id << 3 | 2) >>> 0)('for(var i=0;i<%s.length;++i)', ref)('w.%s(%s[i])', type, ref)('w.ldelim()');

        // Non-packed
      } else {
        gen('for(var i=0;i<%s.length;++i)', ref);
        if (wireType === undefined) { genTypePartial(gen, field, index, ref + '[i]'); } else gen('w.uint32(%i).%s(%s[i])', (field.id << 3 | wireType) >>> 0, type, ref);

      }
      gen('}');

      // Non-repeated
    } else {
      if (field.optional) gen('if(%s!=null&&m.hasOwnProperty(%j))', ref, field.name); // !== undefined && !== null

      if (wireType === undefined) { genTypePartial(gen, field, index, ref); } else gen('w.uint32(%i).%s(%s)', (field.id << 3 | wireType) >>> 0, type, ref);

    }
  }

  return gen('return w');
}
722022
def encode(msg):
    
    msg = bytes(msg)
    return END + msg.replace(ESC, ESC + ESC_ESC).replace(END, ESC + ESC_END) + END
478556
def decode(self, envelope, session, **kwargs):
		
		return WMessengerBytesEnvelope(b64decode(envelope.message()), meta=envelope)
927562
def _IncludeFields(encoded_message, message, include_fields):
    """"""
    if include_fields is None:
        return encoded_message
    result = json.loads(encoded_message)
    for field_name in include_fields:
        try:
            value = _GetField(message, field_name.split('.'))
            nullvalue = None
            if isinstance(value, list):
                nullvalue = []
        except KeyError:
            raise exceptions.InvalidDataError(
                'No field named %s in message of type %s' % (
                    field_name, type(message)))
        _SetField(result, field_name.split('.'), nullvalue)
    return json.dumps(result)
216100
def MapSizer(field_descriptor, is_message_map):
  """"""

  # Can't look at field_descriptor.message_type._concrete_class because it may
  # not have been initialized yet.
  message_type = field_descriptor.message_type
  message_sizer = MessageSizer(field_descriptor.number, False, False)

  def FieldSize(map_value):
    total = 0
    for key in map_value:
      value = map_value[key]
      # It's wasteful to create the messages and throw them away one second
      # later since we'll do the same for the actual encode.  But there's not an
      # obvious way to avoid this within the current design without tons of code
      # duplication. For message map, value.ByteSize() should be called to
      # update the status.
      entry_msg = message_type._concrete_class(key=key, value=value)
      total += message_sizer(entry_msg)
      if is_message_map:
        value.ByteSize()
    return total

  return FieldSize
1175060
def _DecodeUnknownMessages(message, encoded_message, pair_type):
    """"""
    field_type = pair_type.value.type
    new_values = []
    all_field_names = [x.name for x in message.all_fields()]
    for name, value_dict in six.iteritems(encoded_message):
        if name in all_field_names:
            continue
        value = PyValueToMessage(field_type, value_dict)
        if pair_type.value.repeated:
            value = _AsMessageList(value)
        new_pair = pair_type(key=name, value=value)
        new_values.append(new_pair)
    return new_values
1050521
def _ConvertAnyMessage(self, value, message):
    """"""
    if isinstance(value, dict) and not value:
      return
    try:
      type_url = value['@type']
    except KeyError:
      raise ParseError('@type is missing when parsing any message.')

    sub_message = _CreateMessageFromTypeUrl(type_url)
    message_descriptor = sub_message.DESCRIPTOR
    full_name = message_descriptor.full_name
    if _IsWrapperMessage(message_descriptor):
      self._ConvertWrapperMessage(value['value'], sub_message)
    elif full_name in _WKTJSONMETHODS:
      methodcaller(
          _WKTJSONMETHODS[full_name][1], value['value'], sub_message)(self)
    else:
      del value['@type']
      self._ConvertFieldValuePair(value, sub_message)
    # Sets Any message
    message.value = sub_message.SerializeToString()
    message.type_url = type_url
317816
def MapDecoder(field_descriptor, new_default, is_message_map):
  """"""

  key = field_descriptor
  tag_bytes = encoder.TagBytes(field_descriptor.number,
                               wire_format.WIRETYPE_LENGTH_DELIMITED)
  tag_len = len(tag_bytes)
  local_DecodeVarint = _DecodeVarint
  # Can't read _concrete_class yet; might not be initialized.
  message_type = field_descriptor.message_type

  def DecodeMap(buffer, pos, end, message, field_dict):
    submsg = message_type._concrete_class()
    value = field_dict.get(key)
    if value is None:
      value = field_dict.setdefault(key, new_default(message))
    while 1:
      # Read length.
      (size, pos) = local_DecodeVarint(buffer, pos)
      new_pos = pos + size
      if new_pos > end:
        raise _DecodeError('Truncated message.')
      # Read sub-message.
      submsg.Clear()
      if submsg._InternalParse(buffer, pos, new_pos) != new_pos:
        # The only reason _InternalParse would return early is if it
        # encountered an end-group tag.
        raise _DecodeError('Unexpected end-group tag.')

      if is_message_map:
        value[submsg.key].MergeFrom(submsg.value)
      else:
        value[submsg.key] = submsg.value

      # Predict that the next tag is another copy of the same repeated field.
      pos = new_pos + tag_len
      if buffer[new_pos:pos] != tag_bytes or new_pos == end:
        # Prediction failed.  Return.
        return new_pos

  return DecodeMap