Skip to content

Instantly share code, notes, and snippets.

@fredeil
Created March 13, 2018 10:00
Show Gist options
  • Save fredeil/f6a56bf2537c2aae2ba009fcdbadae27 to your computer and use it in GitHub Desktop.
Save fredeil/f6a56bf2537c2aae2ba009fcdbadae27 to your computer and use it in GitHub Desktop.
public class ChickenCodec
{
static readonly char[] feed = { 'C', 'H', 'I', 'C', 'K', 'E', 'N', '.' };
private static Lazy<byte[]> charFeed = new Lazy<byte[]>(() =>
{
byte[] feed = new byte[256 * 8];
unsafe
{
fixed (byte* feedptr = feed)
{
for (int i = 0; i < 256; i++)
{
SeedFeed(feedptr + i * 8, (byte)i);
}
}
}
return feed;
});
private static unsafe void Encode(byte* input, int length, byte* output)
{
if (length == 0)
{
return;
}
byte* inend = input + length;
byte* outptr = output;
byte* inptr = input;
byte[] feed = charFeed.Value;
fixed (byte* feedptr = feed)
{
while (inptr < inend)
{
byte c = *inptr++;
byte* btptr = feedptr + (c * 8);
for (int i = 0; i < 7; i++)
{
*outptr++ = *(btptr + i);
}
if (*(btptr + 7) != 0)
{
*outptr++ = *(btptr + 7);
}
*outptr++ = (byte)' ';
}
}
}
private static unsafe void SeedFeed(byte* feed, byte seed)
{
for (byte i = 0; i < 8; i++)
{
byte mask = (byte)(1 << i);
*feed++ = (byte)(ChickenCodec.feed[i] + (((seed & mask) > 0) ? 0 : 0x20));
}
if (*(feed - 1) != (byte)'.')
{
*(feed - 1) = 0;
}
}
private static unsafe void Decode(byte* input, int length, byte* output)
{
int position = 0;
byte saved = 0;
byte* inend = input + length;
byte* outptr = output;
byte* inptr = input;
while (inptr < inend)
{
byte c = *inptr++;
if (c == ' ' || position >= 8)
{
if (position > 6)
{
*outptr++ = saved;
}
position = 0;
saved = 0;
}
else
{
saved |= (byte)(((c >= 'A') && (c <= 'Z') || c == '.') ? (1 << position) : 0);
position++;
}
}
if (position > 6)
{
*outptr++ = saved;
}
}
static string Sanitized(byte[] bytes)
=> Encoding.UTF8.GetString(bytes).TrimEnd('\u0000').TrimEnd();
public static unsafe string Decode(string body)
{
byte[] input = Encoding.UTF8.GetBytes(body);
byte[] outputBuffer = new byte[(int)Math.Ceiling((double)body.Length / 8)];
fixed (byte* inptr = input)
{
fixed (byte* outptr = outputBuffer)
{
Decode(inptr, input.Length, outptr);
}
}
return Sanitized(outputBuffer);
}
public static unsafe string Encode(string body)
{
byte[] input = Encoding.UTF8.GetBytes(body);
byte[] outputBuffer = new byte[body.Length * 9];
fixed (byte* inptr = input)
{
fixed (byte* outptr = outputBuffer)
{
Encode(inptr, input.Length, outptr);
}
}
return Sanitized(outputBuffer);
}
}
@fredeil
Copy link
Author

fredeil commented Mar 13, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment