Key.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.CompilerServices;
  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. private Key(string name)
  14. {
  15. Name = name;
  16. HashCode = name.GetHashCode();
  17. }
  18. internal readonly string Name;
  19. internal readonly int HashCode;
  20. public static implicit operator Key(string name)
  21. {
  22. return new Key(name);
  23. }
  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 && a.Name == b.Name;
  29. }
  30. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  31. public static bool operator !=(in Key a, in Key b)
  32. {
  33. return a.HashCode != b.HashCode || a.Name != b.Name;
  34. }
  35. public static bool operator ==(in Key a, string b)
  36. {
  37. return a.Name == b;
  38. }
  39. public static bool operator !=(in Key a, string b)
  40. {
  41. return a.Name != b;
  42. }
  43. public bool Equals(Key other)
  44. {
  45. return HashCode == other.HashCode && Name == other.Name;
  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. }