by Mwwhited
29. April 2009 02:04
Using this struct you may implicitly cast string's or char[]'s to "MyString" and it has one current overridden operator... and that would be XOR. Also wanting an insane excuse to play with unsafe code I decided to do it with pointers. It’s may not be the most graceful code in the world… but hey quick and dirty is just as fun.
public struct MyString
{
public MyString(string value) { _value = value.ToCharArray(); }
public MyString(char[] value) { _value = value; }
private char[] _value;
public string Value
{
get { return new string(_value); }
private set { _value = value.ToCharArray(); }
}
public char[] Array
{
get { return _value; }
private set { _value = value; }
}
public override string ToString()
{
return Value;
}
public static implicit operator MyString(char[] input)
{
return new MyString(input);
}
public static implicit operator char[](MyString input)
{
return input.Array;
}
public static implicit operator MyString(string input)
{
return new MyString(input);
}
public static implicit operator string(MyString input)
{
return input.Value;
}
public static MyString operator ^(MyString ileft, MyString iright)
{
var left = ileft.Array;
var right = iright.Array;
if (left == null || right == null)
return new MyString();
if (left.Length == 0)
return new MyString(right);
if (right.Length == 0)
return new MyString(left);
var biggest = new char[left.Length > right.Length ? left.Length : right.Length];
unsafe
{
fixed (char* fl = left)
{
fixed (char* fr = right)
{
int bLen = biggest.Length;
int lLen = left.Length;
int rLen = right.Length;
fixed (char* fb = biggest)
{
char* l = fl, r = fr, b = fb;
for (int i = 0; i < bLen; i++)
{
(*b++) = (char)((byte)(*l++) ^ (byte)(*r++));
if (i > 0)
{
if (i % lLen == 0) l -= (lLen + 1);
if (i % rLen == 0) r -= (rLen + 1);
}
}
}
}
}
}
return new MyString(biggest);
}
}
b1cc9739-6966-476f-8840-9cadddfcbada|0|.0
Tags: c#, insane