Key.cs 1.8 KB

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