From: CryptoManiac Date: Fri, 28 Aug 2015 09:33:08 +0000 (+0300) Subject: Hash comparison operations X-Git-Url: https://git.novaco.in/?p=NovacoinLibrary.git;a=commitdiff_plain;h=df0815d3cb055a1a6108ee7b6788a02e822a8fc1 Hash comparison operations --- diff --git a/Novacoin/Hash.cs b/Novacoin/Hash.cs index 05c4567..092db18 100644 --- a/Novacoin/Hash.cs +++ b/Novacoin/Hash.cs @@ -17,11 +17,12 @@ */ using System; +using System.Diagnostics.Contracts; using System.Linq; namespace Novacoin { - public abstract class Hash + public abstract class Hash : IEquatable, IComparable { /// /// Array of digest bytes. @@ -79,6 +80,93 @@ namespace Novacoin return h._hashBytes; } + public bool Equals(Hash item) + { + if (item == null) + { + return false; + } + + return _hashBytes.SequenceEqual((byte[])item); + } + + public int CompareTo(Hash item) + { + Contract.Requires(item.hashSize == hashSize, "Hashes must have the same size."); + Contract.Requires(item != null, "Null reference is not allowed."); + + if (this > item) + { + return 1; + } + else if (this < item) + { + return -1; + } + + return 0; + } + + public static bool operator <(Hash a, Hash b) + { + Contract.Requires(a.hashSize == b.hashSize, "Hashes must have the same size."); + + for (int i = a.hashSize; i >= 0; i--) + { + if (a._hashBytes[i] < b._hashBytes[i]) + return true; + else if (a._hashBytes[i] > b._hashBytes[i]) + return false; + } + + return false; + } + + public static bool operator <=(Hash a, Hash b) + { + Contract.Requires(a.hashSize == b.hashSize, "Hashes must have the same size."); + + for (int i = a.hashSize; i >= 0; i--) + { + if (a._hashBytes[i] < b._hashBytes[i]) + return true; + else if (a._hashBytes[i] > b._hashBytes[i]) + return false; + } + + return false; + } + + public static bool operator >(Hash a, Hash b) + { + Contract.Requires(a.hashSize == b.hashSize, "Hashes must have the same size."); + + for (int i = a.hashSize; i >= 0; i--) + { + if (a._hashBytes[i] > b._hashBytes[i]) + return true; + else if (a._hashBytes[i] < b._hashBytes[i]) + return false; + } + + return false; + } + + public static bool operator >=(Hash a, Hash b) + { + Contract.Requires(a.hashSize == b.hashSize, "Hashes must have the same size."); + + for (int i = a.hashSize; i >= 0; i--) + { + if (a._hashBytes[i] > b._hashBytes[i]) + return true; + else if (a._hashBytes[i] < b._hashBytes[i]) + return false; + } + + return true; + } + public override string ToString() { return Interop.ToHex(Interop.ReverseBytes(_hashBytes));