TLSharp/TLSharp.Core/MTProto/Serializers.cs

89 lines
2.6 KiB
C#
Raw Permalink Normal View History

2015-09-28 04:01:17 +02:00
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace TLSharp.Core.MTProto
{
2016-04-18 12:50:57 +02:00
public class Serializers
{
2015-09-28 04:01:17 +02:00
2016-04-18 12:50:57 +02:00
public static class Bytes
{
public static byte[] Read(BinaryReader binaryReader)
2016-04-18 12:50:57 +02:00
{
2015-09-28 04:01:17 +02:00
byte firstByte = binaryReader.ReadByte();
int len, padding;
2016-04-18 12:50:57 +02:00
if (firstByte == 254)
{
2015-09-28 04:01:17 +02:00
len = binaryReader.ReadByte() | (binaryReader.ReadByte() << 8) | (binaryReader.ReadByte() << 16);
2016-04-18 12:50:57 +02:00
padding = len % 4;
}
else {
2015-09-28 04:01:17 +02:00
len = firstByte;
padding = (len + 1) % 4;
}
byte[] data = binaryReader.ReadBytes(len);
2016-04-18 12:50:57 +02:00
if (padding > 0)
{
2015-09-28 04:01:17 +02:00
padding = 4 - padding;
binaryReader.ReadBytes(padding);
}
return data;
}
public static BinaryWriter Write(BinaryWriter binaryWriter, byte[] data)
2016-04-18 12:50:57 +02:00
{
2015-09-28 04:01:17 +02:00
int padding;
2016-04-18 12:50:57 +02:00
if (data.Length < 254)
{
padding = (data.Length + 1) % 4;
if (padding != 0)
{
2015-09-28 04:01:17 +02:00
padding = 4 - padding;
}
2016-04-18 12:50:57 +02:00
binaryWriter.Write((byte)data.Length);
2015-09-28 04:01:17 +02:00
binaryWriter.Write(data);
2016-04-18 12:50:57 +02:00
}
else {
padding = (data.Length) % 4;
if (padding != 0)
{
2015-09-28 04:01:17 +02:00
padding = 4 - padding;
}
binaryWriter.Write((byte)254);
binaryWriter.Write((byte)(data.Length));
binaryWriter.Write((byte)(data.Length >> 8));
binaryWriter.Write((byte)(data.Length >> 16));
binaryWriter.Write(data);
}
2016-04-18 12:50:57 +02:00
for (int i = 0; i < padding; i++)
{
2015-09-28 04:01:17 +02:00
binaryWriter.Write((byte)0);
}
return binaryWriter;
}
}
2016-04-18 12:50:57 +02:00
public static class String
{
public static string Read(BinaryReader reader)
2016-04-18 12:50:57 +02:00
{
byte[] data = Bytes.Read(reader);
2015-09-28 04:01:17 +02:00
return Encoding.UTF8.GetString(data, 0, data.Length);
}
public static BinaryWriter Write(BinaryWriter writer, string str)
2016-04-18 12:50:57 +02:00
{
return Bytes.Write(writer, Encoding.UTF8.GetBytes(str));
2015-09-28 04:01:17 +02:00
}
}
}
}