From 6be7ed34017f754e540b9a21a9babb9cb6d4e869 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 10 Jan 2017 19:45:24 -0600 Subject: [PATCH] Add default hash code function to use in unit tests. --- TallyCore/Utility/StringUtility.cs | 51 ++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/TallyCore/Utility/StringUtility.cs b/TallyCore/Utility/StringUtility.cs index 2e64f23c..dc11183a 100644 --- a/TallyCore/Utility/StringUtility.cs +++ b/TallyCore/Utility/StringUtility.cs @@ -159,4 +159,55 @@ public int Compare(string x, string y) int IEqualityComparer.GetHashCode(object obj) => GetHashCode(obj as string); } + + public static class DefaultUnicodeHashFunction + { + /// + /// Hashes the provided string using the given CompareOptions. + /// Doing this allows all custom compare options to be applied in determining the hash value. + /// + /// The string. + /// The CompareInfo object doing the unicode-aware comparison. + /// The options to apply to the comparison. + /// Returns the hash code for the string. + public static int HashFunction(string str, CompareInfo info, CompareOptions options) + { + if (info == null) + throw new ArgumentNullException(nameof(info)); + + if (string.IsNullOrEmpty(str)) + return 0; + + SortKey sortOrder = info.GetSortKey(str, options); + + int hash = GetByteArrayHash(sortOrder.KeyData); + + return hash; + } + + /// + /// Generates a hash code for an array of bytes. + /// + /// The key data. + /// Returns a hash code value. + private static int GetByteArrayHash(byte[] keyData) + { + unchecked + { + const int p = 16777619; + int hash = (int)2166136261; + + for (int i = 0; i < keyData.Length; i++) + hash = (hash ^ keyData[i]) * p; + + hash += hash << 13; + hash ^= hash >> 7; + hash += hash << 3; + hash ^= hash >> 17; + hash += hash << 5; + return hash; + } + } + } + }