Key.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 bool Equals(Key other)
  36. {
  37. return HashCode == other.HashCode && string.Equals(Name, other.Name, StringComparison.Ordinal);
  38. }
  39. public override bool Equals(object? obj)
  40. {
  41. return obj is Key other && Equals(other);
  42. }
  43. public override int GetHashCode() => HashCode;
  44. public override string ToString() => Name;
  45. }
  46. }