Key.cs 1.7 KB

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