From ebe5af7084001012630a2e030247cf2c23e5a67d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Aug 2021 09:35:30 -0500 Subject: add ReplaceFirst() and GetStableHashCode() --- src/slskd/Common/Extensions.cs | 49 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 51c0d147..0da0e128 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -68,6 +68,55 @@ namespace slskd return props; } + /// + /// Replaces the first occurance of in the string with . + /// + /// The string on which to perform the replacement. + /// The phrase or substring to replace. + /// The replacement string. + /// The string, with the desired phrase replaced. + public static string ReplaceFirst(this string str, string phrase, string replacement) + { + int pos = str.IndexOf(phrase); + + if (pos < 0) + { + return str; + } + + return str.Substring(0, pos) + replacement + str.Substring(pos + phrase.Length); + } + + /// + /// Computes a stable/consistent hash code for strings. + /// + /// + /// https://stackoverflow.com/questions/5154970/how-do-i-create-a-hashcode-in-net-c-for-a-string-that-is-safe-to-store-in-a + /// + /// The string for which the hash code is to be computed. + /// The hash code + public static int GetStableHashCode(this string str) + { + unchecked + { + int hash1 = 5381; + int hash2 = hash1; + + for (int i = 0; i < str.Length && str[i] != '\0'; i += 2) + { + hash1 = ((hash1 << 5) + hash1) ^ str[i]; + if (i == str.Length - 1 || str[i + 1] == '\0') + { + break; + } + + hash2 = ((hash2 << 5) + hash2) ^ str[i + 1]; + } + + return hash1 + (hash2 * 1566083941); + } + } + /// /// Deeply compares this object with the specified object and returns a list of properties that are different. /// -- cgit v1.2.3