using System;
using System.Collections;
namespace Duck.Net.Game.Protocol.Encoding
{
///
/// Provides Base64 encoding and decoding.
///
public static class base64Encoding
{
///
/// Encodes an integer to a Base64 string.
///
/// The integer to encode.
public static string Encode(int i)
{
try
{
string s = "";
for (int x = 1; x <= 2; x++)
s += (char)((byte)(64 + (i >> 6 * (2 - x) & 0x3f)));
return s;
}
catch { return ""; }
}
///
/// Decodes a Base64 string to to an integer.
///
/// The string to decode.
public static int Decode(string s)
{
try
{
char[] val = s.ToCharArray();
int i = 0;
int t = 0;
for (int v = (val.Length - 1); v >= 0; v--)
{
int j = (int)(byte)((val[v] - 64));
if (t > 0)
j *= (t ^ 64);
i += j;
t++;
}
return i;
}
catch { return 0; }
}
///
/// Returns the first parameter of a string with a Base64 header.
///
/// The content to get the parameter off.
public static string getFirstParameter(string messageContent)
{
try { return messageContent.Substring(2, Decode(messageContent.Substring(0, 2))); }
catch { return ""; }
}
///
/// Searches for a certain parameter in the message content. If the parameter is not found or any errors occur, then "" is returned.
///
/// The message content to search the parameter in.
/// The ID of the parameter to search.
public static string getParameter(string messageContent, int paramID)
{
try
{
int Cycles = 0;
float Max = messageContent.Length / 4;
while (Cycles <= Max)
{
int cycID = Decode(messageContent.Substring(0, 2));
int v = Decode(messageContent.Substring(2, 2));
if (cycID == paramID)
return messageContent.Substring(4, v);
messageContent = messageContent.Substring(v + 4);
Cycles++;
}
return "";
}
catch { return ""; }
}
///
/// Gets all parameters from a string encoded with Base64 headers, and returns it as a string array.
///
/// The content to get the parameters off.
public static string[] getParameters(string messageContent)
{
try
{
ArrayList res = new ArrayList();
while (messageContent != "")
{
int v = Decode(messageContent.Substring(0, 2));
res.Add(messageContent.Substring(2, v));
messageContent = messageContent.Substring(2 + v);
}
return (string[])res.ToArray(typeof(string));
}
catch { return new string[0]; }
}
}
}