Skip to content

Instantly share code, notes, and snippets.

@wizzard0
Created March 27, 2014 20:40
Show Gist options
  • Save wizzard0/9818121 to your computer and use it in GitHub Desktop.
Save wizzard0/9818121 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Toliman.Cryptography
{
/// <summary>
/// comparable, equatable byte[]
/// </summary>
public class Identifier : IEquatable<Identifier>, IComparable<Identifier>
{
public byte[] bytes;
public Identifier()
{
bytes = null;
}
public Identifier(byte[] bytes)
{
this.bytes = bytes;
}
public bool Equals(Identifier other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (bytes.Length != other.bytes.Length) return false;
for (int i = 0; i < bytes.Length; i++)
{
if (bytes[i] != other.bytes[i]) return false;
}
return true;
}
public int CompareTo(Identifier other)
{
if (this.bytes == null || other.bytes == null || this.bytes.Length != other.bytes.Length) throw new InvalidOperationException();
for (int i = 0; i < bytes.Length; i++)
{
var cmp = bytes[i].CompareTo(other.bytes[i]);
if (cmp != 0) return cmp;
}
return 0;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Identifier)obj);
}
public override int GetHashCode()
{
if (bytes == null) return 0;
return bytes[0]; // todo better hashcode, 32bit actually. or even murmur
}
public static bool operator ==(Identifier left, Identifier right)
{
return Equals(left, right);
}
public static bool operator !=(Identifier left, Identifier right)
{
return !Equals(left, right);
}
// non-cryptographical-quality RNG
private static readonly Random RandomGen = new Random();
public static Identifier Random()
{
var b = new byte[16];
RandomGen.NextBytes(b);
return new Identifier(b);
}
public override string ToString()
{
try
{
return ByteUtils.FormatHashHex(bytes);
}
catch (Exception e)
{
return e.GetType().Name;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment