private void SerializeDRecord(Bencoder e, DRecord rec)
        {
            e.StartDRecord();

            foreach (var kvp in rec.Values)
            {
                e.ByteString(TextEncoding.GetBytes(kvp.Key));

                if (kvp.Value is DNumber)
                {
                    SerializeDNumber(e, (DNumber)kvp.Value);
                }
                else if (kvp.Value is DString)
                {
                    SerializeDString(e, (DString)kvp.Value);
                }
                else /* kvp.Value is DRecord */
                {
                    Debug.Assert(kvp.Value is DRecord);
                    SerializeDRecord(e, (DRecord)kvp.Value);
                }
            }

            e.FinishDRecord();
        }
Beispiel #2
0
        public byte[] Encode(Message msg)
        {
            Bencoder encoder = new Bencoder();

            encoder.StartDictionary();

            encoder.ByteString(TextEncoding.GetBytes(SequenceNumberFieldName))
                   .Integer(msg.SequenceNumber)
                   .ByteString(TextEncoding.GetBytes(AckNumberFieldName))
                   .Integer(msg.AckNumber)
                   .ByteString(TextEncoding.GetBytes(OpCodeFieldName))
                   .Integer((long)msg.OpCode);

            foreach (string k in msg.Attributes.Keys)
            {
                encoder.ByteString(TextEncoding.GetBytes(k));

                object value = msg.Attributes[k];

                if (typeof(long).IsAssignableFrom(value.GetType()))
                {
                    encoder.Integer((long)value);
                }
                else if (value is DNumber)
                {
                    SerializeDNumber(encoder, (DNumber)value);
                }
                else if (value is string)
                {
                    encoder.ByteString(TextEncoding.GetBytes((string)value));
                }
                else if (value is DString)
                {
                    SerializeDString(encoder, (DString)value);
                }
                else if (value is DRecord)
                {
                    SerializeDRecord(encoder, (DRecord)value);
                }
                else
                {
                    throw new NotImplementedException();
                }
            }

            encoder.FinishDictionary();

            return encoder.Encoded;
        }