Extensions.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. namespace Mirror
  5. {
  6. public static class Extensions
  7. {
  8. public static string ToHexString(this ArraySegment<byte> segment) =>
  9. BitConverter.ToString(segment.Array, segment.Offset, segment.Count);
  10. // string.GetHashCode is not guaranteed to be the same on all machines, but
  11. // we need one that is the same on all machines. simple and stupid:
  12. public static int GetStableHashCode(this string text)
  13. {
  14. unchecked
  15. {
  16. int hash = 23;
  17. foreach (char c in text)
  18. hash = hash * 31 + c;
  19. return hash;
  20. }
  21. }
  22. // previously in DotnetCompatibility.cs
  23. // leftover from the UNET days. supposedly for windows store?
  24. internal static string GetMethodName(this Delegate func)
  25. {
  26. #if NETFX_CORE
  27. return func.GetMethodInfo().Name;
  28. #else
  29. return func.Method.Name;
  30. #endif
  31. }
  32. // helper function to copy to List<T>
  33. // C# only provides CopyTo(T[])
  34. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  35. public static void CopyTo<T>(this IEnumerable<T> source, List<T> destination)
  36. {
  37. // foreach allocates. use AddRange.
  38. destination.AddRange(source);
  39. }
  40. #if !UNITY_2021_OR_NEWER
  41. // Unity 2020 and earlier doesn't have Queue.TryDequeue which we need for batching.
  42. public static bool TryDequeue<T>(this Queue<T> source, out T element)
  43. {
  44. if (source.Count > 0)
  45. {
  46. element = source.Dequeue();
  47. return true;
  48. }
  49. element = default;
  50. return false;
  51. }
  52. #endif
  53. }
  54. }