diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-08-06 09:35:30 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2021-08-06 09:35:30 -0500 |
| commit | ebe5af7084001012630a2e030247cf2c23e5a67d (patch) | |
| tree | bb0660a1c776f7d2e16e233f09472153fe5f4714 /src/slskd | |
| parent | 7d40ac22de820019a3c6f4722ea8c139018308f2 (diff) | |
| download | slskd-ebe5af7084001012630a2e030247cf2c23e5a67d.tar.gz | |
add ReplaceFirst() and GetStableHashCode()
Diffstat (limited to 'src/slskd')
| -rw-r--r-- | src/slskd/Common/Extensions.cs | 49 |
1 files changed, 49 insertions, 0 deletions
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 @@ -69,6 +69,55 @@ namespace slskd } /// <summary> + /// Replaces the first occurance of <paramref name="phrase"/> in the string with <paramref name="replacement"/>. + /// </summary> + /// <param name="str">The string on which to perform the replacement.</param> + /// <param name="phrase">The phrase or substring to replace.</param> + /// <param name="replacement">The replacement string.</param> + /// <returns>The string, with the desired phrase replaced.</returns> + 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); + } + + /// <summary> + /// Computes a stable/consistent hash code for strings. + /// </summary> + /// <remarks> + /// https://stackoverflow.com/questions/5154970/how-do-i-create-a-hashcode-in-net-c-for-a-string-that-is-safe-to-store-in-a + /// </remarks> + /// <param name="str">The string for which the hash code is to be computed.</param> + /// <returns>The hash code</returns> + 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); + } + } + + /// <summary> /// Deeply compares this object with the specified object and returns a list of properties that are different. /// </summary> /// <param name="left">The left side of the comparison.</param> |
