TLSharp/TLSharp.Core/MTProto/Serializers.cs

99 lines
2.9 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)
{
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;
}
2016-04-18 12:50:57 +02:00
public static BinaryWriter write(BinaryWriter binaryWriter, byte[] data)
{
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)
{
2015-09-28 04:01:17 +02:00
byte[] data = Bytes.read(reader);
return Encoding.UTF8.GetString(data, 0, data.Length);
}
2016-04-18 12:50:57 +02:00
public static BinaryWriter write(BinaryWriter writer, string str)
{
2015-09-28 04:01:17 +02:00
return Bytes.write(writer, Encoding.UTF8.GetBytes(str));
}
}
2016-04-18 12:50:57 +02:00
public static string VectorToString<T>(List<T> list)
{
2015-09-28 04:01:17 +02:00
string[] tokens = new string[list.Count];
2016-04-18 12:50:57 +02:00
for (int i = 0; i < list.Count; i++)
{
2015-09-28 04:01:17 +02:00
tokens[i] = list[i].ToString();
}
return "[" + System.String.Join(", ", tokens) + "]";
}
}
}