PrivateName.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using Jint.Runtime;
  2. namespace Jint.Native;
  3. /// <summary>
  4. /// Private names are a bit like symbols, they follow reference equality so that each one is globally to object,
  5. /// only exception to the rule is get/set pair which should share same private name.
  6. /// </summary>
  7. internal sealed class PrivateName : JsValue, IEquatable<PrivateName>
  8. {
  9. private readonly PrivateIdentifier _identifier;
  10. public PrivateName(PrivateIdentifier identifier) : base(InternalTypes.PrivateName)
  11. {
  12. _identifier = identifier;
  13. Description = identifier.Name;
  14. }
  15. public string Description { get; }
  16. public override string ToString() => _identifier.Name;
  17. public override object ToObject() => throw new NotImplementedException();
  18. public override bool Equals(object? obj)
  19. {
  20. return Equals(obj as PrivateName);
  21. }
  22. public override bool Equals(JsValue? other)
  23. {
  24. return Equals(other as PrivateName);
  25. }
  26. public bool Equals(PrivateName? other)
  27. {
  28. if (ReferenceEquals(null, other))
  29. {
  30. return false;
  31. }
  32. if (ReferenceEquals(this, other))
  33. {
  34. return true;
  35. }
  36. return ReferenceEquals(this, other);
  37. }
  38. public override int GetHashCode()
  39. {
  40. return StringComparer.Ordinal.GetHashCode(_identifier.Name);
  41. }
  42. }
  43. /// <summary>
  44. /// Compares private identifiers by their name instead of reference equality.
  45. /// </summary>
  46. internal sealed class PrivateIdentifierNameComparer : IEqualityComparer<PrivateIdentifier>
  47. {
  48. internal static readonly PrivateIdentifierNameComparer _instance = new();
  49. public bool Equals(PrivateIdentifier? x, PrivateIdentifier? y) => string.Equals(x?.Name, y?.Name, StringComparison.Ordinal);
  50. public int GetHashCode(PrivateIdentifier obj) => StringComparer.Ordinal.GetHashCode(obj.Name);
  51. }