2
0

Key.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System.Diagnostics;
  2. using System.Runtime.CompilerServices;
  3. using Jint.Extensions;
  4. namespace Jint;
  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. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  13. private Key(string name)
  14. {
  15. Name = name;
  16. HashCode = Hash.GetFNVHashCode(name);
  17. }
  18. internal readonly string Name;
  19. internal readonly int HashCode;
  20. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  21. public static implicit operator Key(string name) => new(name);
  22. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  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 && string.Equals(a.Name, b.Name, StringComparison.Ordinal);
  28. }
  29. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  30. public static bool operator !=(in Key a, in Key b)
  31. {
  32. return a.HashCode != b.HashCode || !string.Equals(a.Name, b.Name, StringComparison.Ordinal);
  33. }
  34. public bool Equals(Key other)
  35. {
  36. return HashCode == other.HashCode && string.Equals(Name, other.Name, StringComparison.Ordinal);
  37. }
  38. public override bool Equals(object? obj)
  39. {
  40. return obj is Key other && Equals(other);
  41. }
  42. public override int GetHashCode() => HashCode;
  43. public override string ToString() => Name;
  44. }