using System;
using System.Text;
using System.Collections;
namespace Woodpecker.Net.Game.Protocol.Encoding
{
///
/// Provides 'wire' encoding and decoding for numbers, better known as 'VL64' or 'LV64'.
///
public static class wireEncoding
{
///
/// Encodes an integer to a VL64 string.
///
/// The integer to encode.
public static string Encode(int i)
{
try
{
byte[] res = new byte[6];
int p = 0;
int sP = 0;
int bytes = 1;
int negativeMask = i >= 0 ? 0 : 4;
i = Math.Abs(i);
res[p++] = (byte)(64 + (i & 3));
for (i >>= 2; i != 0; i >>= 6)
{
bytes++;
res[p++] = (byte)(64 + (i & 0x3f));
}
res[sP] = (byte)(res[sP] | bytes << 3 | negativeMask);
return new ASCIIEncoding().GetString(res).Replace("\0", "");
}
catch { return ""; }
}
///
/// Encodes each integer in the input array and adds it to the 'wire'. Returns the result.
///
/// The integer array to wire up the values of.
public static string Encode(int[] i)
{
string s = "";
foreach (int j in i)
s += Encode(j);
return s;
}
///
/// Encodes a boolean to a VL64 char.
///
/// The boolean to encode.
public static char Encode(bool b)
{
if (b)
return 'I';
else
return 'H';
}
///
/// Decodes a wire encoded string to the first encoded number in the wire.
///
/// The write to decode.
public static int Decode(string s)
{
try
{
char[] u = s.ToCharArray();
int i = u[0] & 3;
int p = 1;
int g = 2;
for (int b = 1; b < (u[p] >> 3 & 7); b++)
{
i |= (u[p] & 0x3f) << g;
g = 2 + 6 * b;
p++;
}
if ((u[0] & 4) == 4)
i *= -1;
return i;
}
catch { return 0; }
}
///
/// Decodes a wire encoded string to a boolean. This is fancy.
///
/// The wire encoded boolean to decode.
public static bool decodeBoolean(string s)
{
return (s == "I");
}
public static int[] decodeWire(string s)
{
try
{
ArrayList res = new ArrayList();
while (s != "")
{
int i = Decode(s);
res.Add(i);
s = s.Substring(Encode(i).Length);
}
return (int[])res.ToArray(typeof(int));
}
catch { return new int[0]; }
}
}
}