PrivateName.cs 1.8 KB

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