TLSharp/TeleSharp.TL/ObjectDeserializer.cs

48 lines
1.4 KiB
C#
Raw Normal View History

2016-09-24 15:38:26 +02:00
using System;
using System.IO;
namespace TeleSharp.TL
{
public class ObjectUtils
{
public static object DeserializeObject(BinaryReader reader)
{
2017-04-13 08:38:01 +02:00
var Constructor = reader.ReadInt32();
2016-09-24 15:38:26 +02:00
object obj;
2017-04-13 08:38:01 +02:00
Type t = null;
try
{
2016-09-24 15:38:26 +02:00
t = TLContext.getType(Constructor);
obj = Activator.CreateInstance(t);
}
2017-04-13 08:38:01 +02:00
catch (Exception ex)
2016-09-24 15:38:26 +02:00
{
throw new InvalidDataException("Constructor Invalid Or Context.Init Not Called !", ex);
2016-09-24 15:38:26 +02:00
}
if (t.IsSubclassOf(typeof(TLMethod)))
{
2017-04-13 08:38:01 +02:00
((TLMethod) obj).deserializeResponse(reader);
2016-09-24 15:38:26 +02:00
return obj;
}
2017-04-13 08:38:01 +02:00
if (t.IsSubclassOf(typeof(TLObject)))
2016-09-24 15:38:26 +02:00
{
2017-04-13 08:38:01 +02:00
((TLObject) obj).DeserializeBody(reader);
2016-09-24 15:38:26 +02:00
return obj;
}
2017-04-13 08:38:01 +02:00
throw new NotImplementedException("Weird Type : " + t.Namespace + " | " + t.Name);
2016-09-24 15:38:26 +02:00
}
2017-04-13 08:38:01 +02:00
public static void SerializeObject(object obj, BinaryWriter writer)
2016-09-24 15:38:26 +02:00
{
2017-04-13 08:38:01 +02:00
((TLObject) obj).SerializeBody(writer);
2016-09-24 15:38:26 +02:00
}
2017-04-13 08:38:01 +02:00
2016-09-24 15:38:26 +02:00
public static TLVector<T> DeserializeVector<T>(BinaryReader reader)
{
if (reader.ReadInt32() != 481674261) throw new InvalidDataException("Bad Constructor");
2017-04-13 08:38:01 +02:00
var t = new TLVector<T>();
2016-09-24 15:38:26 +02:00
t.DeserializeBody(reader);
return t;
}
}
2017-04-13 08:38:01 +02:00
}