Commit 674785f1 authored by mercury233's avatar mercury233

add WriteUnicodeAutoLength, update WriteUnicode

parent 8e4d611a
...@@ -84,9 +84,8 @@ namespace WindBot.Game ...@@ -84,9 +84,8 @@ namespace WindBot.Game
public void Chat(string message) public void Chat(string message)
{ {
byte[] content = Encoding.Unicode.GetBytes(message + "\0");
BinaryWriter chat = GamePacketFactory.Create(CtosMessage.Chat); BinaryWriter chat = GamePacketFactory.Create(CtosMessage.Chat);
chat.Write(content); chat.WriteUnicodeAutoLength(message, 255);
Connection.Send(chat); Connection.Send(chat);
} }
......
...@@ -6,15 +6,40 @@ namespace YGOSharp.Network.Utils ...@@ -6,15 +6,40 @@ namespace YGOSharp.Network.Utils
{ {
public static class BinaryExtensions public static class BinaryExtensions
{ {
// fixed length strings
public static void WriteUnicode(this BinaryWriter writer, string text, int len) public static void WriteUnicode(this BinaryWriter writer, string text, int len)
{ {
byte[] unicode = Encoding.Unicode.GetBytes(text); byte[] unicode = Encoding.Unicode.GetBytes(text);
byte[] result = new byte[len * 2]; byte[] result = new byte[len * 2];
int max = len * 2 - 2; int copy = unicode.Length;
Array.Copy(unicode, result, unicode.Length > max ? max : unicode.Length); if (unicode.Length > len * 2 - 2)
{
copy = len * 2 - 2;
#if DEBUG
throw new ArgumentException("String '" + text + "' is too long for fixed length " + len + ".");
#endif
}
Array.Copy(unicode, result, copy);
writer.Write(result); writer.Write(result);
} }
// variable length strings
public static void WriteUnicodeAutoLength(this BinaryWriter writer, string text, int maxlen)
{
byte[] result = Encoding.Unicode.GetBytes(text + "\0");
int len = result.Length / 2;
if (len > maxlen)
{
len = maxlen;
result[len * 2 - 2] = 0;
result[len * 2 - 1] = 0;
#if DEBUG
throw new ArgumentException("String '" + text + "' is too long for max length " + maxlen + ".");
#endif
}
writer.Write(result, 0, len * 2);
}
public static string ReadUnicode(this BinaryReader reader, int len) public static string ReadUnicode(this BinaryReader reader, int len)
{ {
byte[] unicode = reader.ReadBytes(len * 2); byte[] unicode = reader.ReadBytes(len * 2);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment