Key.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System.Diagnostics;
  2. using System.Runtime.CompilerServices;
  3. using Jint.Extensions;
  4. namespace Jint
  5. {
  6. /// <summary>
  7. /// Represents a key that Jint uses with pre-calculated hash code
  8. /// as runtime does a lot of repetitive dictionary lookups.
  9. /// </summary>
  10. [DebuggerDisplay("{" + nameof(Name) + "}")]
  11. internal readonly struct Key : IEquatable<Key>
  12. {
  13. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  14. private Key(string name)
  15. {
  16. Name = name;
  17. HashCode = Hash.GetFNVHashCode(name);
  18. }
  19. internal readonly string Name;
  20. internal readonly int HashCode;
  21. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  22. public static implicit operator Key(string name) => new(name);
  23. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  24. public static implicit operator string(Key key) => key.Name;
  25. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  26. public static bool operator ==(in Key a, in Key b)
  27. {
  28. return a.HashCode == b.HashCode && string.Equals(a.Name, b.Name, StringComparison.Ordinal);
  29. }
  30. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  31. public static bool operator !=(in Key a, in Key b)
  32. {
  33. return a.HashCode != b.HashCode || !string.Equals(a.Name, b.Name, StringComparison.Ordinal);
  34. }
  35. public static bool operator ==(in Key a, string b)
  36. {
  37. return string.Equals(a.Name, b, StringComparison.Ordinal);
  38. }
  39. public static bool operator !=(in Key a, string b)
  40. {
  41. return !string.Equals(a.Name, b, StringComparison.Ordinal);
  42. }
  43. public bool Equals(Key other)
  44. {
  45. return HashCode == other.HashCode && string.Equals(Name, other.Name, StringComparison.Ordinal);
  46. }
  47. public override bool Equals(object? obj)
  48. {
  49. return obj is Key other && Equals(other);
  50. }
  51. public override int GetHashCode() => HashCode;
  52. public override string ToString() => Name;
  53. }
  54. }